C++ 中多线程的 join() 和 detach() 有什么不同?

What is different between join() and detach() for multi threading in C++?

在 C++ 的多线程中,join()detach() 有什么不同? join() 是否终止线程?

join() 不会终止线程。实际上它一直等到线程主函数returns。因此,如果您的线程主函数如下所示:

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 对象通常(但不总是)表示一个执行线程,这是一个 OS 或平台概念。

调用thread::join()时,调用线程将阻塞,直到执行线程完成。基本上,这是一种可用于了解线程何时完成的机制。当thread::join()returns时,OS执行线程已经完成,C++thread对象可以被销毁。

thread::detach() 被调用时,执行线程与 thread 对象“分离”,不再由 thread 对象表示 - 它们是两个独立的事物. C++ thread 对象可以被销毁并且执行的 OS 线程可以继续。如果程序需要知道执行线程何时完成,则需要使用其他一些机制。 join() 无法再对该 thread 对象调用,因为它不再与执行线程相关联。

在 C++ thread 对象仍然“可连接”时销毁它被认为是错误的。也就是说,为了销毁 C++ thread 对象,需要调用(并完成)join() 或必须调用 detach()。如果 C++ thread 对象在销毁时仍然可以连接,则会抛出异常。

C++ thread 对象不代表执行线程的其他一些方式(即,可以是不可连接的):

  • 默认构造的 thread 对象不代表执行线程,因此不可连接。
  • 已移出的线程将不再代表执行线程,因此不可加入。

By simple terms, both methods start a new thread but -

after detach() execution main thread continues running
after join() execution main thread pauses and waits until the new thread ends

来自 microsoft documentation

Enjoy!