我想學習如何用新的C++標準庫創建多個線程並將它們的句柄存儲到一個數組中。
如何啓動線程?
我看到的例子用構造函數啓動線程,但如果我使用數組,我無法調用構造函數。如何在C++ 11中創建線程對象數組?
#include <iostream>
#include <thread>
void exec(int n){
std::cout << "thread " << n << std::endl;
}
int main(int argc, char* argv[]){
std::thread myThreads[4];
for (int i=0; i<4; i++){
//myThreads[i].start(exec, i); //?? create, start, run
//new (&myThreads[i]) std::thread(exec, i); //I tried it and it seems to work, but it looks like a bad design or an anti-pattern.
}
for (int i=0; i<4; i++){
myThreads[i].join();
}
}
但它會創建一個臨時對象,調用構造函數,執行賦值,然後調用析構函數。國家可能不一致。我試過了,它正在工作,但我不知道它是否會工作。 – Squall
它使用移動語義。沒有什麼會不一致,它通過設計起作用。新執行線程的所有權將從臨時數據庫傳遞到數組元素,使臨時數據與默認構造的線程對象處於相同狀態,即不引用任何執行線程,因此可以安全銷燬它。 –