Random.Next()有时在单独的线程中返回相同的数字
我有以下课程
class Program
{
static Random _Random = new Random();
static void Main(string[] args)
{
...
for (int i = 0; i < no_threads; ++i)
{
var thread = new Thread(new ThreadStart(Send));
thread.Start();
}
...
}
static void Send()
{
...
int device_id = _Random.Next(999999);
...
}
}
代码创建指定数量的线程,启动每个线程,并为每个线程分配随机的device_id
.由于某些原因,创建的前两个线程通常具有相同的device_id
.我不知道为什么会这样.
The code creates the specified number of threads, starts each one, and assigns each thread a random device_id
. For some reason, the first two threads that are created often have the same device_id
. I can't figure out why this happens.
随机不是线程安全的-您不应该在多个线程中使用同一实例.它可能比仅返回相同的数据还要糟糕得多-通过在多个线程中使用它,您可以将其卡住",使其始终 返回0,IIRC.
Random is not thread-safe - you shouldn't be using the same instance from multiple threads. It can get much worse than just returning the same data - by using it from multiple threads, you can get it "stuck" in a state where it will always return 0, IIRC.
很明显,您不只是希望在几乎同时为每个线程创建一个新实例,因为它们最终将具有相同的种子...
Obviously you don't just want to create a new instance for each thread at roughly the same time, as they'll end up with the same seeds...
我有一个文章,其中对此进行了详细介绍并提供了一个实现使用递增种子延迟地实例化每个线程的Random
实例.
I have an article which goes into the details of this and provides an implementation which lazily instantiates one instance of Random
per thread using an incrementing seed.