From a1ccba00f70b0ee7c961922c305367e713259a4c Mon Sep 17 00:00:00 2001 From: Jonas 'Sortie' Termansen Date: Wed, 8 Jan 2014 23:39:13 +0100 Subject: [PATCH] Thread-secure rand(3). --- libc/stdlib/rand.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/libc/stdlib/rand.cpp b/libc/stdlib/rand.cpp index 15495d1b..4d0b7a4e 100644 --- a/libc/stdlib/rand.cpp +++ b/libc/stdlib/rand.cpp @@ -22,9 +22,11 @@ *******************************************************************************/ +#include #include #include +static pthread_mutex_t rand_mutex = PTHREAD_MUTEX_INITIALIZER; static uint32_t m_w = 1337; static uint32_t m_z = 37; @@ -37,11 +39,16 @@ static uint32_t random_32_bits() extern "C" int rand() { - return (int) (random_32_bits() % ((uint32_t) RAND_MAX + 1)); + pthread_mutex_lock(&rand_mutex); + int result = (int) (random_32_bits() % ((uint32_t) RAND_MAX + 1)); + pthread_mutex_unlock(&rand_mutex); + return result; } extern "C" void srand(unsigned int seed) { + pthread_mutex_lock(&rand_mutex); m_w = seed >> 16 & 0xFFFF; m_z = seed >> 0 & 0xFFFF; + pthread_mutex_unlock(&rand_mutex); }