gpt4 book ai didi

c++ - 使用 boost 库编写多线程程序时出错

转载 作者:行者123 更新时间:2023-11-28 02:54:07 25 4
gpt4 key购买 nike

我创建了两个线程,它们将并行执行一段代码。我想在两个线程完成执行后运行另一个方法。我尝试了 join() 和 timed_join(),但它不起作用。我我正在使用 boost 线程类。请在下面找到我的代码:

代码:

A class:
A a;
boost::thread t(boost::bind(&A::method1,&a,s1,e1));//Call method1 using two parameters s1 and e1.boost bind is used to call class methods
boost::thread t1(boost::bind(&A::method1,&a,s2,e2));//Call method1 using two parameters s2 and e2.boost bind is used to call class methods.
t.join();
t1.join();
methodToBeExecutedAfterThreadExec();

让我知道如何使用线程并行执行 method1,然后我必须调用 methodToBeExecutedAfterThreadExec() 方法。

提前致谢。

编辑 1:

void method1(int start,int end)
{
vector< vector<string> >::iterator row;
vector<string>::iterator col;
db.onAutoVacuumMode();//Vacuum mode is set to true which eliminates fragmentation
db.startTransaction();//Starts the transaction which does the stuff in a batch wise
for (row = dupViewResults.begin()+start; row != dupViewResults.begin()+end; ++row) {

std::string filedata=readFileDataInStr(row->at(0));
int x = boost::lexical_cast<int>( row->at(1) );
long long int fileCRC32=MurmurHash(filedata.c_str(),x,0);
std::string strCRC32=std::to_string(fileCRC32);
std::string query="update duplicatesview set CRC32='"+strCRC32+"' where Filepath='"+row->at(0)+"'";
char* charQuery = &query[0];
db.fireSQLQuery(charQuery,results);
}
db.endTransaction();
}

上面的代码会读取 vector dupViewResults(已经由我的代码填充),然后更新 View ,然后在事务中触发 sql 查询。谢谢

最佳答案

根据您的评论,听起来您的 db 成员不是线程安全的。例如,当您对其调用 endTransaction 时,它无法知道要结束哪个事务。

您有三个选择,根据您未提供的详细信息,其中一些可能不起作用:

  1. 每个线程都可以有自己的数据库对象。

  2. 数据库对象可以返回后续函数采用的“事务”对象。每个线程都可以分配自己的事务对象。

  3. 数据库对象可以将操作与调用它的线程相关联,知道 endTransaction 结束由同一线程启动的事务。

如果要同时从多个线程调用数据库,数据库必须是线程安全的。

关于c++ - 使用 boost 库编写多线程程序时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22400967/

25 4 0
文章推荐: javascript - 如何使用我刚刚放入 jQuery UI Sortable 中的任何表行触发函数?
文章推荐: javascript - 图表不适合
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com