Last Updated: September 09, 2019
·
652
· rcohen

rand() Destroys Parallelism

The stdlib rand() function on unix has a global lock around it provided by many versions of Linux. As such, if rand() is called in performance critical parallel code, performance will tank as each thread or process attempts to acquire this lock. Even if this lock is not acquired, you will still have a race condition on the state of the random number generator and may produce bad (non-random) randomness.

Use rand_r(unsigned int *state) instead in parallel and concurrent applications.

Sources:
man 3 rand [unix command]
http://unixhelp.ed.ac.uk/CGI/man-cgi?rand+3