C++多執行緒程式設計回顧(1)(C11)
阿新 • • 發佈:2019-02-04
1、執行緒join&detach,程式碼示例如下(實測,可用):
#include <iostream>
#include <thread>
#include <windows.h>//列印執行緒號所引,僅限Windows平臺
using namespace std;
void Do(int num, const char* c) {
cout << "num: " << num << "c: " << c << endl;
}
void main() {
const int nThread = 10;
thread thThread[nThread];
for (int i = 0; i < nThread; i++) {
/*建立執行緒 ,其中後面的Do為執行緒要執行的函式,再後面的兩個實參為該函式傳遞的引數*/
thThread[i] = thread(&Do,i,"hello");
//列印當前執行緒號
cout << "The thread id is: " << GetCurrentThreadId() << endl;
}
/*將新建立的所有執行緒join*/
/*其作用:可以讓join的執行緒先執行,主執行緒(主程序)等待join的執行緒執行完畢再繼續執行*/
for (auto &t : thThread)
t.join();
/*此處的除了使用join(),還可以使用detach()*/
/*作用:將detach的執行緒交給系統管理,系統保證detach的執行緒的執行*/
/*它並不像join能保執行緒執行完畢,也就是說主執行緒執行完畢*/
return;
}