问题描述
我正在尝试实现一个代码,在该代码中我们生成一个子进程,该子进程应该在每次迭代时向变量 sum
添加一个。我们总共有 3 次迭代。
sum
的结果是:0+1+1+1 = 3。
但是当我想在子进程部分生成 3 个线程时(所以每个线程都会有一个迭代),我得到一个 sum
等于 9。
(我是 POSIX 线程以及我稍后将使用的所有函数的新手,所以如果错误很明显,请不要感到惊讶)
这是我的代码:
program main
use,intrinsic :: iso_c_binding
use :: unix
implicit none
integer :: i,rc,pid,STATUS,any_child
integer,parameter :: NTHREADS = 3
type(c_pthread_t) :: threads(NTHREADS)
integer,target :: routines(NTHREADS) = [ (i,i = 1,NTHREADS) ]
integer :: sum=0,product=5
pid = c_fork()
if (pid < 0) then
! Fork Failed.
call perror('fork()' // c_null_char)
else if (pid == 0) then
print '(a)','>>> child process running ...'
do i = 1,NTHREADS
! Create new thread.
rc = c_pthread_create(threads(i),c_null_ptr,c_funloc(compute),c_loc(routines(i)))
end do
do i = 1,NTHREADS
! Join thread.
rc= c_pthread_join(threads(i),c_loc(routines(i)))
end do
print '(a)','>>> child process done.'
call exit(STATUS)
else
! Parent process.
print*,'habibi'
any_child=c_wait(STATUS)
print*,'ya nour 3in'
open(2,file='variables.dat')
read(2,*) sum,product
close(2)
print*,'The sum is equal to : ',sum
print*,'The product is equal to : ',product
end if
contains
recursive subroutine compute(arg) bind(c)
!! Runs inside a thread and prints out current thread id and loop
!! iteration.
type(c_ptr),intent(in),value :: arg
integer,pointer :: n
integer :: i,rc
integer :: sum=0,product=5
if (.not. c_associated(arg)) return ! Check whether argument has been passed.
call c_f_pointer(arg,n) ! Convert C pointer to Fortran pointer.
do i = 1,3
sum=sum+1
product=product*2
open(1,file = 'variables.dat')
write(1,product
close(1)
print '("--- Thread #",i0," - Loop iteration ",i0)',n,i
rc = c_usleep(10**6) ! Sleep 1 sec.
end do
end subroutine compute
end program main
输出如下:
habibi
>>> child process running ...
--- Thread #1 - Loop iteration 1
--- Thread #3 - Loop iteration 1
--- Thread #2 - Loop iteration 1
--- Thread #1 - Loop iteration 2
--- Thread #3 - Loop iteration 2
--- Thread #2 - Loop iteration 2
--- Thread #1 - Loop iteration 3
--- Thread #3 - Loop iteration 3
--- Thread #2 - Loop iteration 3
>>> child process done.
ya nour 3in
The sum is equal to : 9
The product is equal to : 2560
这是我编译的方式:gfortran -o fork fork.f90 libfortran-unix.a -lpthread
谁能解释为什么我得到的 sum
等于 9,我该怎么做才能解决这个问题?我希望 sum
等于 3,以便每个线程在第一个值(即 0)上加 1。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)