Is Windows' rand_s thread-safe?
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.
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.
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.