Search code examples
c++multithreadingc++11detachstdthread

std::thread finishes before I can detach it


If I create an std::thread that terminates before I am able to call detatch() on it, what is the expected behavior? Should an exception be thrown due to the fact that joinable is already false?

If this is so, then is there a way to create a thread which is initialized into a detached state so that I can avoid this error?

Example:

void func()
{
    // do something very trivial so that it finishes fast
    int a = 1;
}

void main()
{
    thread trivial(func);
    trivial.detach();
}

I realize that it isn't really practical to spawn a thread to do trivial work in practice, however I did manage to run into this behavior, and I was curious to know if there is a way around it...


Solution

  • Join and detach have the same requirement, they have to be joinable. So I think doing the joinable check should suffice.

    If(trivial.joinable())
        trivial.detach();
    

    The documentation states:

    A thread that has finished executing code, but has not yet been joined is still considered an active thread of execution and is therefore joinable.

    So my guess would be that the detached thread will cease to exist right away. But it definitily can be created.

    Note: It's good practice to always call joinable() before joining or detaching a thread.