gpt4 book ai didi

c# - 线程池的处理器亲和性和线程创建

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

此问题基于 Jeffrey Richter 在 Microsoft Virtual Academy 中的线程类(class)。

根据我的理解,如果我将处理器关联设置为仅使用 1 个处理器,如下所示

Int32 affinity = 1;
Process.GetCurrentProcess().ProcessorAffinity = (IntPtr)affinity;

for (int i = 0; i < 200 ; i++)
{
ThreadPool.QueueUserWorkItem(ActiveWorker);
}

ActiveWorker() 是一个 CPU 绑定(bind)函数,它只执行一些 CPU 绑定(bind)计算,大约需要 100 毫秒。当我计算创建的线程数时,它大约为 5。但根据我的理解,由于 CPU 关联设置为仅使用 1 个处理器,线程池不应创建超过 1 个线程。任何想法?在 Jeffrey 的演示中,它显示它只为整个 200 个工作项创建了 1 个线程,但是当我在我的 PC 中运行相同的示例时,我可以看到创建了 5 个线程。 (我的电脑有 2 个内核)

最佳答案

默认是每个处理器一个线程池,但该线程池中的线程数由 .Net 计算。这是 MSDN 的摘录 https://msdn.microsoft.com/en-us/library/system.threading.threadpool(v=vs.110).aspx :

There is one thread pool per process. Beginning with the .NET Framework 4, the default size of the thread pool for a process depends on several factors, such as the size of the virtual address space. A process can call the GetMaxThreads method to determine the number of threads. The number of threads in the thread pool can be changed by using the SetMaxThreads method. Each thread uses the default stack size and runs at the default priority.

关于c# - 线程池的处理器亲和性和线程创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41132596/

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