如何实现线程安全的随机数

How to implement a thread-safe random

试图找到并理解在 .NET Core 2.x 或更高版本中实现线程安全数字生成器的最佳方法

首先我发现了这个 - https://web.archive.org/web/20160326010328/http://blogs.msdn.com/b/pfxteam/archive/2009/02/19/9434171.aspx

通读之后,我觉得有几个“好”方法 -

  1. ThreadStatic随机实例,用全局随机实例生成种子
  2. ThreadStatic 随机实例,使用全局 RNGCryptoServiceProvider 生成种子

如果需要强加密随机性,基本上您会选择后者。

经过一些额外的研究,我发现自从 .NET Core 2.x System.Random class 被修改后,默认种子生成不再主要依赖于系统计时器. (https://blogs.siliconorchid.com/post/coding-inspiration/randomness-in-dotnet)

问题 - 这对线程安全随机class的实现有何影响?

参考第一个 link 我分享代码解决方案 -

public static class RandomGen2
{
    private static Random _global = new Random();
    [ThreadStatic]
    private static Random _local;

    public static int Next()
    {
        Random inst = _local;
        if (inst == null)
        {
            int seed;
            lock (_global) seed = _global.Next();
            _local = inst = new Random(seed);
        }
        return inst.Next();
    }
}

自 dotnet 核心 2.x 调整甚至需要全局锁定种子生成器?还是只需要一个基本的 ThreadStatic 随机实例?比如-

    public static class ThreadSafeRandom
    {
        [ThreadStatic]
        private static Random _local;

        public static int Next()
        {
            Random inst = _local;
            if (inst == null)
            {
                _local = inst = new Random();
            }
            return inst.Next();
        }
    }
  1. System.Random class 使用默认构造函数实例化时使用的算法已更改为新算法,但 class 仍然不是 thread-safe,所以旧技术就像仍然需要使用 [ThreadStatic]
  2. 在 .NET Core 中,the default seed value is produced by the thread-static, pseudo-random number generator.这意味着您不再需要实现全局种子生成器。
  3. 当你真的想确保你的随机数是安全的时候使用RandomNumberGenerator。例如,如果您只想显示随机的每日消息,请使用 System.Random,但如果您想生成随机的秘密字符串,请使用 RandomNumberGenerator.

从 .NET 6 开始,您可以使用 Random.Shared 获取 Random 的 thread-safe 实例。

文档是这样说的:

Provides a thread-safe Random instance that may be used concurrently from any thread.

https://docs.microsoft.com/en-us/dotnet/api/system.random.shared?view=net-6.0

没必要再花哨了。

要获得一个随机整数,您只需要做:

int number = Random.Shared.Next();

如果您想要密码学上的强随机性,那么 Eric Lippert 的 BetterRandom 是可行的方法:

public static class BetterRandom
{
    private static readonly ThreadLocal<System.Security.Cryptography.RandomNumberGenerator> crng = new ThreadLocal<System.Security.Cryptography.RandomNumberGenerator>(System.Security.Cryptography.RandomNumberGenerator.Create);
    private static readonly ThreadLocal<byte[]> bytes = new ThreadLocal<byte[]>(() => new byte[sizeof(int)]);
    public static int NextInt()
    {
        crng.Value.GetBytes(bytes.Value);
        return BitConverter.ToInt32(bytes.Value, 0) & int.MaxValue;
    }
    public static double NextDouble()
    {
        while (true)
        {
            long x = NextInt() & 0x001FFFFF;
            x <<= 31;
            x |= (long)NextInt();
            double n = x;
            const double d = 1L << 52;
            double q = n / d;
            if (q != 1.0)
                return q;
        }
    }
}

从这里开始阅读更多内容:https://ericlippert.com/2019/01/31/fixing-random-part-1/