C++ thread detach

2086 ワード

なぜdetachが必要なの?要約すると、一般的には使用する必要はありません.joinを推奨します.スレッドリソースを迅速に回収する必要がある場合にのみ使用できます.
この投稿の答えは次のとおりです.
  • 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.
  • 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