I have been trying Multi-threading inside a for loop. The basic code block will be like,
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();
}
}
For this block im getting a error saying "value type of void* function()cannot be used to initialize a entity type of std::thread..
How do i correct my error.. is there any other efficient way to do this.
You need to store the thread themselves, and not pointer to threads. You don't create any thread here.
You need to get a runnable object as well. So something like:
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With