MaxDegreeOfParallelism做什么?

MaxDegreeOfParallelism做什么?,第1张

MaxDegreeOfParallelism做什么?

答案是,这是整个并行 *** 作的上限,与内核数无关。

因此,即使由于等待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:6Number of active threads:7Number of active threads:7Number of active threads:7Number of active threads:7Number of active threads:7Number of active threads:6Number of active threads:7Number of active threads:7Number of active threads:7Number of active threads:7Number of active threads:7Number of active threads:7Number of active threads:7Number of active threads:7Number of active threads:7Number of active threads:7Number of active threads:7Number of active threads:7

它开始时较低,随时间增加,最后尝试同时运行8。

如果我将其限制为任意值(例如2),我得到

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

哦,这是在四核计算机上。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4892796.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-12
下一篇 2022-11-12

发表评论

登录后才能评论

评论列表(0条)

保存