I have a problem about the managed of thread.
My problem is that I want to create a class ThreadManager that have to manage all thread created and of course also destroy
void createThread(DerivedInterface& t)
{
boost::thread t1(&DerivedInterface::run, &t);
insert(&t1);
}
In the above t1
object gets created on the stack, then a pointer to t1
gets inserted into the map and then t1
goes out of scope and gets destroyed, so that all existing pointers to it become invalid.
You can fix it by passing around shared_ptr<thread>
instead of thread*
:
void insert(boost::shared_ptr<boost::thread>);
void createThread(DerivedInterface& t)
{
boost::shared_ptr<boost::thread> t1(new boost::thread(&DerivedInterface::run, &t));
insert(t1);
}
Or, by using r-value references in C++11:
void insert(boost::thread&& t1);
void createThread(DerivedInterface& t)
{
boost::thread t1(&DerivedInterface::run, &t);
insert(std::move(t1));
}
Alternatively, use boost::thread_group that does the above for you.