gpt4 book ai didi

c++ - 从多个线程使用 stdlib 的 rand()

转载 作者:IT老高 更新时间:2023-10-28 12:29:15 26 4
gpt4 key购买 nike

我有几个线程都运行相同的功能。在每一个中,它们都会多次生成不同的随机数。我们试图通过将 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 function rand_r() is supplied with a pointer to an unsigned int, to be used as state. This is a very small amount of state, so this function will be a weak pseudo-random generator. Try drand48_r(3) instead.

上面强调的部分可能是你所有线程得到相同数字的原因。

关于c++ - 从多个线程使用 stdlib 的 rand(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6161322/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com