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.
I can't think of any reason why rand_s() or even rand() wouldn't be thread safe.
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.
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.
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.
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.