Does one need to call srand() C function per thread or per process to seed the randomizer?

杀马特。学长 韩版系。学妹 提交于 2019-12-19 05:24:04

问题


The caption pretty much says it.

PS. This is for C++ Windows program.


回答1:


According to the MSDN documentation on srand() (assuming you are using Microsoft's C runtime library), the seed is thread-local, so you need to call srand() for each thread that is using rand(). Note that this may not be the case in other implementations.

Quoting from MSDN:

The srand function sets the starting point for generating a series of pseudorandom integers in the current thread.




回答2:


Even if the answer weren't platform specific I'd suggest you avoid srand() and use <random> instead. Not only does the C++11 <random> library provide clear semantics in multithreaded programs but it also provides much better facilities for random number generation. It provides several different random number generators to meet different quality, speed, and size requirements, and many standard distributions so you won't make the mistakes people often do when using rand.




回答3:


No, as per the Standard, because once you call srand() it affects rand() calls from all threads.

C library function srand() is single-threaded just like all other functions are, which means if you call srand() from one thread, it affects the number-seqeunce generated from rand() in other threads as well.

But Microsoft provides non-standard srand() which does require you to call it from all threads.




回答4:


Be aware that the state is fiber-local (which is more fine-grained than thread-local). Thus, srand has to be called for each fiber. (Of course, when you don't use fibers it's equivalent to thread-local.)



来源:https://stackoverflow.com/questions/10159728/does-one-need-to-call-srand-c-function-per-thread-or-per-process-to-seed-the-r

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