在并行构造“Parallel.ForEach”中使用分区器对象时,为什么我们必须保持分区块的大小,为什么我们必须保持锁的数量小? [英] When using the partitioner object in a parallel construct "Parallel.ForEach", why do we have to keep the size of the partitioned chunks large and why do we have to keep the number of locks small?

查看:83
本文介绍了在并行构造“Parallel.ForEach”中使用分区器对象时,为什么我们必须保持分区块的大小,为什么我们必须保持锁的数量小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在并行构造Parallel.ForEach中使用分区器对象时,为什么我们必须保持分区块的大小很大,为什么我们必须保持锁的数量小?



When using the partitioner object in a parallel construct "Parallel.ForEach", why do we have to keep the size of the partitioned chunks large and why do we have to keep the number of locks small?

static double ParallelPartitionerPi()
        {
            double sum = 0.0;
            double step = 1.0 / (double)num_steps;
            object monitor = new object();
            Parallel.ForEach(Partitioner.Create(0, num_steps), () => 0.0,
            (range, state, local) =>
            {
                for (int i = range.Item1; i < range.Item2; i++)
                {
                    double x = (i + 0.5) * step;
                    local += 4.0 / (1.0 + x * x);
                }
                return local;
            }, local => { lock (monitor) sum += local; });
            return step * sum;
        }

推荐答案

太多锁的性能影响击败了多线程对象

http://tipsandtricks.runicsoft.com/CSharp/ParallelClass.html [ ^ ]以获得更全面的解释。
The performance impact of too many locks defeats the object of multi-threading
See http://tipsandtricks.runicsoft.com/CSharp/ParallelClass.html[^] for a fuller explanation.


这篇关于在并行构造“Parallel.ForEach”中使用分区器对象时,为什么我们必须保持分区块的大小,为什么我们必须保持锁的数量小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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