【C++】detach和join的區別
阿新 • • 發佈:2021-02-19
首先看一下join的簡單示例:
//joinTest.cc
#include<iostream>
#include<thread>
class Obj
{
public:
Obj() {std::cout << "hello ";}
~Obj() {std::cout << "world\n";}
};
void joinWorker()
{
Obj obj;
std::this_thread:: sleep_for(std::chrono::seconds(2));
}
int main()
{
std::thread j(joinWorker);
j.join();
std::this_thread::sleep_for(std::chrono::seconds(1));
return 0;
}
執行結果為:
接著把join換成detach試試:
//detachTest.cc
#include<iostream>
#include<thread>
class Obj
{
public:
Obj() {std:: cout << "hello ";}
~Obj() {std::cout << "world\n";}
};
void detachWorker()
{
Obj obj;
std::this_thread::sleep_for(std::chrono::seconds(2));
}
int main()
{
std::thread d(detachWorker);
d.detach();
std::this_thread::sleep_for(std::chrono::seconds (1));
return 0;
}
輸出結果為:
顯而易見的是,在執行joinWorker()時,函式內Obj物件的構造和解構函式都被成功呼叫,但在執行detachWorker()時,Obj物件只調用了建構函式而沒有成功呼叫解構函式。
這是由於,join()是讓使用者手動管理執行緒,會阻塞當前執行緒直到*this所標識的執行緒結束;detach()不會阻塞當前執行緒,通過將thread物件分離執行緒,讓執行緒獨立執行,並且當執行緒執行結束後釋放執行緒的所有資源。
回過頭來看例子,由於我們在joinWorker()/detachWorker()中讓該執行緒延遲等待2秒,然後在主執行緒中只等待1秒,這導致我們的j/d執行緒的執行時間會大於主執行緒執行時間。
由於j.join()會阻塞主執行緒,所以j執行緒依舊會在主執行緒結束前結束;但d.detach()並不會阻塞主執行緒,所有在主執行緒結束後d執行緒依然沒有結束,所以直到main函式退出,d執行緒中的Obj物件的解構函式還沒有被呼叫。