These days I am reading the pdf Designing MT programs . It explains that the user MUST explicitly call detach()
on an object of class std::thread
i
Here's one way to implement RAII threads.
#include
#include
void run() { /* thread runs here */ }
struct ThreadGuard
{
operator()(std::thread* thread) const
{
if (thread->joinable())
thread->join(); // this is safe, but it blocks when scoped_thread goes out of scope
//thread->detach(); // this is unsafe, check twice you know what you are doing
delete thread;
}
}
auto scoped_thread = std::unique_ptr(new std::thread(&run), ThreadGuard());
If you want to use this to detach a thread, read this first.