Parallel.For():在循环外更新变量 [英] Parallel.For(): Update variable outside of loop

查看:24
本文介绍了Parallel.For():在循环外更新变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在研究新的 .NET 4.0 功能.有了这个,我正在尝试使用 Parallel.For 和一个普通的 for(x;x;x) 循环进行简单的计算.

I'm just looking in to the new .NET 4.0 features. With that, I'm attempting a simple calculation using Parallel.For and a normal for(x;x;x) loop.

但是,我在大约 50% 的时间内得到了不同的结果.

However, I'm getting different results about 50% of the time.

long sum = 0;

Parallel.For(1, 10000, y =>
    {
        sum += y;
    }
);

Console.WriteLine(sum.ToString());

sum = 0;

for (int y = 1; y < 10000; y++)
{
   sum += y;
}
Console.WriteLine(sum.ToString());

我的猜测是线程试图同时更新sum".
有没有明显的解决方法?

My guess is that the threads are trying to update "sum" at the same time.
Is there an obvious way around it?

推荐答案

你不能这样做.sum 在您的并行线程之间共享.您需要确保 sum 变量一次只能被一个线程访问:

You can't do this. sum is being shared across you parallel threads. You need to make sure that the sum variable is only being accessed by one thread at a time:

// DON'T DO THIS!
Parallel.For(0, data.Count, i =>
{
    Interlocked.Add(ref sum, data[i]);
});

但是...这是一种反模式,因为您已经有效地序列化了循环,因为每个线程都会锁定 Interlocked.Add.

BUT... This is an anti-pattern because you've effectively serialised the loop because each thread will lock on the Interlocked.Add.

您需要做的是添加小计并在最后合并它们,如下所示:

What you need to do is add sub totals and merge them at the end like this:

Parallel.For<int>(0, result.Count, () => 0, (i, loop, subtotal) =>
    {
        subtotal += result[i];
        return subtotal;
    },
    (x) => Interlocked.Add(ref sum, x)
);

您可以在 MSDN 上找到对此的进一步讨论:http://msdn.microsoft.com/en-us/library/dd460703.aspx

You can find further discussion of this on MSDN: http://msdn.microsoft.com/en-us/library/dd460703.aspx

PLUG:您可以在关于并行编程指南<的第 2 章中找到更多相关信息/a>

PLUG: You can find more on this in Chapter 2 on A Guide to Parallel Programming

以下内容也绝对值得一读...

The following is also definitely worth a read...

并行编程模式: 使用 .NET Framework 4 理解和应用并行模式 - Stephen Toub

这篇关于Parallel.For():在循环外更新变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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