简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM