Reusing std::thread objects

2015/12/26

Tags: c++ joinable c++11 std::thread

Sometimes it’s useful to reuse a std::thread object - from a resource and design point of view. This would seem trivial, but since the std::thread was designed as a single use object, there are a few tricks to reusing it.

Reusing a std::thread object would look something like this:

#include <thread>  
  
void foo()  
{  
  // do stuff...  
}  
  
void bar()  
{  
  // do stuff...  
}  
  
//...  
  
std::thread thObject (foo); //first use  
  
//...  
  
thObject = std::thread(bar); //reuse  
Seems simple. However, there is a limitation: the thread object must not be joinable when reusing it, otherwise it will throw an exception.
So make sure you call join() on the thread object before reusing it.

This rule does not apply for detached threads.