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

2019-02-19 18:20发布

问题:

I have a loop in my code

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

however in the DoWork() function, there are multiple calls to a random number generator which is defined as follows:

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

}

It's static instance so that it is only seeded once. And I can use it throughout the code.

According to MSDN and other stackoverflow threads, this is not threadsafe. Infact, I have noticed at sometimes my code breaks and the random number generator starts generating all zeros (as per the MSDN documentation).

There are other stackoverflow threads, but are rather old and the implementation is slow. I can't afford to lose time on generating the numbers as the program is a scientific computation and is running hundreds of simulations.

I havn't worked with .net since the 2.0 days and I am not sure how the language has evolved to be able to make a fast, efficient, thread-safe RNG.

Here are the previous threads:

Is C# Random Number Generator thread safe?

Correct way to use Random in multithread application

Fast thread-safe random number generator for C#

Note: because I need a fast implementation, I can not use the RNGCryptoServiceProvider which is rather slow.

Note2: I don't have a minimal working code. I don't even know where to begin as I don't know how thread-safety works or have high level knowledge of c#. So it does seem like I am asking for a complete solution.

回答1:

Using the ThreadStatic attribute and a custom getter, you will get a single Random instance per thread. If this is not acceptable, use locks.

public static class Utils
{
    [ThreadStatic]
    private static Random __random;

    public static Random Random => __random??(__random=new Random());
}

The ThreadStatic attribute does not run the initializer on each thread so you are responsible for doing so in your accessor. Also think about your seed initializer, you can use something like

new Random((int) ((1+Thread.CurrentThread.ManagedThreadId) * DateTime.UtcNow.Ticks) )


回答2:

If you have knowledge of how many threads you are running in parallel this may work:

Random rand = new Random();
var randomNums = Enumerable.Range(0, Cnts.MosqPopulation)
                           .Select(_ => rand.Next()).ToList();
Parallel.For(0, Cnts.MosqPopulation, i => 
{
    Random localRand = new Random(randomNums[i]);
    DoWork();
});

Not sure how indistinguishable the resulting distribution would be from a uniform one though.



回答3:

I would consider something like this:

private static int _tracker = 0;

private static ThreadLocal<Random> _random = new ThreadLocal<Random>(() => {
    var seed = (int)(Environment.TickCount & 0xFFFFFF00 | (byte)(Interlocked.Increment(ref _tracker) % 255));
    var random = new Random(seed);
    return random;
});

I'm not a huge fan of ThreadStatic these days. We have better tools than that using ThreadLocal. Just use _random.Value in your parallel loop and it will give you a new Random per thread.

It combines an atomically incrementing value as well as the default behavior of using Environemnt.TickCount. The incrementing value is there to solve the problem of two Random's getting the same seed. Note that this approach only allows 255 randoms to be created. If you need more, then change the size of the mask.

As you already noted, this isn't usable for secure purposes.



回答4:

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();

}