!******************************************************************** ! program : mpi_samp3.f90 ! programmer : makoto nakajima ! description: compute the sum of integers from 1 to n, using ! one-to-one communication. ! date : april 25, 2006 !******************************************************************** program main implicit none !prohibit implicit declaration of variables include 'mpif.h' !include mpi library !******* variables related mpi ******* integer:: ierror !return error message from mpi subroutines integer:: id !identification number of each processor integer:: nproc !total number of processors integer,dimension(mpi_status_size):: mpi_status !used to store status of mpi_recv !******* other variable declaration ******* integer,parameter:: idmom=0 !node which works as the frontend. integer,parameter:: n=1000 !sum(1:n) is computed. integer:: n_each !number if integers assigned to each node integer:: n_top !for each node, sum(n_top:n_end) is caomputed. integer:: n_end integer:: n0 !intdex for loop integer:: mysum !sum of integer assigned to each node integer:: recvsum !sum received from other nodes integer:: totsum !total sum of integers integer:: idnow !used for loop of nodes integer:: tag !used for tag of send/recv operations !******* initialization ******* !initialization of mpi environment call mpi_init(ierror) !obtain id for each node call mpi_comm_rank(mpi_comm_world, id, ierror) !returns the number of nodes call mpi_comm_size(mpi_comm_world, nproc, ierror) !******* compute Neach ******* !determies number of integer assigned to each node do n0=1,n if (n0*nproc>=n) exit end do !******* compute Ntop and Nend ******* n_top=id*n0+1 n_end=min((id+1)*n0,n) !notice n0*nproc might be above n !******* compute sum of assigned integers ******* mysum=0 do n0=n_top,n_end mysum=mysum+n0 end do !******* gather all sum to idmom ******* if (id==idmom) then totsum=0 !initialize totsum do idnow=0,nproc-1 !loop for all nodes if (idnow==idmom) then !myself totsum=totsum+mysum else !receive from others! tag=idnow+100 !set tag call mpi_recv(recvsum,1,mpi_integer,idnow,tag,& mpi_comm_world,mpi_status,ierror) totsum=totsum+recvsum !add received sum end if end do else totsum=0 tag=id+100 ! set tag call mpi_send(mysum,1,mpi_integer,idmom,tag,& mpi_comm_world,ierror) end if !******* print out results ******* print *,'I am id=',id,' my sum=',mysum,' my total sum=',totsum !******* finalize mpi environment ******* call mpi_finalize(ierror) end program main