C++多線程(一)
#include<iostream>
#include<thread>
using namespace std;
void func()
{
cout << "子線程開始了" << endl;
cout << "......" << endl;
cout << "子線程結束了" << endl;
}
int main()
{
cout << "主線程開始了" << endl;
thread th(func);
th.join();
cout << "主線程結束了" << endl;
getchar();
return 0;
}
輸出:

分析:

主線程先執行,到了th.join()時阻塞住,創建了一個新的子線程,執行子線程,子線程執行完,阻塞解除,執行主線程至結束。
對以上代碼進行改動:
#include<iostream>
#include<thread>
using namespace std;
void func()
{
cout << "子線程開始了" << endl;
cout << "......" << endl;
cout << "子線程結束了" << endl;
}
int main()
{
cout << "主線程開始了" << endl;
thread th(func);
th.detach();
cout << "主線程結束了" << endl;
getchar();
return 0;
}
輸出結果:

分析:
把join換成detach作用是使得主線程不會阻塞等待子線程執行結束。也就是說主線程可以先執行結束。而在子線程中的thread對象會被C++運行時庫接管,也就是說運行時庫負責清理子線程相關的資源。
注意點:
正對一個線程,一旦調用了detach,則不能再次調用join,否則會導致程序運行異常。
利用joinable可以判斷是否可以調用join或者detach

浙公網安備 33010602011771號