Bdb 在并发写入时崩溃,c++ linux/osx
Posted
技术标签:
【中文标题】Bdb 在并发写入时崩溃,c++ linux/osx【英文标题】:Bdb crashes on concurrent write, c++ linux/osx 【发布时间】:2011-05-07 04:57:01 【问题描述】:我在使用 bdb 和锁定机制时遇到问题。
以下代码会导致段错误,或者看起来像死锁/无限循环
#include <iostream>
#include "db_cxx.h"
#include <boost/thread.hpp>
using namespace std;
void thread_instance(Db* db, double start)
double s = start;
double finish = start + 5000;
for(int x=s; x < finish ; x++)
Dbt key(&x, sizeof(double));
Dbt ddata(&x, sizeof(double));
db->put(NULL, &key, &ddata, 0);
int
compare_double(DB *dbp, const DBT *a,const DBT *b)
double ai, bi;
memcpy(&ai, a->data, sizeof(double));
memcpy(&bi, b->data, sizeof(double));
return (ai > bi ? 1 : ((ai < bi) ? -1 : 0));
int main()
system("rm data/*");
u_int32_t env_flags = DB_CREATE | DB_INIT_MPOOL | DB_INIT_CDB;
DbEnv* env = new DbEnv(0);
env->set_cachesize(0, 2000000, 1);
u_int32_t m = 0;
env->open("data/", env_flags, 0);
Db* db = new Db(env, 0);
db->set_bt_compare(compare_double);
db->set_flags(DB_DUPSORT);
db->set_pagesize(32768);
db->set_dup_compare(compare_double);
u_int32_t oFlags = DB_CREATE;
try
db->open(NULL, "db", NULL, DB_BTREE, oFlags, 0);
catch (DbException &e)
catch (std::exception &e)
vector<boost::thread*> threads;
for(int x=0; x < 3; x++)
threads.push_back(new boost::thread(boost::bind(&thread_instance, db, (x *5000))));
for(int x=0; x < threads.size(); x++)
threads[x]->join();
;
我也尝试过 DB_INIT_LOCK,但结果相同。
堆栈轨迹:
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000019
[Switching to process 34816]
0x00000001002e36a7 in __bamc_put ()
(gdb) ba
#0 0x00000001002e36a7 in __bamc_put ()
#1 0x0000000100386689 in __dbc_iput ()
#2 0x0000000100387a6c in __dbc_put ()
#3 0x0000000100383092 in __db_put ()
#4 0x0000000100397888 in __db_put_pp ()
#5 0x00000001002cee59 in Db::put ()
#6 0x0000000100001f88 in thread_instance (db=0x1007006c0, start=5000) at src/main.cpp:16
#7 0x0000000100698254 in thread_proxy ()
#8 0x00007fff80cb9456 in _pthread_start ()
#9 0x00007fff80cb9309 in thread_start ()
有人知道这里会发生什么吗?
【问题讨论】:
【参考方案1】:我建议在 db->open 之后检查错误,如果有则打印消息而不是跳过它: 捕捉(DbException &e) cerr
另外,您似乎没有正确定义标志:至少 DB_THREAD 是必需的,因为您在线程中使用它
【讨论】:
以上是关于Bdb 在并发写入时崩溃,c++ linux/osx的主要内容,如果未能解决你的问题,请参考以下文章
C++ 类文件未在 Linux OS 上运行的 Eclipse Mars 中构建二进制文件
如何在 C++ 中的 unordered_map 的并发读取和锁定单线程写入之间交替