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 <<"m