When I use std::thread
like this:
func()
{
std::thread(std::bind(&foo, this));
}
the thread object is allocated in stack and is destroyed when func()
returns.
So I try to use it like:
func()
{
std::thread* threadPtr = new std::thread(std::bind(&foo, this));
}
Where should I delete threadPtr
?
And how can I create a thread that is initially suspended?
If you want the thread to run independently, you need to use the detach()
method on the object. Otherwise, the thread
destructor will terminate your program if the object is destroyed while the thread is still running.
Threads start running as soon as they are created. You cannot create a thread object in a suspended state. You can either store the arguments to create the thread instead of actually creating it (possibly using, for instance, std::function
), or make it block on a mutex or a condition variable until you are ready to let it run.