随机数发生器产生唯一的单随机数

随机数发生器产生唯一的单随机数

本文介绍了随机数发生器产生唯一的单随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下功能:

//Function to get random number
public static int RandomNumber(int min, int max)
{
    Random random = new Random();
    return random.Next(min, max);
}

我怎么称呼它:

byte[] mac = new byte[6];
for (int x = 0; x < 6; ++x)
    mac[x] = (byte)(Misc.RandomNumber((int)0xFFFF, (int)0xFFFFFF) % 256);

如果我在运行期间加强了环路与调试,我得到不同的值(这是我想要的)。
但是,如果我把低于code断点两行中,陆委会阵列的所有成员都有同等的价值。

If I step that loop with the debugger during runtime I get different values (which is what I want).However, if I put a breakpoint two lines below that code, all members of the "mac" array have equal value.

为什么会发生呢?

推荐答案

你做的每一次新的随机()它正在使用的时钟初始化。这意味着,在紧密循环,你得到的价值很多次一样。你应该保持一个随机实例,并继续使用下一页相同实例。

Every time you do new Random() it is initialized using the clock. This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the same instance.

//Function to get random number
private static readonly Random random = new Random();
private static readonly object syncLock = new object();
public static int RandomNumber(int min, int max)
{
    lock(syncLock) { // synchronize
        return random.Next(min, max);
    }
}


编辑(见注释):为什么我们需要一个锁定此处

基本上,下一页是要修改随机实例的内部状态。如果我们这样做,在从多个线程同时,你的可能的争论我们刚刚做出的结果更随机的,但我们是什么的真正的做的是潜在的打破内部实现,而且我们还可以从开始不同的线程,它的得到相同的数字可能的一个问题 - 而且可能不会。什么内部发生的是更大的问题,虽然保证;因为随机做的不可以使线程安全的任何保证。因此,有两种有效的方法:

Basically, Next is going to change the internal state of the Random instance. If we do that at the same time from multiple threads, you could argue "we've just made the outcome even more random", but what we are actually doing is potentially breaking the internal implementation, and we could also start getting the same numbers from different threads, which might be a problem - and might not. The guarantee of what happens internally is the bigger issue, though; since Random does not make any guarantees of thread-safety. Thus there are two valid approaches:


  • 同步,以便我们不会从不同的线程同时访问

  • 每个线程使用不同的随机实例

  • synchronize so that we don't access it at the same time from different threads
  • use different Random instances per thread

无论是可罚款;但一个突变的实例从在同一时间多个来电是自找麻烦。

either can be fine; but mutating a single instance from multiple callers at the same time is just asking for trouble.

锁定实现这些方法的第一个(简单);然而,另一种方法可能是:

The lock achieves the first (and simpler) of these approaches; however, another approach might be:

private static readonly ThreadLocal<Random> appRandom
     = new ThreadLocal<Random>(() => new Random());

这是那么每个线程,所以你并不需要同步。

this is then per-thread, so you don't need to synchronize.

这篇关于随机数发生器产生唯一的单随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 14:22