Random number for each process in MPI

I use MPICH2 to implement "Odd-Even" sorting. I made an implementation, but when I randomized its value for each process, the same number was randomized for all processes.

Here is the code for each process, each process has randomized its value.

int main(int argc,char *argv[])
{
    int  nameLen, numProcs, myID;
    char processorName[MPI_MAX_PROCESSOR_NAME];
    int myValue;

    MPI_Init(&argc,&argv);
    MPI_Comm_rank(MPI_COMM_WORLD,&myID);
    MPI_Comm_size(MPI_COMM_WORLD,&numProcs);    
    MPI_Get_processor_name(processorName,&nameLen);
    MPI_Status status;

    srand((unsigned)time(NULL));
    myValue = rand()%30+1; 

    cout << "myID: " << myID << " value: " << myValue<<endl;
    MPI_Finalize();

    return 0;
 }

why does each process get the same value?

Edit: thanks for the answers :)

I changed the line

 srand((unsigned)time(NULL));

to

 srand((unsigned)time(NULL)+myID*numProcs + nameLen);

and gives different values ​​for each process :)

+4
source share
2 answers

This task is not trivial.

, srand() time(0). , time(0) , ( ). , , , srand() , . .

1. .

, , cat /proc/meminfo /dev/random, , . , - N 1 . , task_id. , , . . . .

2. .

task 0 send-to-all. (, 10 ^ 5 ). . .

+5

, , .

srand docs:

, srand, , rand.

: srand.

+2

All Articles