gpt4 book ai didi

c# - 哪些结构使用 .NET 4 中的 ThreadPool?

转载 作者:行者123 更新时间:2023-11-30 16:22:46 25 4
gpt4 key购买 nike

这个问题最好征求高级用户的意见。

我正在优化一些数字运算代码,并有一些处理器内核可用。为了有效地利用它们,我正在研究一些使用任务 (Task.StartNew) 的细粒度并发,用于运行时间极短的操作(100 到 500 毫秒)。这里根本不涉及 UI。

这里的一个关键要素是使用线程池,它可以在不产生线程创建开销的情况下为短期运行的任务带来性能优势。然而,在某些情况下,在循环中思考比在任务中思考更自然(例如 Parallel.For)。

我知道 Tasks 使用 ThreadPool 但不确定 Parallel.For。问题是:

  • 哪些结构使用 ThreadPool?
  • 能否将 Parallel.For 配置为使用 ThreadPool,还是它总是会产生线程创建开销?
  • 不是主要问题的一部分,但任何与最大化并行性相关的链接都会有所帮助。

请注意,此问题特定于 .NET 4。目前无法升级到 4.5。

更新:
根据 Daniel Kinsman 的评论,请考虑以下内容:

System.Threading.Tasks.Parallel.For(0, 100, i => { System.Console.WriteLine("Is ThreadPool @ low priority: " + System.Threading.Thread.CurrentThread.IsThreadPoolThread); });
System.Diagnostics.Process.GetCurrentProcess().PriorityBoostEnabled = true;
System.Diagnostics.Process.GetCurrentProcess().PriorityClass = System.Diagnostics.ProcessPriorityClass.RealTime;
System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest;
System.Threading.Tasks.Parallel.For(0, 100, i => { System.Console.WriteLine("Is ThreadPool @ high priority: " + System.Threading.Thread.CurrentThread.IsThreadPoolThread); });

如果您有一台多核机器,IsThreadPoolThread 将根据您运行的应用程序数量返回不确定的结果。

最佳答案

Parallel.For默认情况下,“始终”使用线程池来运行任务并且不会产生线程创建开销。

从 .Net 4.0 CLR 的当前版本开始,Parallel.For 在内部使用 ThreadPoolTask​​Scheduler 类(内部类)来运行其任务。当然,这是内部细节可能会发生变化,但 Parallel.For 很可能会继续使用 ThreadPool 来运行其任务。如果您不想冒这个“风险”,那么您可以随时编写自己的 TaskScheduler并使用 ParallelOptions Class 将其提供给 Parallel.For

If you have a multi-core machine, IsThreadPoolThread will return non-deterministic results depending on how many applications you have running.

解释:

ThreadPoolTask​​Scheduler 类是一个优化的任务调度程序,如果没有必要,它会尽量不在线程上运行任务,即如果任务可以立即执行,它会在当前线程上执行,这可能不是 ThreadPool 线程。您看到的“假”输出是针对这种情况的。但是如果它不能立即运行任务,它总是使用线程池将任务排队等待稍后执行。

请注意,在这两种情况下都没有创建线程的“开销”(不完全正确,因为 ThreadPool 本身可能会根据某些启发式决定在池中包含新线程)

您可以使用以下代码来确认这一点:

Thread.CurrentThread.Name = "MyThread";
System.Threading.Tasks.Parallel.For(0, 100, i => Console.WriteLine(i + ". Is ThreadPool: " + Thread.CurrentThread.IsThreadPoolThread + " Name: " + Thread.CurrentThread.Name));

您将能够注意到,对于所有“错误”的情况,线程名称都是“MyThread”。

关于最大化并行性,受 CPU 限制的工作只能在可用 CPU 内核数量的范围内并行化。 TPL 考虑到了这一点,非常适合并优化了 CPU 绑定(bind)任务的并行计算。通过使用 TPL,您走在正确的道路上,应该继续沿着这条道路前进:)

关于c# - 哪些结构使用 .NET 4 中的 ThreadPool?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12189305/

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