【Boost】boost库中thread多线程详解6——线程组简单例子
生活随笔
收集整理的這篇文章主要介紹了
【Boost】boost库中thread多线程详解6——线程组简单例子
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? ? 如果你需要創建幾個線程,考慮使用一個線程組對象thread_group來組織它們。一個thread_group對象可以使用多種方法管理線程。首先,可以使用一個指向動態創建的線程對象的指針作為參數來調用add_thread方法,將這個線程加入線程組。也可以直接使用線程組類的create_thread方法,可不先創建線程而直接把線程加入到線程組中。當線程組對象的析構函數被調用時,它將刪除(delete)所有這些通過add_thread方法加入的線程指針。所以,只能將堆上的線程對象指針通過add_thread方法加入線程組。remove_thread方法從線程組刪除某個線程的指針,但是我們仍需負責把線程本身內存釋放掉。線程組對象的成員方法join_all方法等待線程組中所有線程結束,才返回。
例子:
namespace { struct Run { void operator()(void) { std::cout << __FUNCTION__ << std::endl; } }; void run(void) { std::cout << __FUNCTION__ << std::endl; } } void test_thread_group2() { Run r; boost::thread_group grp; // 兩種方法通過線程組增加線程 boost::thread *t = grp.create_thread(r); // 使用create_thread grp.add_thread(new boost::thread(run)); // 使用add_thread grp.join_all(); // 兩種方法移除線程 grp.remove_thread(t); // delete t; }總結
以上是生活随笔為你收集整理的【Boost】boost库中thread多线程详解6——线程组简单例子的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Boost】boost库中thread
- 下一篇: 【Boost】boost库中thread