How to manage shared variable in OpenMp

允我心安 提交于 2020-03-05 01:31:10

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/14569954/how-to-manage-shared-variable-in-openmp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!