使用线程池的处理器数限制 [英] Limit number of processors used in ThreadPool

查看:147
本文介绍了使用线程池的处理器数限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么办法来限制线程池对象将使用的处理器的数量?根据文档,你不能设置工作线程的数目或I / O完成线程来了一批比在计算机处理器的数量少了一些。

Is there any way to limit the number of processors that the ThreadPool object will use? According to the docs, "You cannot set the number of worker threads or the number of I/O completion threads to a number smaller than the number of processors in the computer."

所以,我怎么能限制我的程序不会消耗所有的处理器?

So how can I limit my program to not consume all the processors?

推荐答案

一些实验后,我想我刚才的事情。我注意到,在线程池考虑处理器的系统数量为可用于当前进程的处理器的数量。这可以工作,你的优势。

After some experiments, I think I have just the thing. I've noticed that the ThreadPool considers the number of processors in the system as the number of processors available to the current process. This can work to your advantage.

我在我的CPU 4核。试图调用 SetMaxThreads 以2:

I have 4 cores in my CPU. Trying to call SetMaxThreads with 2:

ThreadPool.SetMaxThreads(2, 2);

失败,因为我有4个核心,因此数量保持在初始值(1023和1000为我的系统)。

fails since I have 4 cores and so the numbers remain at their initial values (1023 and 1000 for my system).

不过,就像我说的开始,在线程池只考虑可用处理器的过程中,我可以管理使用的次数 Process.ProcessorAffinity 。这样做:

However, like I said initially, the ThreadPool only considers the number of processors available to the process, which I can manage using Process.ProcessorAffinity. Doing this:

Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(3);  

限制了可用的处理器向第一两个芯(自3二进制= 11)。呼叫 SetMaxThreads 又说:

ThreadPool.SetMaxThreads(2, 2);

应该像一个魅力(至少它为我做的)。只要确保使用正确的亲和力在程序启动时设置!

should work like a charm (at least it did for me). Just make sure to use the affinity setting right at program start-up!

当然,我不会鼓励这种破解,因为反正你的程序将被固定在一个有限数量的内核其执行的整个过程。

Of course, I would not encourage this hack, since anyway your process will be stuck with a limited number of cores for the entire duration of its execution.

这篇关于使用线程池的处理器数限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆