-
MPI question
Hello to everybody I would welcome some info to my question since I am very new to MPI.
Below is a piece of code where I would like every process that I use to print the Hello message and a random number in the range 0 to x (pick(x). If I run this code I take for every process the same random number. Why? How can I take different? Is the time seed the problem? What can I use? Many thanks on behalf
Code:
#include <stdio.h>
#include <mpi.h>
#include <time.h>
#include <limits.h>
#include <stdlib.h>
unsigned time_seed();
int pick(int x);
int main(int argc, char *argv[])
{int i,id,p, rand;
srand48(time(NULL));
srand(time_seed());
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&id);
MPI_Comm_size(MPI_COMM_WORLD,&p);
/* for(i=0; i<p;i++)
{*/
rand=pick(5);
printf("Hello, world from process number %d with rand no %d\n", id, rand);
/* }*/
MPI_Finalize();
return 0;
}
unsigned time_seed()
{
time_t now =time(0);
unsigned char *p = (unsigned char *)&now;
unsigned seed=0;
size_t i;
for (i=0;i<sizeof now;i++)
seed = seed * (UCHAR_MAX+2U) + p[i];
return seed;
}
int pick(int x)
{
static int p1=0;
int p2;
if(p1 == 0)
{
srand(time_seed());
p1=1;
}
p2 = (rand()% (x+1));
return p2;
}
-
Is there any way when I call a random number generator to have different random numbers generated in each process
-
You could incorporate the "rank" in your time_seed() function. This will ensure each process uses a different seed at startup.
/edit Doh, dupe thread
gg
-
yes that's it thank you very much