Is Windows' rand_s thread-safe?

别来无恙 提交于 2020-01-11 08:12:08

问题


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.


回答1:


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:


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.




回答3:


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.




回答4:


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.




回答5:


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



来源:https://stackoverflow.com/questions/143108/is-windows-rand-s-thread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!