C++多线程

C++ thread detach

2017-10-12  本文已影响195人  Brent姜

为什么需要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:

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 ?

上一篇 下一篇

猜你喜欢

热点阅读