我想寫一個相當簡單的線程應用程序,但是對於boost的線程庫來說是新的。一個簡單的測試程序,我的工作是:(簡單)提升thread_group問題
#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。否則,如果在干預代碼中出現錯誤(即拋出),則會泄漏該線程。 – 2009-08-08 13:10:05
是的,這似乎是這種情況,也是大型程序中的錯誤原因。現在的工作示例使用: //啓動三個線程 g.add_thread(new boost :: thread(threaded_function,10)); g.add_thread(new boost :: thread(threaded_function,10)); g.add_thread(new boost :: thread(threaded_function,10)); – RandomGuy 2009-08-17 16:54:22
確保不泄漏它的好方法是使用std :: unique_ptr或類似的解決方案,並使用ptr.get()將該線程提供給group_thread。 –
Klaim
2011-07-19 22:46:38