gpt4 book ai didi

c# - MaxDegreeOfParallelism 有什么作用?

转载 作者:IT王子 更新时间:2023-10-29 03:51:11 24 4
gpt4 key购买 nike

我正在使用 Parallel.ForEach 并且我正在做一些数据库更新,现在没有设置 MaxDegreeOfParallelism ,双核处理器机器导致 sql 客户端超时,而四核处理器机器不知何故不会超时。

现在我无法控制我的代码运行时可用的处理器内核类型,但是我可以使用 MaxDegreeOfParallelism 更改一些设置,这些设置可能会同时运行较少的操作并且不会导致超时吗?

我可以增加超时,但这不是一个好的解决方案,如果在较低的 CPU 上我可以同时处理较少的操作,那将减少 cpu 的负载。

好的,我也阅读了所有其他帖子和 MSDN,但是将 MaxDegreeOfParallelism 设置为较低的值会使我的四核机器受到影响吗?

例如,如果 CPU 有两个内核,则使用 20 个内核,如果 CPU 有四个内核,则使用 40 个内核?

最佳答案

答案是它是整个并行运算的上限,与核数无关。

因此,即使您因为等待 IO 或锁而没有使用 CPU,也不会并行运行额外的任务,只有您指定的最大值。

为了弄清楚这一点,我写了这段测试代码。那里有一个人工锁来刺激 TPL 使用更多线程。当您的代码正在等待 IO 或数据库时,也会发生同样的情况。

class Program
{
static void Main(string[] args)
{
var locker = new Object();
int count = 0;
Parallel.For
(0
, 1000
, new ParallelOptions { MaxDegreeOfParallelism = 2 }
, (i) =>
{
Interlocked.Increment(ref count);
lock (locker)
{
Console.WriteLine("Number of active threads:" + count);
Thread.Sleep(10);
}
Interlocked.Decrement(ref count);
}
);
}
}

如果我不指定 MaxDegreeOfParallelism,控制台日志记录会显示最多大约 8 个任务同时运行。像这样:

Number of active threads:6
Number of active threads:7
Number of active threads:7
Number of active threads:7
Number of active threads:7
Number of active threads:7
Number of active threads:6
Number of active threads:7
Number of active threads:7
Number of active threads:7
Number of active threads:7
Number of active threads:7
Number of active threads:7
Number of active threads:7
Number of active threads:7
Number of active threads:7
Number of active threads:7
Number of active threads:7
Number of active threads:7

它开始较低,随着时间的推移增加,最后它试图同时运行 8 个。

如果我将它限制为某个任意值(比如 2),我会得到

Number of active threads:2
Number of active threads:1
Number of active threads:2
Number of active threads:2
Number of active threads:2
Number of active threads:2
Number of active threads:2
Number of active threads:2
Number of active threads:2
Number of active threads:2
Number of active threads:2
Number of active threads:2
Number of active threads:2
Number of active threads:2
Number of active threads:2
Number of active threads:2
Number of active threads:2

哦,这是在四核机器上。

关于c# - MaxDegreeOfParallelism 有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9538452/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com