【发布时间】:2016-08-29 04:27:40
【问题描述】:
在 C++ 的多线程中,join() 和 detach() 有什么不同?
join() 会杀死线程吗?
【问题讨论】:
标签: c++ multithreading c++11 detach
在 C++ 的多线程中,join() 和 detach() 有什么不同?
join() 会杀死线程吗?
【问题讨论】:
标签: c++ multithreading c++11 detach
join() 不会杀死线程。实际上它一直等到线程主函数返回。所以如果你的线程主函数看起来像这样:
while (true) {
}
join() 将永远等待。
detatch() 也不会杀死线程。实际上它告诉std::thread 即使std::thread 对象被销毁,该线程也应该继续运行。 C++ 在 std::thread 析构函数中检查线程是否加入或分离,如果检查失败则终止程序。
因此,如果您取消注释以下代码的main 函数中的第一行,它将崩溃。如果您取消注释第二行或第三行,它将正常工作。
#include <thread>
void func() {
}
void fail1() {
std::thread t(func);
// will fail when we try to destroy t since it is not joined or detached
}
void works1() {
std::thread t(func);
t.join();
}
void works2() {
std::thread t(func);
t.detach();
}
int main() {
// fail1();
// works1();
// works2();
}
【讨论】:
一个 C++ thread 对象通常(但不总是)代表一个执行线程,这是一个操作系统或平台概念。
当thread::join() 被调用时,调用线程将阻塞,直到执行线程完成。基本上,这是一种可以用来知道线程何时完成的机制。当thread::join()返回时,OS线程执行完毕,可以销毁C++thread对象。
thread::detach() 被调用,执行线程与thread 对象“分离”,不再由thread 对象表示——它们是两个独立的东西。 C++ thread 对象可以被销毁,操作系统线程可以继续执行。如果程序需要知道执行线程何时完成,则需要使用其他机制。 join() 不能再对该 thread 对象调用,因为它不再与执行线程相关联。
在 C++ thread 对象仍然“可连接”时销毁它被认为是错误的。也就是说,为了销毁 C++ thread 对象,要么需要调用(并完成)join(),要么必须调用 detach()。如果 C++ thread 对象在被销毁时仍可连接,则会引发异常。
C++ thread 对象不代表执行线程的其他一些方式(即,可以不可连接):
thread 对象不代表执行线程,因此不可连接。【讨论】:
detached 线程与移出的情况相同,只是没有拥有该线程的新对象
简单来说,这两种方法都会启动一个新线程,但是 -
after detach() execution main thread continues runningafter join() execution main thread pauses and waits until the new thread ends
享受吧!
【讨论】: