views:

1077

answers:

5

Just as in title. Is suspect it is, but I couldn't find it anywhere explicitly stated. And for this property I wouldn't like to rely on speculations.

A: 

I can't think of any reason why rand_s() or even rand() wouldn't be thread safe.

Jeff Hubbard
Okay, but it's still a speculation. For example rand() stores its current seed in a variable shared by all threads... And in POSIX there are special functions that are designed for use inside threads.
phjr
rand() is not thread-safe, because its internal state in static, like phjr mentioned. rand_s() should be thread-safe, however.
Chris Jester-Young
posted your commented as a community answer chris
Simucal
As I responded to Simucal, the VC runtime apparently enforces static variables being stored in the TLS, meaning rand() is as completely thread safe as rand_s().
Jeff Hubbard
+3  A: 

Chris said: rand() is not thread-safe because its internal state is static, but rand_s() should be thread-safe, however.

Jeff added however that with the multithreaded version of MSVCRT, rand()'s state is held in thread-local storage, so it's okay still.

Simucal
According to: http://hype-free.blogspot.com/2008/05/multi-threaded-visual-c-rand.htmlrand() stores its state in the TLS, meaning it's thread-safe from the VC environment (which is implied by the specific question regarding rand_s()).
Jeff Hubbard
Thanks, Simucal, and Jeff!
Chris Jester-Young
+6  A: 

If you use the multithreaded version of the CRT, all functions are thread safe, because any thread-specific information is stored in TLS. rand_s actually doesn't use state information in the first place, since it just calls an OS API, so question of thread-safety doesn't arise for rand_s. rand(), however depends on a seed value to generate a random number.

+2  A: 

Visual Studio comes with the source to the runtime library. While some of it can be rather painful to wade through, rand_s() is pretty simple.

All rand_s() does is call SystemFunction036() in ADVAPI32.DLL to get the random value. Anything in ADVAPI32.DLL should be thread-safe.

For its part, rand_s() gets the pointer to that function in a thread-safe manner.

Michael Burr
A: 

I don't know if rand_s is thread-safe, but it seems like it probably is, since it seems to make a round-trip to the OS for entropy. (as long as you link to the VC++ multi-thread CRT, all bets are off if you link to the single-thread one)

If it's supported by windows CRT, you can try a call to rand_r which is the posix reentrant version of rand. OR even better boost::random, if you're already using boost.

considering how pervasive multi-threading will be soon, no one should be using rand() anymore in new code - always try to use rand_r/rand_s/boost/various platform-dependent secure rands/etc.