重新分配執行緒物件

我們可以建立空的執行緒物件,並在以後為它們分配工作。

如果我們將一個執行緒物件分配給另一個活動的 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);
}