Is Windows' rand_s thread-safe?
Asked Answered
H

5

13

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.

Helvetii answered 27/9, 2008 at 6:13 Comment(0)
R
11

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.

Rola answered 27/9, 2008 at 6:28 Comment(0)
E
3

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.

Esquimau answered 27/9, 2008 at 6:13 Comment(1)
According to: hype-free.blogspot.com/2008/05/… rand() 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()).Showdown
E
2

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.

Everyone answered 27/9, 2008 at 6:32 Comment(0)
M
0

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.

Manometer answered 27/9, 2008 at 6:53 Comment(0)
S
-2

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

Showdown answered 27/9, 2008 at 6:16 Comment(3)
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.Rigatoni
rand() is not thread-safe, because its internal state in static, like phjr mentioned. rand_s() should be thread-safe, however.Pornocracy
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().Showdown

© 2022 - 2024 — McMap. All rights reserved.