2

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.

1
  • 2
    Why use pointers here? Commented Feb 6, 2019 at 10:31

1 Answer 1

14

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

}
Sign up to request clarification or add additional context in comments.

1 Comment

The passing by reference is probably not what you want; the thread is started, but then this emplace_back will return and you really don't know when the thread stops needing that reference: under no circumstances you may alter (or destroy) any of the objects that were passed. Since ThreadVector is a vector it seems likely that one will do this call multiple times which then will only work correctly if distinct objects a, b, Obj and Obj2 are used for each of the threads (aka, they also need to be elements of a vector) and that just doesn't make sense: you're better off passing them by value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.