!******************************************************************** ! program : mpi_samp4.f90 ! programmer : makoto nakajima ! description: compute the sum of integers from 1 to n, using ! collective communications. ! 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 !******* 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,dimension(1:100):: recvsum !store sum received from other nodes. !max number of nodes=100 integer:: totsum_gather !total sum (with mpi_gather) integer:: totsum_reduce !total sum (with mpi_reduce) 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 using mpi_gather ******* totsum_gather=0 !initialize total sum recvsum(:)=0 !initialize received sums call mpi_gather(mysum,1,mpi_integer,recvsum(1),1,mpi_integer,& idmom,mpi_comm_world,ierror) if (id==idmom) then !sum up the numbers received totsum_gather=sum(recvsum(1:nproc)) end if !******* gather all sum using mpi_reduce ******* totsum_reduce=0 !initialize total sum call mpi_reduce(mysum,totsum_reduce,1,mpi_integer,& mpi_sum,idmom,mpi_comm_world,ierror) !******* print out results ******* print *,'I am id=',id,' my sum=',mysum,& ' my total sum from gather=',totsum_gather,& ' my total sum from reduce=',totsum_reduce !******* finalize mpi environment ******* call mpi_finalize(ierror) end program main