关于detach的线程讨论
C++标准库中的线程需要经过两中处理,join或者detach操作,来管理线程的生命周期。其中,detach的线程可以脱离主线程运行,但是在实际操作的时候有些出入。现在查资料并在实际操作下记录运行情况。
主线程退出 子线程表现
想办法造成主线程先退出:
1 2 3 4 5 6 7 8 9 10 11 12 13
| void threadFunction() { _sleep(3000); std::cout << "Thread is running!" << std::endl; }
int main() { std::thread t1(threadFunction); t1.detach();
_sleep(1000); std::cout << "Hello, World!" << std::endl; return 0; }
|
输出为:
可以看到在mian
执行完毕,主线程正常退出之后,子线程也随之结束。也就是说,主线程不是突然结束的,子线程就不会随之结束。看下面代码:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
int main() { std::thread t1(threadFunction); t1.detach();
_sleep(1000); std::cout << "Hello, World1!" << std::endl; std::terminate(); std::cout << "Hello, World2!" << std::endl; return 0; }
|
表现如图所示:

主线程的第一个信息被正常输出,然后主线程就被结束了,并且抛出一个异常,子线程正常输出。这就是主线程突然结束的情况,来不及带走子线程。
子线程退出 主线程表现
假设子线程先退出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| int threadFunction() { std::cout << "Thread is running!" << std::endl; return 0; }
int main() {
std::thread t1(threadFunction); t1.detach();
_sleep(1000); std::cout << "Hello, World!" << std::endl; return 0; }
|
可以看到输出结果:
1 2
| Thread is running! Hello, World!
|
如果换一种退出方式呢?
1 2 3 4 5
| void threadFunction() { std::cout << "Thread is running!" << std::endl; exit(0); }
|
运行结果:
可以看到,子线程如果以这种形式退出,会影响到主线程。