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

前端 未结 4 685
粉色の甜心
粉色の甜心 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 04:51

    I would consider something like this:

    private static int _tracker = 0;
    
    private static ThreadLocal _random = new ThreadLocal(() => {
        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.

提交回复
热议问题