简体   繁体   English

MPI:rand() 在每次运行中为所有进程提供相同的常数

[英]MPI: rand() gives the same constant numbers across all processes in every run

I would like to ask a question about rand() in the context of (Open)MPI.我想在 (Open)MPI 的上下文中问一个关于 rand() 的问题。 We were given an implementation task in our parallel programming course - create an MPI application in which all participant processes chose one leader (randomly - they have to "vote").在我们的并行编程课程中,我们获得了一项实施任务 - 创建一个 MPI 应用程序,其中所有参与者进程选择一个领导者(随机 - 他们必须“投票”)。 My program looks like this:我的程序是这样的:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>
#include <mpi.h>

int main (int argc, char *argv[]) {
    int rank, size, vote, result;

    MPI_Init(&argc, &argv);

    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    vote = rand(); // Each process' vote.
    printf("%d: %d\n",rank+1, vote); // Only for debugging purposes here.

    MPI_Allreduce(&vote, &result, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
    result = (result & INT_MAX) % size + 1; // Select the leader.

    printf("Process %*d/%d: %d is the leader.\n", (int)(ceil(log10(size+1))), rank+1, size, result);

    MPI_Finalize();
    return 0;
}

The problem is, when I compile and run it using OpenMPI1.6, every process' vote is 1804289383, no matter how many processes is the program started with.问题是,当我使用 OpenMPI1.6 编译和运行它时,无论程序启动多少个进程,每个进程的投票都是 1804289383。 The number is always the same in every new run of the program.在程序的每次新运行中,该数字始终相同。 Thus, if I run mpirun -np 7 ./a.out, the leader is always number 5, if I run it with -np 8, the first process is always the leader and so on...因此,如果我运行 mpirun -np 7 ./a.out,领导者总是数字 5,如果我用 -np 8 运行它,第一个进程总是领导者等等......

Could please anyone explain me what am I doing wrong and how to fix this behaviour?请任何人解释我做错了什么以及如何解决这种行为?

Thank you very much.非常感谢。

你必须播种你的随机数生成器,例如

srand(time(NULL) + rank);

You are not providing a seed to you random function.您没有为您的随机函数提供种子。 The 'usual' seed is time(NULL) although you might want to check something that a bit more flexible, like Mersenne Twister. “通常”的种子是time(NULL)虽然你可能想要检查一些更灵活的东西,比如 Mersenne Twister。

A good random number generator for C 一个很好的 C 随机数生成器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM