C++ thread detach

作者: Brent姜 | 来源:发表于2017-10-12 12:34 被阅读195次

为什么需要detach?一言以概之:一般不需要使用,推荐使用join,当且仅当你需要快速回收线程资源的时候可以使用。

这篇帖子的回答说:

  1. Create a detached thread when you know you won't want to wait for it with pthread_join(). The only performance benefit is that when a detached thread terminates, its resources can be released immediately instead of having to wait for the thread to be joined before the resources can be released.

  2. It is 'legal' not to join a joinable thread; but it is not usually advisable because (as previously noted) the resources won't be released until the thread is joined, so they'll remain tied up indefinitely (until the program exits) if you don't join it.

When should I use std::thread::detach?

In the destructor of std::thread, std::terminate is called if:

  • the thread was not joined (with t.join())
  • and was not detached either (with t.detach())

Thus, you should always either join or detach a thread before the flows of execution reaches the destructor.


When a program terminates (ie, main returns) the remaining detached threads executing in the background are not waited upon; instead their execution is suspended and their thread-local objects destructed.

Crucially, this means that the stack of those threads is not unwound and thus some destructors are not executed. Depending on the actions those destructors were supposed to undertake, this might be as bad a situation as if the program had crashed or had been killed. Hopefully the OS will release the locks on files, etc... but you could have corrupted shared memory, half-written files, and the like.


So, should you use join or detach ?

  • Use join
  • Unless you need to have more flexibility AND are willing to provide a synchronization mechanism to wait for the thread completion on your own, in which case you may use detach

相关文章

  • C++ thread detach

    为什么需要detach?一言以概之:一般不需要使用,推荐使用join,当且仅当你需要快速回收线程资源的时候可以使用...

  • thread join()和detach()

    1.在声明一个std::thread 对象之后,都可以使用detach和join函数来启动被调线程,区别在于二者是...

  • C++ concurrency in action: 1~4 章

    1 概述 2 管理线程: thread/join/detach/RAAI/std::ref/std::bind/m...

  • C++ concurrency in action: Key p

    1 概述 2 管理线程: thread/join/detach/RAAI/std::ref/std::bind/m...

  • C多线程 队列

    join,detach thread::join(): 阻塞当前线程,直至 this 所标识的线程完成其执行。th...

  • 3. Thread.h——封装thread

    该类封装了thread的create、join、detach等操作。 多线程中系统中将要大量使用线程操作函数。为了...

  • 初识c++多线程

    主要参考以下两篇博客c++多线程 thread类c++实现线程池当一个thread被创建以后要么join等待线程执...

  • 翻译:Cancelling a thread using pth

    Stack overflow地址:c++ - Cancelling a thread using pthread_...

  • C++ concurrency[1]

    结合C++ concurrency in action Passing data to a thread by v...

  • C++ 线程join和detach

    (1)当使用join()函数时,主调线程(main函数里有一个主调线程)阻塞,等待被调线程终止,然后主调线程回收被...

网友评论

    本文标题:C++ thread detach

    本文链接:https://www.haomeiwen.com/subject/onuvyxtx.html