的Parallel.For和对于产生不同的结果 [英] Parallel.For and For yield different results

查看:364
本文介绍了的Parallel.For和对于产生不同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我运行这个测试:

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



我得到以下结果:

I get the following result:

2: 92,14445
3: 0,41765
4: 0,62245
5: 0,82525
6: 1,04035
7: 1,25215
8: 1,0531
9: 0,8341
10: 0,6334
11: 0,4192
12: 0,2109

当我使用常规为:

for (int i = 0; i < 2000000; i++) {
    var result = r.Next(1, 7) + r.Next(1, 7);
    ints[result] += 1;
}



输出是:

The output is:

2: 2,7797
3: 5,58645
4: 8,3414
5: 11,09935
6: 13,8909
7: 16,6731
8: 13,82895
9: 11,10205
10: 8,3424
11: 5,5712
12: 2,7845

最后的结果是一个三角形分布,这是预期的输出。

The last result is a Triangular Distribution and it is the expected output.

我的问题的目的不是讨论并行的适用性。现在的问题是,为什么的Parallel.For行为呀?

The purpose of my question is not to discuss the applicability of parallelism. The question is why the Parallel.For behaves that way?

推荐答案

Random类方法不是线程安全的。

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.

编辑:

至于稍炒,从什么小我知道的操作系统,我相信随机数生成是一个相当低的水平运行,因此甚至可能的需要的上下文切换。当发生这种情况你可能最终相同的随机数多次抓住它有机会更新之前。这将占到分配不平衡。

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.

这篇关于的Parallel.For和对于产生不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆