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;
}