简体   繁体   English

如何在OpenMp中管理共享变量

[英]How to manage shared variable in OpenMp

I am trying to write a OpenMp program. 我正在尝试编写一个OpenMp程序。 I have a for loop which iterates 100 times. 我有一个for循环,可以迭代100次。 I have divided that into 10 threads. 我将其分为10个线程。 Each thread runs 10 iterations and generates some count based on some condition. 每个线程运行10次迭代,并根据某些条件生成一些计数。 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. 这样,我将只序列化10个赋值语句。 I tried to use lastprivate but I am getting confused as to how to use it to my requirement. 我尝试使用lastprivate但对于如何根据自己的需求使用它感到困惑。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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