boost ::生成线程时的线程运行时错误
我有一个项目,我们想提供使用线程来加速一切。 我们希望能够调用此函数在单个线程:boost ::生成线程时的线程运行时错误
Request& Filter::processRequest(Request& req)
所以我在lambda表达式包装的功能,可以访问返回值。
我现在得到以下运行时错误:
glibc detected ... double free or corruption (!prev): ...
当我取消,我的线程添加到组中的一切工作正常就行了。
boost::thread_group thread;
for (std::set<boost::shared_ptr<Filter> >::iterator i = sources_.begin();
i != sources_.end(); ++i) {
Request ret
thread.add_thread(new boost::thread(boost::lambda::var(ret) =
(*i)->processRequest(req)));
req+=ret;
...
}
thread.join_all();
什么可能是此运行时错误的原因。还是有另一种方法可以将这个函数放入单独的线程中?
如果这种技术完全可以工作,则需要多个可以稳定引用的ret值(每个执行线程一个)。而且你必须等到你的线程连接完成后再使用这些值。
一个简单的修改,你可以尝试只是在vector<Request> retValues
的循环之外创建一个向量,然后每次向该向量添加一个元素,并传递该元素的引用。那么如果你等到连接使用这些值之后,也许它会起作用?
boost::thread_group thread;
vector<Request> retValues;
for (std::set<boost::shared_ptr<Filter> >::iterator i = sources_.begin();
i != sources_.end(); ++i) {
retValues.push_back(0);
thread.add_thread(new boost::thread(
boost::lambda::var(retValues.back()) =
(*i)->processRequest(req)));
...
}
thread.join_all();
// retValues safe to use here...
(注:使用boost::lambda
可能没有必要,你可以使用boost ::绑定连接到存储结果的工人阶级:
Getting return value from a boost::threaded member function?
......但实际上,不管你需要一个单独的变量来存储每个线程的结果......它的生命周期足以让线程能够写入它。)
我不认为从'boost :: thread'派生是一个好主意,因为它没有虚拟析构函数。还是我得到这个错误? – tune2fs
嗯,看起来你是对的。奇怪的。我想这与QThread完全不同......让我再看一遍...... http://doc.qt.nokia.com/latest/qthread.html#details – HostileFork
感谢您的回复。我会试一试。我也会看看QThreads。 – tune2fs
你期待什么'boost :: lambda :: var(ret)=(* i) - > processRequest(req)'做什么?你在一个循环中添加N个线程...那么N个稳定的“ret”位置通过引用存储结果在哪里? – HostileFork
我在上面的代码中添加了我想用ret做的事情。我想将它添加到需求。我认为ret的副本放在每一个线程中,或者这个假设是错误的? – tune2fs
我不是'boost :: lambda'用户,我只用'boost :: thread'修饰了一下,所以我其实并不了解你的方法(尽管它让我觉得“没有办法可以工作“)。如果你启动了一个异步任务,那么如果没有完成它的计算,就不能使用它的结果。并且文档建议'boost :: lambda :: var'通过引用来引用一个参数(如果它“复制”它,调用者将如何连接到副本?)...所以你真的只有一个'Request ret; '循环的每次迭代都是“活着的”。 – HostileFork