使用嵌套的Parallel.For嵌套、Parallel、For

2023-09-07 15:05:55 作者:都撩人

考虑这个例子:

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.