Nick
Nick

Reputation: 155

How to wait for multiple threads to complete and reuse them?

I have a C++ program that tries to process each line of array in parallel, and after one line completely finishes, it moves on to the next line. My current program creates a thread for each line of array, and join them after usage. But it seems that the program is wasting a lot of time on creating/closing threads.

Is there a way to create those threads just for one time, and for each line they wait for the slowest thread to finish and then execute functions for the next line?

Here is my sample code:

#include <iostream>
#include <thread>
using namespace std;
#define THREAD 5
int arr[2][10000];
void update_arr(int i, int j_s, int j_to){
    for (int j = j_s; j <= j_to; j++)
        arr[i%2][j]= arr[(i-1)%2][j]+2*arr[(i-1)%2][j-1];
}

int main(){
    for (int i = 0; i < 10000; i++) arr[0][i] = 1;
    for (int i = 1; i <= 10000; i++){
        thread t[THREAD];
        for (int ii = 0; ii < THREAD; ii++)
            t[ii] = thread(update_arr, i, ii * 10000 / THREAD, (ii+1) * 10000 / THREAD - 1);

        for (int ii = 0; ii < THREAD; ii++)
            t[ii].join();   
    }
    cout<<arr[1][9999]<<endl;
}

Upvotes: 2

Views: 652

Answers (1)

Raedwald
Raedwald

Reputation: 48702

This problem, the relatively high cost of creating and destroying threads, is what a is intended to avoid. Note that the std::async class can be implemented using a thread pool (but that is not guaranteed), so you should consider using that first.

Upvotes: 2

Related Questions