我一直在试图多线程里面一个for循环。基本码块会像,
void function(int a, string b, MyClass &Obj, MyClass2 &Obj2)
{
//execution part
}
void anotherclass::MembrFunc()
{
std::vector<std::thread*> ThreadVector;
for(some condition)
{
std::thread *mythread(function,a,b,obj1,obj2) // creating a thread that will run parallely until it satisfies for loop condition
ThreadVector.push_back(mythread)
}
for(condition to join threads in threadvector)
{
Threadvector[index].join();
}
}
对于此块即时得到一个错误说“无效*函数的值类型()不能用于初始化性病的实体类型::线程..
如何纠正我的错误..有任何其他有效的方式来做到这一点。
你需要存储线程本身,而不是指向线程。你不要在这里创建任何线程。
你需要得到一个Runnable对象为好。因此,像:
std::vector<std::thread> ThreadVector;
for(some condition)
{
ThreadVector.emplace_back([&](){function(a, b, Obj, Obj2)}); // Pass by reference here, make sure the object lifetime is correct
}
for(auto& t: Threadvector)
{
t.join();
}