參考cplusplus
參考cppreference
0.線程的基礎知識
0.1 線程的狀態(tài)
0.2 c++線程的joinable和detached狀態(tài)
- joinable
一個可結合的線程能夠被其他線程收回其資源和殺死;在被其他線程回收之前竣灌,它的存儲器資源(如棧)是不釋放的妥泉。
- detached
一個分離的線程是不能被其他線程回收或殺死的鳖昌,它的存儲器資源在它終止時由系統(tǒng)自動釋放。
0.3 兩種等待線程結束的方式
- 當線程啟動后抡谐,一定要在和線程相關聯(lián)的thread銷毀前,確定以何種方式等待線程執(zhí)行結束。
1)detach方式也祠,啟動的線程自主在后臺運行,當前的代碼繼續(xù)往下執(zhí)行近速,不等待新線程結束诈嘿。
2)join方式堪旧,等待啟動的線程完成,才會繼續(xù)往下執(zhí)行奖亚。
1.構造函數(shù)
- 注意第二個構造函數(shù):
新產(chǎn)生的線程會調用fn函數(shù)淳梦,該函數(shù)的參數(shù)由args給出。
template <class Fn, class... Args>
explicit thread (Fn&& fn, Args&&... args);
2.賦值操作
// move (1)
thread& operator= (thread&& rhs) noexcept;
// copy [deleted] (2)
thread& operator= (const thread&) = delete;
// example for thread::operator=
#include <iostream> // std::cout
#include <thread> // std::thread, std::this_thread::sleep_for
#include <chrono> // std::chrono::seconds
void pause_thread(int n)
{
std::this_thread::sleep_for (std::chrono::seconds(n));
std::cout << "pause of " << n << " seconds ended\n";
}
int main()
{
std::thread threads[5]; // 該thread對象不是joinable
std::cout << "Spawning 5 threads...\n";
for (int i=0; i<5; ++i)
threads[i] = std::thread(pause_thread,i+1); // move-assign threads
std::cout << "Done spawning threads. Now waiting for them to join:\n";
for (int i=0; i<5; ++i)
threads[i].join();
std::cout << "All threads joined!\n";
return 0;
}
3.判斷對象是否是joinable
- 如下三種情況的thread對象不是joinable
1)默認構造的
2)對象進行了移動(構建其他對象昔字,或者賦值)
3)已經(jīng)調用了join和detach
bool joinable() const noexcept;