使用嵌套的Parallel.For [英] Using nested Parallel.For

查看:193
本文介绍了使用嵌套的Parallel.For的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个例子:

var x = 0;

for (var i = 0; i < 100; i++ )
{
    for (var a = i+1; a < 100; a++)
        x += 1;
}

当打印x我们的总是的获得4950怎么样,如果我想并行处理呢?

When printing x we always get 4950. What about if I want to parallelise this?

这是我想出

Parallel.For(0, 100, i => Parallel.For(i + 1, 100, a => { x += 1; }));

然而这不打印4950我每次运行它​​。为什么呢?

However this does Not print 4950 each time I run it. Why?

推荐答案

并行扩展可帮助您创建任务,分配,运行和交会,在一个近乎强制性语法。它的做的是采取什么样的每个线程安全的护理(的陷阱的)。您正在尝试做并行线程同时更新一个共享变量。要正确地做这样的事,你必须引进如锁定。

Parallel Extensions helps you with task creation, allocation, running and rendezvous, in a near-imperative syntax. What it doesn't do is take care of every kind of thread safety (one of the pitfalls). You are trying to make parallel threads simultaneously update a single shared variable. To do anything like this correctly, you have to introduce e.g. locking.

我不知道你想做什么。我假设你的code是只是一个占位符或实验。并行只适合当你可以找出你的不同部分的工作;而不是当你不断地有约会与共享数据。

I'm not sure what you're trying to do. I assume your code is just a placeholder or experiment. Parallelization is only suitable when you can isolate your different pieces of work; not when you constantly have to rendezvous with shared data.

这篇关于使用嵌套的Parallel.For的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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