重新分配线程对象

我们可以创建空的线程对象,并在以后为它们分配工作。

如果我们将一个线程对象分配给另一个活动的 joinable 线程,则会在替换线程之前自动调用 std::terminate

#include <thread>

void foo()
{
    std::this_thread::sleep_for(std::chrono::seconds(3));
}
//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);
}