Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用OpenMP进行fortran简单集成_Fortran_Openmp - Fatal编程技术网

使用OpenMP进行fortran简单集成

使用OpenMP进行fortran简单集成,fortran,openmp,Fortran,Openmp,我正在使用Fortran90解决一个简单的积分问题,并计算并行运行时的速度差。在使用openMP并行进程时,我很难获得正确的结果 program midpoint use omp_lib implicit none integer :: beginning, rate, end, iteration double precision :: sum, div, x, sum2 integer ::a,b, n n = 100000000 a = 10 b = 0 div = dble(a-b)

我正在使用Fortran90解决一个简单的积分问题,并计算并行运行时的速度差。在使用openMP并行进程时,我很难获得正确的结果

program midpoint
use omp_lib
implicit none

integer :: beginning, rate, end, iteration
double precision :: sum, div, x, sum2
integer ::a,b, n

n = 100000000
a = 10
b = 0
div = dble(a-b)/n
x=b+div/2
sum = 0.0

call system_clock(beginning, rate)
do iteration=1,n
    sum = sum  + sqrt(x)*div ! evaluating sqrt(x) function
    x = x + div
end do
call system_clock(end)

print *, "Computation from single core: ", sum
print *, "elapsed time from single core: ", real(end - beginning) / real(rate)

x=b+div/2
sum = 0.0
sum2 = 0.0
call system_clock(beginning, rate)

!$omp parallel private(iteration, sum) shared(sum2, x)
!$omp do
do iteration=1,n
    sum = sum  + sqrt(x)*div ! evaluating sqrt(x) function
    x = x + div
end do
!$omp end do
sum2 = sum2 + sum
!$omp end parallel
call system_clock(end)

print *, "Computation from multiple cores: ", sum2
print *, "elapsed time from multiple cores: ", real(end - beginning) / real(rate)

end program
谢谢

您已编程设定了比赛条件。排队

sum2 = sum2 + sum
您已经授予线程读写共享变量(
sum2
)的权限,而不控制操作的顺序。下一行
x=x+div
也会出现同样的问题

继续阅读OpenMP教程,直到遇到针对您似乎正在做的事情而设计的
reduce
子句。还要了解
firstprivate
子句,该子句将在首次遇到并行区域时使用同名变量的值初始化线程局部变量

我没有仔细检查语法,但应该是这样的:

!$omp parallel do private(iteration) firstprivate(x) shared(div) reduction(+:sum)
do iteration=1,n
    sum = sum  + sqrt(x)*div ! evaluating sqrt(x) function
    x = x + div
end do
!$omp end parallel do

! at this point the value of sum will have been 'reduced' across all threads
print *, "Computation from multiple cores: ", sum

谢谢你的帮助。我使用您的编辑重新运行。我得到了正确答案的1/2。是因为我需要线程将它们各自的总和相加吗?是因为我需要线程将它们各自的总和相加吗?可能是,但这是你的算法,我没有检查它的正确性,只是试图修复OpenMP问题。@Alex,你得到了正确答案的1/2,因为所有线程都以相等的
x
值开始,这是错误的。在并行区域内正确初始化
x
,或者将
x=x+div
替换为
x=x0+iteration*div
,其中
x0=b+div/2
是共享变量,
x
是私有变量(注意乘法比加法慢)。