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

Using stdlib#39;s rand() from multiple threads(从多个线程使用 stdlib 的 rand())

本文介绍了从多个线程使用 stdlib 的 rand()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个线程都运行相同的功能.在其中的每一个中,它们都会多次生成不同的随机数.我们试图通过将 srand(time(0)) 放在函数的开头来做到这一点,但它们似乎都得到了相同的数字.

I have several threads which all run the same function. In each of these they generate a different random number several times. We tried to do this by putting srand(time(0)) at the start of the function, but it seems that they all get the same number.

我们是否需要每个程序只调用一次 srand(time(0)) ,即在 main 的开头(例如),在每个程序的开头被多次调用的函数,还是别的什么?

Do we need to call srand(time(0)) only once per program, i.e at the start of main (for example), at the start of each function that is called several times, or something else?

推荐答案

srand() 种子随机数生成器.您应该只需要在启动期间调用 srand(time(NULL)) 一次.

srand() seeds the random number generator. You should only have to call srand(time(NULL)) once during startup.

也就是说,文档指出:

函数 rand()不可重入的或线程安全,因为它使用隐藏在每次调用时修改的状态.这可能只是种子值被下一次调用使用,或者它可能做一些更精细的事情.为了获得可重现的行为线程应用程序,此状态必须明确.功能rand_r() 提供了一个指向一个 unsigned int,用作状态.这是一个非常少量的状态,所以这个功能会很弱伪随机发生器.尝试drand48_r(3) 代替.

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.

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

The emphasized part of the above is probably the reason why all your threads get the same number.

这篇关于从多个线程使用 stdlib 的 rand()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:从多个线程使用 stdlib 的 rand()

基础教程推荐