Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it safe to detach a thread and then let it go out of scope (and have it still running)?

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?

like image 796
code_fodder Avatar asked Feb 03 '23 23:02

code_fodder


2 Answers

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 }

like image 163
Gaurav Sehgal Avatar answered Feb 21 '23 03:02

Gaurav Sehgal


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();
}
like image 27
rustyx Avatar answered Feb 21 '23 05:02

rustyx