我正在尝试编写一个相当简单的线程应用程序,但我对 boost 的线程库很陌生。我正在开发的一个简单的测试程序是:
#include <iostream>
#include <boost/thread.hpp>
int result = 0;
boost::mutex result_mutex;
boost::thread_group g;
void threaded_function(int i)
{
for(; i < 100000; ++i) {}
{
boost::mutex::scoped_lock lock(result_mutex);
result += i;
}
}
int main(int argc, char* argv[])
{
using namespace std;
// launch three threads
boost::thread t1(threaded_function, 10);
boost::thread t2(threaded_function, 10);
boost::thread t3(threaded_function, 10);
g.add_thread(&t1);
g.add_thread(&t2);
g.add_thread(&t3);
// wait for them
g.join_all();
cout << result << endl;
return 0;
}
但是,当我编译并运行该程序时,我得到的输出是
$ ./test
300000
test: pthread_mutex_lock.c:87: __pthread_mutex_lock: Assertion `mutex->__data.__owner == 0' failed.
Aborted
显然,结果是正确的,但我担心这个错误消息,特别是因为具有基本相同结构的实际程序卡在 join_all() 点。有人可以向我解释发生了什么事吗?有没有更好的方法来做到这一点,即启动多个线程,将它们存储在外部容器中,然后等待它们全部完成,然后再继续程序?
感谢您的帮助。
我认为你的问题是由程序退出时调用的 thread_group 析构函数引起的。线程组想要负责销毁你的线程对象。另请参见提升::线程组 http://www.boost.org/doc/libs/1_39_0/doc/html/thread/thread_management.html#thread.thread_management.threadgroup.destructor文档。
您正在堆栈上创建线程对象作为主函数范围内的局部变量。因此,当程序退出并且 thread_group 尝试删除它们时,它们已经被破坏。
作为解决方案,请使用以下命令在堆上创建线程对象new并让 thread_group 负责它们的销毁:
boost::thread *t1 = new boost::thread(threaded_function, 10);
...
g.add_thread(t1);
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)