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. Will this result in any race conditions in my threads? What about the random number generated -- will it be different every time?
Edit 1: Okay, so the answer to that question was basically that it is incorrect. You need a unique seed integer for each thread. This can come from, for example, time() or the p_thread_self() id. I'm still confused as to how to implement this exactly, but I will work on it and report back. Right now I decided to use p_thread_self as the seed for each thread.
Thank you so much for taking the time to look/answer.