I am trying to produce random numbers for each thread to use, but all the threads produce the same number.
The number changes when I run my program each time, but all the threads produce the same number for a given run.
What should I do to produce different random numbers for each thread?
void *Customer(void *customer_id)
{
unsigned int iseed = (unsigned int)time(NULL);
srand (iseed);
int rastgele = rand() % 3 + 1;
int *id_ptr,customer_idd;
id_ptr=(int *) customer_id;
customer_idd=*id_ptr;
printf("This is thread : %d %d \n",customer_idd,rastgele);
pthread_exit(NULL);
}
You shouldn’t use
randfor pseudo random generation in connection with threads. This function uses a shared state that is common to all threads. This creates dependencies between the PRN drawn by the threads and slows down substantially since the access to the state must be mutexted.Alternatives on POSIX systems would be
nrand48andjrand48that receive a state (that should be thread specific) as their argument. As others said, seeding that state just with a time value is not a good idea, threads may do that at the same moment.