我正在尝试编写一个相当简单的线程应用程序,但对 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() 点。有人可以向我解释发生了什么吗?有没有更好的方法来做到这一点,即启动多个线程,将它们存储在外部容器中,然后等待它们全部完成后再继续程序?
谢谢你的帮助。