Anup Buchke
Anup Buchke

Reputation: 5500

How to manage shared variable in OpenMp

I am trying to write a OpenMp program. I have a for loop which iterates 100 times. I have divided that into 10 threads. Each thread runs 10 iterations and generates some count based on some condition. So as per this logic each thread will generate its own count.

All I want is to copy this count to a variable which will hold the sum of all counts from all threads. If we make this variable(shared) to write in the loop, I guess it will serialize the threads. I just want to copy the last count of each thread into a global variable. This way I will be only serializing 10 assignment statements. I tried to use lastprivate but I am getting confused as to how to use it to my requirement.

Here is my code

#pragma omp parallel for private(i) schedule(dynamic) shared(count)
for (i = 1; i <= 100 ; i++)
{
    if(i%2==0)
        count++; 
}
printf("Total = %d \n", count);

Upvotes: 1

Views: 9263

Answers (1)

Lol4t0
Lol4t0

Reputation: 12547

You should use reduction

int count = 0;
int i;
#pragma omp parallel for private(i) schedule(dynamic) reduction(+:count)
for (i = 1; i <= 100 ; i++)
    if(i%2==0)
        count++; 

Upvotes: 5

Related Questions