使用OpenMP进行fortran简单集成

时间:2014-11-30 05:25:00

标签: 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)/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

由于

1 个答案:

答案 0 :(得分:0)

您已编制竞争条件。在行

sum2 = sum2 + sum

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

继续阅读您的OpenMP教程,直到您遇到专为您正在做的事情而设计的reduction子句。还要了解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