I have the following code, which I think works ok (forgive the silly/contrived example).
void run_thread()
{
std::thread t([]{
while(true)
{
// keep getting chars... to stop peoples eye's hurting : )
char c = getchar();
}
});
t.detach(); // Detach thread
// thread goes out of scope here - but is it ok because its detached??
}
int main()
{
run_thread();
// Wait here forever
while (true) {;}
}
But after re-reading it I have a doubt about it. Thread t goes out of scope. I can't remember now if it is safe to do this after you have called detach()... I think it is, but as I say I have a nagging doubt. Can anyone confirm if this is good/bad practise?
Thread t goes out of scope. I can't remember now if it is safe to do this after you have called detach()
You detach()
because you want to disassociate the actual running thread with the thread object. So after }
t
goes out of scope but the actual thread will keep on running until its instruction completes.
If it weren't for detach()
std::terminate
would have killed the thread at }
detach
basically releases the std::thread
object instance which is the C++ "handle" to the actual OS thread, thereby making it impossible to join
the thread later.
In most cases it's better to keep the thread
instance around at some global scope so that you can join
it later, for example before exiting main
. That way you can ensure all threads finish before the main thread.
For example:
std::thread t; // can be "empty"
void run_thread()
{
t = std::thread([]{
while(true)
{
// keep getting chars...
char c = getchar();
}
});
}
int main()
{
run_thread();
// Wait here
std::this_thread::sleep_for(30s);
// Before exiting wait for the thread to finish
if (t.joinable())
t.join();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With