- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我正在使用 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/
今天有小伙伴给我留言问到,try{...}catch(){...}是什么意思?它用来干什么? 简单的说 他们是用来捕获异常的 下面我们通过一个例子来详细讲解下
我正在努力提高网站的可访问性,但我不知道如何在页脚中标记社交媒体链接列表。这些链接指向我在 facecook、twitter 等上的帐户。我不想用 role="navigation" 标记这些链接,因
说现在是 6 点,我有一个 Timer 并在 10 点安排了一个 TimerTask。之后,System DateTime 被其他服务(例如 ntp)调整为 9 点钟。我仍然希望我的 TimerTas
就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用资料或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
我就废话不多说了,大家还是直接看代码吧~ ? 1
Maven系列1 1.什么是Maven? Maven是一个项目管理工具,它包含了一个对象模型。一组标准集合,一个依赖管理系统。和用来运行定义在生命周期阶段中插件目标和逻辑。 核心功能 Mav
我是一名优秀的程序员,十分优秀!