Increasing array elements in parallel using OpenMP

I have an array a size N with random numbers. Using OpenMP, I want to increment elements from 0 to 9 of array b size 10 for each number in A. Language - C.

 #pragma omp parallel for for(i = 0; i < N; i++) b[a[i]]++; 

Unfortunately, apparently, some elements of b seem to have simultaneous entries, and the result is not as expected. I tried it with setting b for firstprivate and lastprivate, but that didn't help either.

The task seems simple, but I do not know how to do this, since there is no atomic for arrays in OpenMP for arrays. I could create a new array for the number of threads and then add them together at the end, but this does not seem optimal.

What would be the fastest way to count the numbers of numbers in a in elements of an array of b ?

+5
source share
3 answers

Your question is essentially a duplicate of the question I asked fill-histograms-in-parallel-with-openmp-without-use-a-critical-section .

A simple solution in your case

 #pragma omp parallel { int i, b_local[10] = {0}; #pragma omp for nowait for(i = 0; i < n; i++) b_local[a[i]]++; #pragma omp critical for(i=0; i<10; i++) b[i] += b_local[i]; } 

This can be done without a critical section (see my question), but it is not necessarily more efficient.

Here is a working example

 #include <stdio.h> #include <string.h> #include <stdlib.h> #define N 100 void foo(int *b, int *a, int n) { #pragma omp parallel { int i, b_local[10]; memset(b_local, 0, 10*sizeof(int)); #pragma omp for for(i = 0; i < n; i++) b_local[a[i]]++; #pragma omp critical { for(i=0; i<10; i++) { b[i] += b_local[i]; } } } } int main() { int i; int b[10] = {0,1,2,3,4,5,6,7,8,9}; int b2[10] = {0,1,2,3,4,5,6,7,8,9}; int a[N]; for(i=0; i<N; i++) a[i] = rand()%10; foo(b,a,N); for(i=0; i<N; i++) b2[a[i]]++; for(i=0; i<10; i++) printf("%d ", b[i]); puts(""); for(i=0; i<10; i++) printf("%d ", b2[i]); puts(""); } 
+2
source

If any of the values ​​in [] are identical, you must write the same element b at the same time.

a [0] = 1 and a [1] = 1, then you will write to b [1] at the same time.

0
source

You can use 2 "for ()", one for each array

0
source

Source: https://habr.com/ru/post/1216212/


All Articles