northerner
northerner

Reputation: 794

How to avoid destroying and recreating threads inside loop?

I have a loop with that creates and uses two threads. The threads always do the same thing and I'm wondering how they can be reused instead of created and destroyed each iteration? Some other operations are do inside the loop that affect the data the threads process. Here is a simplified example:

const int args1 = foo1();
const int args2 = foo2();
vector<string> myVec = populateVector();
int a = 1;
while(int i = 0; i < 100; i++)
{
    auto func = [&](const vector<string> vec){
        //do stuff involving variable a
        foo3(myVec[a]);
    }
    thread t1(func, args1);
    thread t2(func, args2);
    t1.join();
    t2.join();

    a = 2 * a;
}

Is there a way to have t1 and t2 restart? Is there a design pattern I should look into? I ask because adding threads made the program slightly slower when I thought it would be faster.

Upvotes: 3

Views: 639

Answers (1)

g19fanatic
g19fanatic

Reputation: 10931

You can use std::async as suggested in the comments.

What you're also trying to do is a very common usage for a Threadpool. I simple header only implementation of which I commonly utilize is here

To use this library, create the pool outside of the loop with a number of threads set during construction. Then enqueue a function in which a thread will go off and execute. With this library, you'll be getting a std::future (much like the std::async steps) and this is what you'd wait on in your loop.

Generically, you'd want to make access to any data thread-safe with mutexs (or other means, there are a lot of ways to do this) but under very specific situations, you'll not need to.

In this case,

  1. so long as the vector isn't being increased in size (doesn't need to reallocate)
  2. Only reading items or only modifying each item at a time in its own thread

the you wouldn't need to worry about synchronization.

Though its just good habit to do the sync anyways... When other people eventually modify the code, they're not going to know your rules and will cause issues.

Upvotes: 1

Related Questions