jeudi 19 janvier 2017

Generate different random numbers on every processor in C with MPI

I just wanted to generate on every processor different random numbers. But instead of that, I get the same random numbers on every processor.

Here is the output for 4 processors:

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

This is what my code looks like:

    #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));

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

        MPI_Finalize();
        return 0;
}

So my question is: How do I get on every processor different random numbers?




Aucun commentaire:

Enregistrer un commentaire