如何声明线程的向量

how to declare a vector of thread

本文关键字:线程 向量 声明 何声明      更新时间:2023-10-16

我是c++编程新手,需要一些帮助来使用带有矢量库的线程库…

首先我遵循这个教程

但是编译器(visual studio 2013)告诉我错误,我不知道它有多正确:

函数的第一个声明

void Fractal::calcIterThread(vector<vector<iterc>> &matriz, int desdePos, int hastaPos, int idThread){
   ...
}    

主循环

vector<vector<iterc>> res;
res.resize(altoPantalla);
for (int i = 0; i < altoPantalla; i++){
   res[i].resize(anchoPantalla);
}
int numThreads = 10;
vector<thread> workers(numThreads);
for (int i = 0; i < numThreads; i++){ //here diferent try
   thread workers[i] (calcIterThread, ref(res), inicio, fin, i)); // error: expresion must have a constant value
   workers[i] = thread(calcIterThread, ref(res), inicio, fin, i)); // error: no instance of constructor "std::thread::thread" matches the argument list
}
...rest of code... 

试试这个:

#include <functional>
#include <thread>
#include <vector>
// ...
int numThreads = 10;
std::vector<std::thread> workers;
for (int i = 0; i != numThreads; ++i)
{
    workers.emplace_back(calcIterThread, std::ref(res), inicia, fin, i);
}
for (auto & t : workers)
{
    t.join(); 
}

最后我可以解决这个问题,在我的代码的这个变化…

workers.emplace_back(thread{ [&]() {
    calcIterThread(ref(res), inicio, fin, i);
}});