join:主线程阻塞,一直等到线程执行结束后,主线程才继续向下进行。
detach:主线程继续进行,同时线程也会开始进行,主线程与创建的线程互不影响。
#define THREAD_SIZE 4 //线程数组的大小
#include <iostream>
#include <thread>
#include <chrono> //包含线程休眠函数sleep_for
using namespace std;
int _irun = 0; //控制线程循环的变量
void run(string name)
{
while (!_irun)
{
cout << "thread:" << name << "running" << endl;
//线程休眠一秒
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main()
{
//线程数组
thread thd;
string thread_name;
cin>>thread_name;
//将函数绑定到线程,并传参
thd = thread(run, thread_name);
//线程开始执行
thd.detach();
//thd.join();
cin >> _irun;
system("pause");
return 0;
}
如果使用join开始线程,_irun 将无法得到新的赋值,线程将无法结束