join | waits for the thread to finish its execution (public member function) |
detach | permits the thread to execute independently from the thread handle (public member function) |
对创建线程的两种操作:等待/分离,join/detach
1.join():主线程会阻塞,当子线程执行结束后,主线程才会继续执行。
2.detach():将主线程和子线程分离,分离后,主线程无法控制子线程,子线程转为后台线程,子线程将由系统(运行时库)托管。其后,子线程的“死活”就和主线程无关。子线程结束后,由系统自动释放其资源。即守护线程。
join
void CTask::work()
{
int i = 0;
while (i<5) {
cout<<"Task work:"<<i<<endl;
std::this_thread::sleep_for(chrono::seconds(1));
i++;
}
}
int main(int argc, char *argv[])
{
cout <<"main thread 1"<<endl;
CTask task;
cout <<"main thread 2"<<endl;
thread th1(&CTask::work, &task);
cout <<"main thread 3"<<endl;
th1.join();
cout <<"main thread 4"<<endl;
return 1;
}
从运行结果可知,主线程启动子线程后,在join处阻塞主线程,等待子线程处理结束后,才又开始处理主线程。
detach
int main(int argc, char *argv[])
{
cout <<"main thread 1"<<endl;
CTask task;
cout <<"main thread 2"<<endl;
thread th1(&CTask::work, &task);
cout <<"main thread 3"<<endl;
th1.detach();
int i=0;
while (1) {
i++;
cout<<"run:"<<i<<endl;
std::this_thread::sleep_for(chrono::seconds(1));
}
cout <<"main thread 4"<<endl;
return 1;
}
使用detach函数,主线程和子线程并行运行,会出现资源抢占的情况,同时输出。
版权声明:本文为zhuzitop原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。