問題描述
我有幾個線程都運行相同的功能.在其中的每一個中,它們都會多次生成不同的隨機數.我們試圖通過將 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 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.
上面強調的部分可能是你所有線程得到相同數字的原因.
The emphasized part of the above is probably the reason why all your threads get the same number.
這篇關于從多個線程使用 stdlib 的 rand()的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!