为什么PLINQ只使用两个线程? [英] Why does PLINQ use only two threads?

查看:73
本文介绍了为什么PLINQ只使用两个线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个IO绑定的任务。我使用WithDegreeOfParallelism = 10,WithExecution = ForceParallelism模式,但仍是查询只使用两个线程。为什么呢?

我理解PLINQ通常会选择并行度等于我的核心数量,但为什么它忽略我的更高的并行具体要求?

 静态无效的主要(字串[] args)
{
    TestParallel(0.UpTo(8));
}

私有静态无效TestParallel(IEnumerable的< INT>输入)
{
    VAR定时器=新的秒表();
    timer.Start();
    变种大小= input.Count();

    如果(input.AsParallel()。
        WithDegreeOfParallelism(10)。
        WithExecutionMode(ParallelExecutionMode.ForceParallelism)。
        凡(ISODD).Count之间的()!=尺寸/ 2)
        抛出新的异常(无法计数的可能性);

    timer.Stop();
    Console.WriteLine(测试+规模+号码+ timer.Elapsed.TotalSeconds +秒);
}

私有静态布尔ISODD(INT N)
{
    Thread.sleep代码(1000);
    回报N%2 == 1;
}
 

解决方案

PLINQ试图找到最佳线程数来执行,你想要它做的尽可能快的,如果你只对你的CPU的2个核心是什么,那数字是最有可能的2。如果你有一个四核,你会更有可能看到4个线程出现,但双核的机器上创建4个线程不会真的提高性能,因为只有2个线程可以在同一时间被激活

另外,对于基于IO的操作,它很可能是任何额外的线程将简单地阻止执行的第一个IO操作

Say I have an IO-bound task. I'm using WithDegreeOfParallelism = 10 and WithExecution = ForceParallelism mode, but still the query only uses two threads. Why?

I understand PLINQ will usually choose a degree of parallelism equal to my core count, but why does it ignore my specific request for higher parallelism?

static void Main(string[] args)
{
    TestParallel(0.UpTo(8));
}

private static void TestParallel(IEnumerable<int> input)
{
    var timer = new Stopwatch();
    timer.Start();
    var size = input.Count();

    if (input.AsParallel().
        WithDegreeOfParallelism(10).
        WithExecutionMode(ParallelExecutionMode.ForceParallelism).
        Where(IsOdd).Count() != size / 2)
        throw new Exception("Failed to count the odds");

    timer.Stop();
    Console.WriteLine("Tested " + size + " numbers in " + timer.Elapsed.TotalSeconds + " seconds");
}

private static bool IsOdd(int n)
{
    Thread.Sleep(1000);
    return n%2 == 1;
}

解决方案

PLINQ tries to find the optimal number of threads to perform what you want it to do as quickly as possible, if you only have 2 cores on your cpu, that number is most likely 2. If you had a quad core, you would be more likely to see 4 threads appear, but creating 4 threads on a dual core machine wouldn't really improve performance because only 2 threads could be active at the same time.

Also, with IO-based operations, it is likely that any extra threads would simply block on the first IO operation performed.

这篇关于为什么PLINQ只使用两个线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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