使用MPI在C中的每个处理器上生成不同的随机数

时间:2017-01-19 10:21:57

标签: c random mpi

我只想在每个处理器上生成不同的随机数。但不是那样,我在每个处理器上得到相同的随机数。

以下是4个处理器的输出:

Processor 0: 0 random number is 21
Processor 0: 1 random number is 62
Processor 0: 2 random number is 27
Processor 0: 3 random number is 90
Processor 0: 4 random number is 59

Processor 1: 0 random number is 21
Processor 1: 1 random number is 62
Processor 1: 2 random number is 27
Processor 1: 3 random number is 90
Processor 1: 4 random number is 59

Processor 2: 0 random number is 49
Processor 2: 1 random number is 21
Processor 2: 2 random number is 62
Processor 2: 3 random number is 27
Processor 2: 4 random number is 90

Processor 3: 0 random number is 49
Processor 3: 1 random number is 21
Processor 3: 2 random number is 62
Processor 3: 3 random number is 27
Processor 3: 4 random number is 90

这就是我的代码:

    #include <stdlib.h>
    #include <time.h>
    #include <stdio.h>
    #include <mpi.h>

    typedef struct{
        int myrank;
        int numprocs;
        int *range;
    } SubD;

    void compRange(SubD *s, int myrank, int numprocs){
        s->myrank = myrank;
        s->numprocs = numprocs;

        // Allocate memory
        s->range = malloc((numprocs+1) * sizeof(int));
        // Fill range with random numbers between 0 and 99
        for(int p=0; p<=numprocs; p++){
            s->range[p] = rand()%100;
        }

        for(int p=0; p<s->numprocs; p++){
            if(myrank == p){
            for(int k=0; k<=numprocs; k++){
                printf("Processor %d: %d random number is %d\n", p, k, s->range[k]);
            }
            printf("\n");
            }
        }
    }


    int main(int argc, char **argv){

        int myrank;           // Rank of processor
        int numprocs;         // Number of processes
        MPI_Init(&argc, &argv);
        MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
        MPI_Comm_size(MPI_COMM_WORLD, &numprocs);

       time_t t;     
        /* Intializes random number generator */
       srand((unsigned) time(&t));

        SubD s;
        compRange(&s, myrank, numprocs);

        MPI_Finalize();
        return 0;
}

所以我的问题是:如何让每个处理器获得不同的随机数?

0 个答案:

没有答案