C# 随机数生成器线程安全吗? [英] Is C# Random Number Generator thread safe?
问题描述
是 C# 的 Random.Next()
方法线程安全吗?
Is C#'s Random.Next()
method thread safe?
推荐答案
Next
方法中没有做任何特殊的事情来实现线程安全.但是,它是一个实例方法.如果您不跨不同线程共享 Random
的实例,则不必担心实例内的状态损坏.不要在没有持有某种排他锁的情况下跨不同线程使用 Random
的单个实例.
There's nothing special done in the Next
method to achieve thread safety. However, it's an instance method. If you don't share instances of Random
across different threads, you don't have to worry about state corruption within an instance. Do not use a single instance of Random
across different threads without holding an exclusive lock of some sort.
Jon Skeet 有几篇关于这个主题的好帖子:
Jon Skeet has a couple nice posts on this subject:
正如一些评论者所指出的那样,使用 Random
的不同实例存在另一个潜在问题,这些实例是线程专有的,但种子相同,因此会导致伪随机数的相同序列,因为它们可以同时创建或在彼此的时间上很接近.缓解该问题的一种方法是使用主 Random
实例(由单个线程锁定)生成一些随机种子并为每个其他线程初始化新的 Random
实例使用.
As noted by some commentators, there is another potential problem in using different instances of Random
that are thread-exclusive, but are seeded identically, and therefore induce the identical sequences of pseudorandom numbers, because they may be created at the same time or within close temporal proximity of each other. One way to alleviate that issue is to use a master Random
instance (which is locked by a single thread) to generate some random seeds and initialize new Random
instances for every other thread to use.
这篇关于C# 随机数生成器线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!