CodeKhaleesi
CodeKhaleesi

Reputation: 79

Creating Thread inside a For Loop c++

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.

Upvotes: 2

Views: 17175

Answers (1)

Matthieu Brucher
Matthieu Brucher

Reputation: 22043

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

}

Upvotes: 14

Related Questions