Search code examples
c++multithreadingdetach

A function that do an asynchronized job


I have function foo:

void foo(){
    //Command set A
    std::this_thread::sleep_for(100s);
    //Command set B
}

The first part which is Command set A has to block the execution. However, the sleep part and //Command set B does not have to block the execution and does not return any data.

So I implement it as follow:

void foo(){
    //Command set A
    std::thread t([](){
        std::this_thread::sleep_for(100s);
        //Command set B
    }
    t.detach()
}

Did I utilizedetach correctly here? Is it the right place to use detach? is there a better solution?


Solution

  • detach is rarely the correct solution. If does exactly what it says: It removes the connection between the std::thread object and the actual thread. The thread keeps running until it finishes on its own, but your program has lost any control over it, if you don’t explicitly implement communication with the thread (e.g. via a message queue).

    Things become problematic if the threads is still active when your program ends. Your process is in the middle of releasing its resources and dying, but the thread is chucking merrily along, using some of these resources. Because all resources are released, even the most basic ones (think low-level C++ runtime) that’s a recipe for desaster. Chances are, your program will crash on exit.

    Look into std::async for a straight forward replacement. It runs a task asynchronously and immediately returns a std::future. Even if the task doesn’t return any data then the future is the handle you can hold on to and on program exit check if the thread is still running – and wait for it to finish, if necessary.