增加并行运行线程的数量

增加并行运行线程的数量

本文介绍了增加并行运行线程的数量.For的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚使用此链接 如下:

Console.WriteLine("Number of Threads: {0}", System.Diagnostics.Process.GetCurrentProcess().Threads.Count);
int count = 0;
Parallel.For(0, 50000, options,(i, state) =>
{
            count++;
});

Console.WriteLine("Number of Threads: {0}", System.Diagnostics.Process.GetCurrentProcess().Threads.Count);
Console.ReadKey();

它在 Parellel.For 之前为我提供了 15 个线程,在它仅提供了 17 个线程之后.所以只有 2 个线程被 Parellel.For 占用.

It gives me 15 thread before Parellel.For and after it gives me 17 thread only. So only 2 thread is occupy with Parellel.For.

然后我使用此链接创建了另一个示例代码,如下所示:

Then I have created a another sample code using This Link like below:

var options = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 10 };
Console.WriteLine("MaxDegreeOfParallelism : {0}", Environment.ProcessorCount * 10);
Console.WriteLine("Number of Threads: {0}", System.Diagnostics.Process.GetCurrentProcess().Threads.Count);
int count = 0;
Parallel.For(0, 50000, options,(i, state) =>
{
            count++;
});

Console.WriteLine("Number of Threads: {0}", System.Diagnostics.Process.GetCurrentProcess().Threads.Count);
Console.ReadKey();

在上面的代码中,我将 MaxDegreeOfParallelism 设置为 40,但仍然为 Parallel.For 使用相同的线程.

In above code, I have set MaxDegreeOfParallelism where it sets 40 but is still taking same threads for Parallel.For.

那么如何增加Parallel.For的运行线程?

So how can I increase running thread for Parallel.For?

推荐答案

并行循环使用硬件 CPU 内核.如果您的 CPU 有 2 个内核,则这是您的机器可以达到的最大并行度.

Parallel loops use hardware CPU cores. If your CPU has 2 cores, this is the maximum degree of paralellism that you can get in your machine.

摘自 MSDN:

默认情况下,并行度(即在硬件中同时运行多少次迭代)取决于可用内核数.在典型场景中,您的核心数越多有,你的循环执行得越快,直到你到达阿姆达尔定律预测的收益递减.多快取决于您的循环所做的工作类型.

进一步阅读:

这篇关于增加并行运行线程的数量.For的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 18:23