Thread Lifetime Management: Warnings and Tips
Some caveats and tips on the lifetime of threads in C++ coming your way...
Warnings
The Challenge of
detach: Of course you can uset.detach()instead oft.join()in the last program. The threadtis not joinable any more; therefore, its destructor didn’t callstd::terminate. But now you have another issue. The program behaviour is undefined because the main program may complete before the threadthas time to complete its workpackage; therefore, its lifetime is too short to display the id. For more details, see lifetime issues of variables.
Tips
🔑
scoped_threadby Anthony WilliamsIf it’s too bothersome for you to manually take care of the lifetime of your threads, you can encapsulate a
std::threadin your own wrapper class. This class should automatically call join in its destructor. Of course you can go the other way and call detach, but there is an issue with detach.Anthony Williams created such a useful class and presented it in his excellent book Concurrency in Action. He called the wrapper
scoped_thread.scoped_threadgets a threadtin its constructor and checks iftis still joinable. If the threadtpassed into the constructor is not joinable anymore, there is no need for thescoped_thread. Iftis joinable, the destructor callst.join(). Because the copy constructor and copy assignment operator are declared asdelete, instances ofscoped_threadcan not be copied to or assigned from.