C++11库中join和detach的区别
当子线程t1调用join()时,主程序就阻塞在join(),主线程必须等子线程t1执行完才能继续往下执行;
当子线程t1调用detach()时,主线程与t1相分离,这时他们成为两个独立的线程,子线程t1执行完后会自动释放掉资源,同时主线程也没必要等子线程t1执行完才回收所有子线程的资源, 主线程结束,所有子线程的资源会立刻被回收。
下面看一段测试代码
#include <iostream>
#include <thread>
using namespace std;
void func_1(int time)
{
this_thread::sleep_for(std::chrono::seconds(time));
cout << "hello func1" << endl;
}
void func_2(int time)
{
this_thread::sleep_for(std::chrono::seconds(time));
cout << "hello func2" << endl;
}
int main()
{
thread t1(func_1, 2);
thread t2(func_2, 1);
//把子线程设置为分离线程,子线程和主线程就毫无关系了
//主线程结束的时候查看其他线程
//但是这个子线程运行完还是没运行完都和这个主线程没关系了
//这个子线程就从这个main分离出去了
//运行程序时也看不到这个子线程的任何输出打印了
t1.detach();
//t1.join();
t2.join();
cout << "main thread done!" << endl;
//主线程运行完成,查看如果当前进程还有未运行完成的子线程
//进程就会异常终止
return 0;
}
显然,func1要等待2s才会打印,func2只需要等待1s,此时线程1分离了,所以主线程在等待线程2执行结束后就会直接回收全部资源。