这是Andrew Vaught文章中详细讲解的例子,感兴趣的可以试试。
[Fortran] 纯文本查看 复制代码 module pi_calc
use, intrinsic :: iso_c_binding
implicit none
type results
integer(kind=8) :: in,total
end type results
type(results) :: acc[*]
logical :: flag[*]
interface
subroutine usleep(u) bind(c)
use, intrinsic :: iso_c_binding
integer(kind=c_long),value :: u
end subroutine usleep
end interface
contains
subroutine master
implicit none
integer :: n
type(results) :: sum
do
call usleep(1000000_c_long)
do n=2,num_images()
flag[n]=.true.
end do
sync images(*)
sum%total=0
sum%in=0
do n=2,num_images()
sum%total=sum%total+acc[n]%total
sum%in=sum%in+acc[n]%in
end do
print*,sum%in,sum%total,4*dble(sum%in)/dble(sum%total)
end do
end subroutine master
subroutine worker
implicit none
real :: x,y
type(results) :: local
local%in=0
local%total=0
do
call random_number(x)
call random_number(y)
if(x*x+y*y<1.0)local%in=local%in+1
local%total=local%total+1
if(flag)then
acc=local
flag=.false.
sync images(1)
end if
end do
end subroutine worker
end module pi_calc
program m
use pi_calc
if(num_images()==1)stop "Need more images!"
if(this_image()==1)then
call master()
else
call worker()
end if
end program m |