假设我有一个IO绑定任务.我使用WithDegreeOfParallelism = 10和WithExecution = ForceParallelism模式,但查询仍然只使用两个线程.为什么?
我知道PLINQ通常会选择一个与我的核心数相等的并行度,但为什么它忽略了我对更高并行性的特定要求呢?
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;
}
Run Code Online (Sandbox Code Playgroud)
PLINQ试图找到最佳线程数来执行你希望它尽快做,如果你只对你的CPU有2个核心的东西,这个数字是最有可能2.如果你有一个四核,你会更可能会看到4个线程出现,但在双核机器上创建4个线程并不能真正提高性能,因为只有2个线程可以同时处于活动状态.
此外,对于基于IO的操作,任何额外的线程可能只会阻塞执行的第一个IO操作.
| 归档时间: |
|
| 查看次数: |
4283 次 |
| 最近记录: |