8

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?

code_fodder
  • 12,697
  • 10
  • 68
  • 123
  • Read: http://en.cppreference.com/w/cpp/thread/thread/~thread – Richard Critten May 24 '18 at 08:55
  • [This `std::thread` destructor reference](http://en.cppreference.com/w/cpp/thread/thread/%7Ethread) might be useful. – Some programmer dude May 24 '18 at 08:55
  • @RichardCritten yes, I did see that infact, but it says it is safe to destroy (does not tell me that its going to still run ok though). Even detach says: `Separates the thread of execution from the thread object, allowing execution to continue independently. Any allocated resources will be freed once the thread exits. After calling detach *this no longer owns any thread. ` But I just wanted to double-double sure : ) – code_fodder May 24 '18 at 08:58
  • Off-topic, but a thread the literally runs forever could lead to some surprises for you https://timsong-cpp.github.io/cppwp/n4659/intro.multithread#intro.progress-1 – StoryTeller - Unslander Monica May 24 '18 at 08:59
  • @rustyx ...lol sorry, ok I will .. I knew I should have made a better example :o – code_fodder May 24 '18 at 09:02

4 Answers4

7

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 }

Gaurav Sehgal
  • 7,011
  • 2
  • 15
  • 29
2

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();
}
rustyx
  • 62,971
  • 18
  • 151
  • 210
  • thanks for that. I usually only ever use this method - which was why I felt a bit uncomfortable with the detach method. But I think this answer adds to this question so +1 for that : ) – code_fodder May 24 '18 at 09:29
1

Such a usage is the point of detach.

Caleth
  • 35,377
  • 2
  • 31
  • 53
1

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();    
}
S.M.
  • 13,389
  • 7
  • 29
  • 39
  • Yeah, sorry that is due to my crappy example - I just had the example to show the "issue". But your point is noted : ) – code_fodder May 24 '18 at 09:00