vendredi 27 mars 2020

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?

Aucun commentaire:

Enregistrer un commentaire