# L-7 MCS 572 Wed 11 Sep 2024 : dynamic_loaddist.jl # Illustration of dynamic load balancing with MPI.jl. # To run, type # mpiexecjl -n 4 julia dynamic_loaddist.jl # at the command prompt. using MPI MPI.Init() COMM = MPI.COMM_WORLD """ function manager(p::Int, n::Int, verbose::Bool=true) distributes n jobs to p-1 workers and prints the received results. Assumed is that n is at least equal to p-1. """ function manager(p::Int, n::Int, verbose::Bool=true) if verbose println("Manager distributes ", n, " jobs to ", p-1, " workers ...") end result = "" for j=1:p-1 println("-> manager sends job ", j, " to worker ", j) MPI.send(j, COMM; dest=j, tag=11) end jobcnt = p-1 done = 0 while done < p-1 for i=1:p-1 messageSent = MPI.Iprobe(COMM; source=i) if messageSent data = MPI.recv(COMM; source=i) println("-> manager received ", data, " from ", i) result = string(result, data) jobcnt = jobcnt + 1 if jobcnt > n MPI.send(-1, COMM; dest=i, tag=11) done = done + 1 else nbr = 1 + (jobcnt % p) MPI.send(nbr, COMM; dest=i, tag=11) end end end end println("result : ", result) println("number of characters : ", length(result)) println(" number of jobs : ", n) end """ function worker(i::Int, verbose::Bool=true) The i-th worker receives a number. The worker terminates if the number is -1, otherwise it sends to the manager the corresponding character following 'a'. """ function worker(i::Int, verbose::Bool=true) println("Worker ", i, " says hello.") while true nbr = MPI.recv(COMM; source=0, tag=11) println("-> worker ", i, " received ", nbr) if nbr == -1 break end chrnbr = Char(Int('a') + nbr) MPI.send(chrnbr, COMM; dest=0, tag=11) end end """ function main(verbose::Bool=true) runs a manager/worker dynamic load distribution. """ function main(verbose::Bool=true) myid = MPI.Comm_rank(COMM) size = MPI.Comm_size(COMM) #if myid == 0 # print("Give the number of jobs : ") # line = readline(stdin) # njobs = parse(Int, line) #end njobs = 10 MPI.Barrier(COMM) if myid == 0 manager(size, njobs) else worker(myid) end MPI.Barrier(COMM) end main()