Squ*_*all 24 c++ arrays multithreading constructor c++11
我想学习如何使用新的C++标准库创建多个线程并将其句柄存储到数组中.
我该如何开始一个帖子?
我看到的示例使用构造函数启动一个线程,但如果我使用数组,则无法调用构造函数.
#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();
}
}
Run Code Online (Sandbox Code Playgroud)
Nev*_*vin 55
没有任何花哨的东西; 只需使用作业.在你的循环中,写
myThreads[i] = std::thread(exec, i);
Run Code Online (Sandbox Code Playgroud)
它应该工作.