code_fodder
code_fodder

Reputation: 16391

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?

Upvotes: 15

Views: 5510

Answers (4)

rustyx
rustyx

Reputation: 85481

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 does.

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
    t.join();
}

Upvotes: 5

Gaurav Sehgal
Gaurav Sehgal

Reputation: 7542

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 }

Upvotes: 15

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38883

Yes, it is ok and safe in you code. But it does not have any sense. main function will utilize CPU and a thread function will get less CPU time. You can attach to forever thread and reach similar behaviour: run_thread will never exit, thus main will never exit.

void run_thread()
{
    std::thread t([]{
        while(true){/* also run forever */;}
    });

    // Wait here forever
    t.attach();
}

int main()
{
     run_thread();    
}

Upvotes: 1

Caleth
Caleth

Reputation: 63142

Such a usage is the point of detach.

Upvotes: 1

Related Questions