Array reduction in OpenMP
Question:
How to perform it in OpenMP for arrays Reduction operation?
Answer:
OpenMP does support array reduction. There are two ways to do this:
Method 1: Use "private" variables
to create a private copy of S for each thread, populate them in parallel, and then Merge them into S in the area:
int A[] = {84, 30, 95, 94, 36, 73, 52, 23, 2, 13}; int S[10] = {0}; #pragma omp parallel { int S_private[10] = {0}; #pragma omp for for (int n = 0; n < 10; ++n) { for (int m = 0; m <= n; ++m) { S_private[n] += A[m]; } } #pragma omp critical { for (int n = 0; n < 10; ++n) { S[n] += S_private[n]; } } }
method 2: Create an array of dimension 10*nthreads using multidimensional array
, fill it in parallel, and then merge it into S without critical section:
int A[] = {84, 30, 95, 94, 36, 73, 52, 23, 2, 13}; int S[10] = {0}; int *S_private; #pragma omp parallel { const int nthreads = omp_get_num_threads(); const int ithread = omp_get_thread_num(); #pragma omp single { S_private = new int[10 * nthreads]; for (int i = 0; i < (10 * nthreads); i++) S_private[i] = 0; } #pragma omp for for (int n = 0; n < 10; ++n) { for (int m = 0; m <= n; ++m) { S_private[ithread * 10 + n] += A[m]; } } #pragma omp for for (int i = 0; i < 10; i++) { for (int t = 0; t < nthreads; t++) { S[i] += S_private[10 * t + i]; } } } delete[] S_private;
The above is the detailed content of How to Perform Array Reduction in OpenMP?. For more information, please follow other related articles on the PHP Chinese website!