开发者

Multithreading Random.NextDouble()

Which error/problems (if any) are to be expected, if NextDouble() of the same System.Random instance is called from multiple threads co开发者_如何学JAVAncurrently - without any locking ?


In short, System.Random is not thread-safe.
For a longer answer see this awesome post which explains the issue in details.


You could corrupt the object. The Random object uses an internal array of seed values, and calling an of the Next update that array.

Don't do it.


Since there is no guarantee of thread safety, there is no defined or sensible way of answering "nothing", "anything", and "boom" are all valid answers, and indeed it could change between versions, platforms, architecture, etc.

Have you considered making it [ThreadStatic] so each thread can have an isolated version automatically? (initialisation should probably be double-checked per thread).


It is difficult to tell without reverse engineering the implementation entirely. However, one thing that could happen is that the same "random" number be returned multiple times in a row (across multiple threads).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜