how to set CPU affinity of a program?

∥☆過路亽.° 提交于 2021-02-06 10:45:07

问题


I have a program written in C#, I am using VSTS 2008 + .Net 3.5 + Windows Vista Enterprise x86 to develop a Windows Forms application.

My current computer is dual-core CPU, I want to set CPU affinity of my program to run on a specific CPU and free another CPU to do some other job. Any ideas how to do this? Either through coding or configuration is ok.

A little more background is, my program is CPU intensive, so I do not want to let it occupy all two CPU resources on my computer and I want to free one CPU so that I can browse network at the same time quickly. :-)

thanks in advance, George


回答1:


  1. Go to Task Manager -> Processes tab.
  2. Look for your program. Right click on it.
  3. Select Set Affinity and uncheck one of the checkboxes.

This should free up one processor for you.

For doing it from the code you can add this statement:

System.Diagnostics.Process.GetCurrentProcess().ProcessorAffinity = (System.IntPtr) 1;

Cheers!




回答2:


The Windows API functions to do this are SetProcessAffinityMask() and SetThreadAffinityMask(). I don't know .NET so I can't say whether there are wrappers around those functions, but this seems to suggest otherwise.

BTW: I agree that these are necessary only in very specific circumstances, it's normally best to let the OS scheduler deal with it. It's one of those questions where you probably shouldn't do it if you have to ask how.




回答3:


Actually, your application will not use more than one CPU unless you specifically do something to utilize more CPUs. If you use the thread pool and/or start additional threads you may use additional available cores, but otherwise your application will just have one thread per default and thus only use one CPU.



来源:https://stackoverflow.com/questions/1052276/how-to-set-cpu-affinity-of-a-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!