Cod*_*esi 2 c++ multithreading
我一直在 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();
}
}
Run Code Online (Sandbox Code Playgroud)
对于此块,我收到一条错误消息,提示“void* function() 的值类型不能用于初始化 std::thread 的实体类型......
我如何纠正我的错误.. 有没有其他有效的方法来做到这一点。
您需要存储线程本身,而不是指向线程的指针。您不会在此处创建任何线程。
您还需要获得一个可运行的对象。所以像:
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();
}
Run Code Online (Sandbox Code Playgroud)
编辑:添加缺失;