Reassigning thread objects

suggest change

We can create empty thread objects and assign work to them later.

If the thread object on the left of the assignment is still joinable, std::terminate is called before that object takes the new thread. The loop has to sit inside a function. A std::thread that is still joinable when it is destroyed also calls std::terminate, so these threads still need join() or detach().

#include <chrono>
#include <thread>

void foo()
{
    std::this_thread::sleep_for(std::chrono::seconds(3));
}

int main()
{
    //create 100 thread objects that do nothing
    std::thread executors[100];

    // Some code

    // I want to create some threads now

    for (int i = 0;i < 100;i++)
    {
        // If this object doesn't have a thread assigned
        if (!executors[i].joinable())
             executors[i] = std::thread(foo);
    }

    for (auto& t : executors)
        t.join();
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents