Parallel.For and For yield different results

前端 未结 3 1895
春和景丽
春和景丽 2021-02-13 15:53

If I run this test:

 var r = new Random();
 var ints = new int[13];
 Parallel.For(0, 2000000, i => {            
     var result = r.Next(1, 7) + r.Next(1, 7)         


        
3条回答
  •  被撕碎了的回忆
    2021-02-13 16:43

    The Random class methods are not thread safe.

    http://msdn.microsoft.com/en-us/library/system.random.next(v=vs.90).aspx#2

    So the first piece of code is just demonstrating some undefined behavior.

    EDIT:

    As for a little speculation, from what little I know about operating systems I believe random number generation is a pretty low level operation and hence might even require a context switch. While this is happening you may end up grabbing the same random number multiple times before it's had a chance to update. This would account for the lopsided distribution.

提交回复
热议问题