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 }