Random.Next()有时在单独的线程中返回相同的数字 [英] Random.Next() sometimes returns same number in separate threads

查看:69
本文介绍了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.

这篇关于Random.Next()有时在单独的线程中返回相同的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆