how to make a c# thread-safe random number generator

前端 未结 4 722
粉色の甜心
粉色の甜心 2021-01-14 04:27

I have a loop in my code

Parallel.For(0, Cnts.MosqPopulation, i => { DoWork() });

however in the DoWork() function, there a

4条回答
  •  佛祖请我去吃肉
    2021-01-14 05:00

    You can inherit from Random to build a thread safe random class

    public class ThreadsafeRandom : Random
    {
        private readonly object _lock = new object();
    
        public ThreadsafeRandom() : base() { }
        public ThreadsafeRandom( int Seed ) : base( Seed ) { }
    
        public override int Next()
        {
            lock ( _lock )
            {
                return base.Next();
            }
        }
    
        public override int Next( int maxValue )
        {
            lock ( _lock )
            {
                return base.Next( maxValue );
            }
        }
    
        public override int Next( int minValue, int maxValue )
        {
            lock ( _lock )
            {
                return base.Next( minValue, maxValue );
            }
        }
    
        public override void NextBytes( byte[ ] buffer )
        {
            lock ( _lock )
            {
                base.NextBytes( buffer );
            }
        }
    
        public override double NextDouble()
        {
            lock ( _lock )
            {
                return base.NextDouble();
            }
        }
    }
    

    and use an instance of that class

    public static class Utils
    {
        public static readonly Random random = new ThreadsafeRandom();
    
    }
    

提交回复
热议问题