C 11中多執行緒的建立

2022-07-21 01:45:16 字數 1173 閱讀 3335

c++11語言本身支援了多執行緒。在以往,linux和windows下建立執行緒的方式是不一樣的,這也就降低了程式的可移植性和可讀性。

以前對多前程的了解不多,最近在看一些c++11的新特性,看到多執行緒這裡,故做以記錄。

建立執行緒的兩種方式:

1.執行緒的入口必須是乙個函式,那麼就可以用函式的方式:

1)匯入執行緒庫函式:#include

2)使用thread mytobj(printf)建立乙個執行緒。printf是函式名,也就是執行緒的入口位址

1

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

2void

mythread()

13int main() //

主線程14

21else

2225

mytobj.join();

26//

mytobj.detach();

27if

(mytobj.joinable())

2831

else

3235 }

2.使用類物件來建立執行緒

1

//使用類物件來建立執行緒

2int data = 10;3

char a = 'a'

;4char *p = &a;

5 std::string str = "

you are pretty good!!!!!!!!!!!!!!!";

6creatthreadclass ctc(data,p);

7thread mytobj(ctc);8if

(mytobj.joinable())912

else

1316

mytobj.detach();

1718

if(mytobj.joinable())

1922

else

2326 std::string str222 = getins::getinstance()->lastfunc(str);

27 cout << str222 <28 }

使用類物件來建立執行緒,必要要過載()運算子,在這個過載函式中,呼叫其他的函式。

1

void

operator

()()

多執行緒(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中多執行緒

std lock guard是raii模板類的簡單實現,功能簡單。std lock guard 在建構函式中進行加鎖,析構函式中進行解鎖。鎖在多執行緒程式設計中,使用較多,因此c 11提供了lock guard模板類 在實際程式設計中,我們也可以根據自己的場景編寫resource guardraii...

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

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