我有几个线程都运行相同的功能。在每一个中,它们都会多次生成不同的随机数。我们试图通过将 srand(time(0))
放在函数的开头来做到这一点,但似乎它们都得到了相同的数字。
我们是否需要每个程序只调用一次 srand(time(0))
,即在 main
的开头(例如),在每个程序的开头被多次调用的函数,还是别的什么?
最佳答案
srand()种子随机数生成器。您应该只需要在启动期间调用一次 srand(time(NULL))
。
也就是说,文档指出:
The function
rand()
is not reentrant or thread-safe, since it uses hidden state that is modified on each call. This might just be the seed value to be used by the next call, or it might be something more elaborate. In order to get reproducible behaviour in a threaded application, this state must be made explicit. The functionrand_r()
is supplied with a pointer to anunsigned int
, to be used as state. This is a very small amount of state, so this function will be a weak pseudo-random generator. Trydrand48_r
(3) instead.
上面强调的部分可能是你所有线程得到相同数字的原因。
https://stackoverflow.com/questions/6161322/