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

前端 未结 4 719
粉色の甜心
粉色の甜心 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:44

    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.

提交回复
热议问题