問題描述
我有幾個線程都運行相同的功能.在其中的每一個中,它們都會多次生成不同的隨機(jī)數(shù).我們試圖通過將 srand(time(0))
放在函數(shù)的開頭來做到這一點,但它們似乎都得到了相同的數(shù)字.
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.
我們是否需要每個程序只調(diào)用一次 srand(time(0))
,即在 main
的開頭(例如),在每個程序的開頭被多次調(diào)用的函數(shù),還是別的什么?
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() 種子隨機(jī)數(shù)生成器.您應(yīng)該只需要在啟動期間調(diào)用 srand(time(NULL))
一次.
srand() seeds the random number generator. You should only have to call srand(time(NULL))
once during startup.
也就是說,文檔指出:
函數(shù) rand()
是不可重入的或線程安全,因為它使用隱藏在每次調(diào)用時修改的狀態(tài).這可能只是種子值被下一次調(diào)用使用,或者它可能做一些更精細(xì)的事情.為了獲得可重現(xiàn)的行為線程應(yīng)用程序,此狀態(tài)必須明確.功能rand_r()
提供了一個指向一個 unsigned int
,用作狀態(tài).這是一個非常少量的狀態(tài),所以這個功能會很弱偽隨機(jī)發(fā)生器.嘗試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 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.
上面強(qiáng)調(diào)的部分可能是你所有線程得到相同數(shù)字的原因.
The emphasized part of the above is probably the reason why all your threads get the same number.
這篇關(guān)于從多個線程使用 stdlib 的 rand()的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!