如何在OpenMp中管理共享变量 [英] How to manage shared variable in OpenMp

查看:873
本文介绍了如何在OpenMp中管理共享变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个OpenMp程序.我有一个for循环,可以迭代100次.我将其分为10个线程.每个线程运行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.

我只想将此计数复制到一个变量中,该变量将保存所有线程中所有计数的总和.如果我们使该变量(共享)在循环中写入,我想它会序列化线程.我只想将每个线程的最后一个计数复制到全局变量中.这样,我将只序列化10个赋值语句.我尝试使用lastprivate,但是我对如何根据自己的要求使用它感到困惑.

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.

这是我的代码

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

推荐答案

您应使用减少量

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

这篇关于如何在OpenMp中管理共享变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆