gpt4 book ai didi

c++ - OpenMP 和#pragma omp atomic

转载 作者:可可西里 更新时间:2023-11-01 18:20:36 30 4
gpt4 key购买 nike

我对 OpenMP 有疑问。 MSVS 编译器向我抛出“pragma omp atomic 的形式不正确”。我不知道为什么。代码:(程序用积分法指定PI号)

#include <stdio.h>
#include <time.h>
#include <omp.h>

long long num_steps = 1000000000;
double step;

int main(int argc, char* argv[])
{
clock_t start, stop;
double x, pi, sum=0.0;
int i;
step = 1./(double)num_steps;
start = clock();

#pragma omp parallel for
for (i=0; i<num_steps; i++)
{
x = (i + .5)*step;
#pragma omp atomic //this part contains error
sum = sum + 4.0/(1.+ x*x);
}

pi = sum*step;
stop = clock();

// some printf to show results
return 0;
}

最佳答案

根据当前的 OpenMP 标准,您的程序在语法上是完全正确的 OpenMP 代码(例如,它未经修改地使用 GCC 4.7.1 编译),除了 x 应该声明为 private (这不是句法而是语义错误)。不幸的是,Microsoft Visual C++ 实现了一个非常古老的 OpenMP 规范(2002 年 3 月的 2.0),它只允许以下语句在 atomic 构造中可接受:

x binop= expr
x++
++x
x--
--x

后来的版本包括 x = x binop expr,但即使在 VS2012 中,MSVC 也永远停留在 OpenMP 2.0 版。仅供比较,当前的 OpenMP 版本为 3.1,我们预计 4.0 将在接下来的几个月内推出。

在 OpenMP 2.0 中,您的语句应为:

#pragma omp atomic
sum += 4.0/(1.+ x*x);

但是正如已经注意到的那样,使用归约会更好(通常更快):

#pragma omp parallel for private(x) reduction(+:sum)
for (i=0; i<num_steps; i++)
{
x = (i + .5)*step;
sum = sum + 4.0/(1.+ x*x);
}

(你也可以这样写 sum += 4.0/(1.+ x*x);)

关于c++ - OpenMP 和#pragma omp atomic,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14016026/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com