我正在编写一个MPI程序,在该程序中,我允许每个进程在需要某个进程的经过的时间内生成它的自己的随机数具有相同的随机数,并通过某些其他过程生成。例如,一个简单的printf语句:
Process 1 has generated the number 19
Process 2 has generated the number 8
Process 3 has generated the number 19
.
.
因此,进程1和3生成了相同的随机数。另外,为了确保我可以获得生成的相同随机数,我将仅限制为整数值,而不是双精度或浮点型。
我写过:
#include <stdio.h>
#include "mpi.h"
#include <stdlib.h>
#include <time.h>
#define numprocess 20
int main(int argc, char *argv[])
{
int rank,size;
int rand_value;
int lower,upper;
MPI_Status status;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
upper = 20;
lower = 0;
rand_value = rand()%(upper-lower);
printf("Process %d generated a random number of %d\n",rank,rand_value);
MPI_Finalize();
return 0;
}
但是我得到的输出是:
Process 0 generated a random number of 7
Process 2 generated a random number of 7
Process 8 generated a random number of 7
Process 1 generated a random number of 7
Process 3 generated a random number of 7
Process 4 generated a random number of 7
Process 5 generated a random number of 7
Process 6 generated a random number of 7
Process 7 generated a random number of 7
Process 9 generated a random number of 7
Process 11 generated a random number of 7
Process 10 generated a random number of 7
Process 16 generated a random number of 7
Process 17 generated a random number of 7
Process 19 generated a random number of 7
Process 13 generated a random number of 7
Process 12 generated a random number of 7
Process 18 generated a random number of 7
Process 15 generated a random number of 7
Process 14 generated a random number of 7
答案 0 :(得分:3)
您可以这样:
srand(time(NULL)+rank * 10000);
使用time
将确保您在每次运行中获得不同的输出,并且使用rank
确保(以较高的概率,但不是100%)确保每个线程都有不同的种子。常数10000是一个任意常数,只是为了减少两个线程意外获得相同种子的可能性。
但这是一种更好的方法:
const int current_time = time(NULL);
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
srand(current_time+rank);
或使用MPI_Bcast
int current_time;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
if(rank == 0)
current_time = time(NULL);
MPI_Bcast(¤t_time, 1, MPI_INT, 0, MPI_COMM_WORLD);
srand(current_time+rank);