How do I put a thread in a C++ smart pointer?
You can put std::thread
s where ever you want, they are not special. Destroying thread handles is problematic. You can implicitly detach, implicitly kill or implicitly join and every option is bad. std::~thread
(usually) just kills the whole program. To prevent that join
or detach
it.
Since you seem to want to implicitly join you may want to use std::async
(probably with the std::launch::async
policy) to launch your threads. It returns an std::future
who's destructor implicitly joins.
it's possible to create std::unique_ptr<std::thread>
. It will call std::thread destructor, when scope of unique_ptr will end. Remember that calling std::thread destructor is not terminating running thready gently, but by std::terminate
. To end std::thread normally, you have to run .join()
on std::thread object.
According to cppreference.com,
A thread object does not have an associated thread (and is safe to destroy) after
- it was default-constructed
- it was moved from
- join() has been called
- detach() has been called
So if you define the thread as a member variable and write your destructor like this:
~my_class(){ done_ = true; my_thread_.join();}
everything is fine, because it is guaranteed by the standard that the std::thread
destructor will be called only after the my_class
destructor, see this Q/A.