C 使用thread類進行多執行緒程式設計

2022-07-01 12:21:09 字數 1971 閱讀 1980

c++11中引入了乙個用於多執行緒操作的thread類,簡單多執行緒示例:

#include #include #include using namespace std;

void thread01()

}void thread02()}

int main()

system("pause");

}

輸出:

兩個子執行緒並行執行,join函式會阻塞主流程,所以子執行緒都執行完成之後才繼續執行主線程。可以使用detach將子執行緒從主流程中分離,獨立執行,不會阻塞主線程:

#include #include #include using namespace std;

void thread01()

}void thread02()}

int main()

system("pause");

}

輸出:

使用detach的主線程和兩個子執行緒並行執行。

帶參子執行緒

在繫結的時候也可以同時給帶引數的執行緒傳入引數:

#include #include #include using namespace std;

//定義帶引數子執行緒

void thread01(int num)

}void thread02(int num)}

int main()

system("pause");

}

輸出跟上例輸出一樣:

多執行緒資料競爭

多個執行緒同時對同一變數進行操作的時候,如果不對變數做一些保護處理,有可能導致處理結果異常:

#include #include #include using namespace std;

int totalnum = 100;

void thread01()

}void thread02()}

int main()

輸出結果(部分):

有兩個問題,一是有很多變數被重複輸出了,而有的變數沒有被輸出;二是正常情況下每個執行緒輸出的資料後應該緊跟乙個換行符,但這裡大部分卻是另乙個執行緒的輸出。

這是由於第乙個執行緒對變數操作的過程中,第二個執行緒也對同乙個變數進行各操作,導致第乙個執行緒處理完後的輸出有可能是執行緒二操作的結果。

針對這種資料競爭的情況,可以使用執行緒互斥物件mutex保持資料同步。

mutex類的使用需要包含標頭檔案mutex:

#include #include #include #include using namespace std;

mutex mu; //執行緒互斥物件

int totalnum = 100;

void thread01()

}void thread02()}

int main()

多執行緒中加入mutex互斥物件之後輸出正常:

後記:c++11之前,windows系統為我們提供了相關api,我們可以使用他們來進行多執行緒程式設計。

c++11 thead 多執行緒類

C 多執行緒程式設計 使用Thread類建立執行緒

使用thread類可以建立和控制線程。使用thread類需要引入系統的system.threading命名空間。下面簡單示例 using system using system.collections.generic using system.linq using system.text using...

C 中的多執行緒使用 Thread 類

好文,現在c 已經建議擯棄使用 suspend,resume 暫停 恢復執行緒,也盡量少用 abort方法中斷乙個執行緒.建議使用執行緒的同步手段有 mutex manualresetevent autoresetevent,monitor.下面再對此進行詳細描述.thread類的建構函式有2類 一...

C 中的多執行緒使用 Thread 類

現在c 已經建議擯棄使用 suspend,resume 暫停 恢復執行緒,也盡量少用 abort方法中斷乙個執行緒.建議使用執行緒的同步手段有 mutex manualresetevent autoresetevent,monitor.下面再對此進行詳細描述.thread類的建構函式有2類 一種是不...