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;
}