...
Consider a multithreaded application which involves a function which returns a random value each time it is invoked. According to POSIX implementation, rand() returns the next pseudorandom number in the sequence determined by an initial seed value. The rand() function updates the seed value, which is stored at a library allocated static memory location. If two threads concurrently invoke the rand() function, it may result in undefined behavior and may also result in rand() returning the same value in both the threads.
...
The compliant solution uses a mutex to make each call to prevent concurrent access to the shared seed value used in rand() library function atomic
Code Block | ||
---|---|---|
| ||
#include <pthread.h> pthread_mutex_t rand_lock = PTHREAD_MUTEX_INITIALIZER; int get_secret() { int secret; pthread_mutex_lock(&rand_lock) ; secret = (rand() % 100) + 100; pthread_mutex_unlock(&rand_lock); return secret; } |
...