Fast thread-safe random number generator for C#

前端 未结 3 1805
自闭症患者
自闭症患者 2021-01-26 06:57

I need to quickly generate random floating-point numbers across multiple running threads. I\'ve tried using System.Random, but it\'s too slow for my needs and it re

3条回答
  •  遥遥无期
    2021-01-26 07:25

    If Random is giving you the same numbers then you're probably using it incorrectly, either by creating many instances in close succession (meaning that they'll all use the same seed and so generate the same sequence), or by using a single instance across several threads (thereby "breaking" that instance since it's not safe for multithreaded use).

    If the speed and randomness of Random are good enough for you when running in a single thread then you could try wrapping it in a ThreadLocal to ensure a separate instance for each thread in your multithreaded scenario:

    var number = _rng.Value.NextDouble() * 100;
    
    // ...
    
    private static int _staticSeed = Environment.TickCount;
    private static readonly ThreadLocal _rng = new ThreadLocal(() =>
        {
            int seed = Interlocked.Increment(ref _staticSeed) & 0x7FFFFFFF;
            return new Random(seed);
        });
    

提交回复
热议问题