dimanche 5 avril 2015

Correct way to use rand_r for multithredded programs in C/C++

So, I need some help with multithredding in C++. I would like to have my multiple threads call the function usleep with a random number below 800. However, from my understanding, rand_r must be seeded with a different integer in each thread.


My confusion stems from the fact that if I want a different integer to be used for rand_r for each thread, then how can I do this? How can I have a different (ie. random) integer be used for each thread, if I can't create random integers?



static unsigned int consumerseed = 1;
static unsigned int producerseed = 54321;

//producer thread:
void *producer(void *param) {
buffer_item rand;

while (1) {
//sleep for a random period of time:
int producersleeptime = rand_r(&producerseed)%500+100;
usleep(producersleeptime);
//produce an item:

//wait on both semaphores

//attempt to insert into buffer

//signal both semaphores
}
}

//consumer thread:
void *consumer(void *param) {
buffer_item rand;

while (1) {
//sleep for a random period of time:
int consumersleeptime = rand_r(&consumerseed)%600+200;
usleep(consumersleeptime);

//wait on both semaphores

//attempt to remove an item from buffer

//signal both semaphores
}
}


I have the static integers producerseed and consumerseed defined at the top of the program, as global variables. I did it this way because I thought that the calls to rand_r needed to access a static, non-changing memory location.


Is this the correct way to do this? Or do I need different integers for each thread. a different Will this result in any race conditions in my threads? What about the random number generated -- will it be different every time?


Thank you so much for taking the time to look/answer.





Aucun commentaire:

Enregistrer un commentaire