how to declare a vector of thread

£可爱£侵袭症+ 提交于 2019-12-02 21:17:31

问题


i'm new in c++ programing and need some help to use a thread library with vector library...

first I follow this tutorial

but the compiler (visual studio 2013) show me errors and I don't know how correct it:

first declaration of function

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

in main loop

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... 

thanks for any help to clarify


回答1:


Try this:

#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(); 
}



回答2:


finally I can solve the problem with this change in my code...

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


来源:https://stackoverflow.com/questions/32872202/how-to-declare-a-vector-of-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!