我想学习如何用新的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
它使用移动语义。没有什么会不一致,它通过设计起作用。新执行线程的所有权将从临时数据库传递到数组元素,使临时数据与默认构造的线程对象处于相同状态,即不引用任何执行线程,因此可以安全销毁它。 –