使用mpi,fortran在每个线程上获取不同的随机数

Get different random numbers on each thread using mpi, fortran

我有一个基本程序,它从一个线程到另一个线程发送一条消息,每次替换一个字符。我的问题是每个线程中生成的随机数总是相同的。这是我的代码:

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 = 线程数,npe = 线程总数

除了随机生成的数字外,一切正常。我尝试使用 call random_seed(me) 但它不起作用。

您没有正确使用 RANDOM_SEED()。使用单个(标量)虚拟参数,您实际上是在查询 SIZE,其中

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

正确的用法是

call random_seed(put=seed)

其中 seed 是一个数组(在我的机器上大小为 12/gfortran)。

查看 the documentation 示例,您可以根据需要进行调整,即为每个进程使用不同的种子。你可以,例如根据当前排名在 pcg 中选择不同的素数。 不要与排名相乘,因为这可能会产生零种子,参考文献中明确提到不要这样做...