Search code examples
fortranopenmpi

Get different random numbers on each thread using mpi, fortran


I have a basic program which sends a message from thread to thread and replaces a character each time. My problem is that the random number generated in each thread is always the same. Here is my code:

if (me+1 == npe) then
        a = 0
    else
        a = me + 1
    end if

    if (me == 0) then
        b = npe-1
    else
        b = me-1
    end if

    if (me == 0) then
        call MPI_Send(msg, len(msg), MPI_CHARACTER, a, tag, comm, ierr)
    else
        call MPI_Recv(msg, len(msg), MPI_CHARACTER, b, tag, comm, stat, ierr)
        call random_number(u)
        j = FLOOR(14*u)
        msg(j:j) = "?"
        call MPI_Send(msg, len(msg), MPI_CHARACTER, a, tag, comm, ierr)
    end if
    if (me == 0) then
        call MPI_Recv(msg, len(msg), MPI_CHARACTER, b, tag, comm, stat, ierr)
end if

me = thread number, npe = total number of threads

everything works except for the random generated number. I tried using call random_seed(me) but it doesn't work.


Solution

  • You are not using RANDOM_SEED() correctly. With a single (scalar) dummy argument, you are in fact querying SIZE, which

    specifies the minimum size of the arrays used with the PUT and GET arguments.

    The correct usage is

    call random_seed(put=seed)
    

    where seed is an array (of size 12 on my machine/gfortran).

    See the documentation for an example that you can adjust to your needs, i.e. use a different seed for each process. You could, e.g. choose a different prime in pcg according to the current rank. Do not multiply with the rank since this might give a zero seed, which is explicitly mentioned not to do in the reference...