C 11多執行緒程式設計 2 執行緒啟動,建立,結束

2021-10-24 07:28:47 字數 1083 閱讀 2476

#include

#include

using namespace std;

//自己建立的執行緒也要從乙個函式(初始函式)開始執行

void myprint()

class ta

ta(const ta& ta) :m_i(ta.m_i)

~ta()

void operator()()//不能帶引數

};int main()

else

cout << "主線程收尾,最終主線程安全退出1" << endl;

cout << "主線程收尾,最終主線程安全退出2" << endl;

cout << "主線程收尾,最終主線程安全退出3" << endl;

cout << "主線程收尾,最終主線程安全退出4" << endl;

cout << "主線程收尾,最終主線程安全退出5" << endl;

/*二:其他建立執行緒的手法

(2.1)用類,以及問題範例

問題:一旦呼叫了detach(),那我主線程執行結束了,我這裡用的這個ta物件還在嗎?(物件不在了)

答案:這個物件實際上是被賦值到執行緒中去;所以執行完主線程後,ta會被銷毀,但是所賦值的ta物件依舊存在

所以,只要這個ta類物件裡面沒有引用,沒有指標,那麼就不會產生問題。

*/int myi = 6;

ta ta(myi);

thread mytobj3(ta);

mytobj3.detach();

//(2.2)用lambda表示式建立

auto mylamthread = ;

thread mytobj4(mylamthread);

mytobj4.join();

cout << "i love china" << endl;

cout << "i love china" << endl;

cout << "i love china" << endl;

cout << "i love china" << endl;

cout << "i love china" << endl;

return 0;

C 11 多執行緒程式設計 執行緒的建立

1 通過函式指標建立執行緒 includevoid counter int id,int numiterations 過載 操作符 void operator const int main 建構函式不含引數 std thread t2 counter 將導致編譯錯誤,c 會將std thread t...

多執行緒(c 11) 建立執行緒

c 11 中建立執行緒非常簡單 include include using namespace std void thread func void thread func2 int i int main int argc,tchar argv thread t2 return 0 首先包含標頭檔案,...

C 11多執行緒程式設計

1 c 11新標準引入了五個標頭檔案支援多執行緒程式設計,分別如下 該標頭檔案 該標頭檔案主要宣告了std thread類,其中std this thread 提供了一些輔助函式 命名空間也在該標頭檔案中 該標頭檔案主要宣告了std atomic和std atomic flag兩個類,另外還宣告了一...