Specify a special cpu for a thread in C#

自古美人都是妖i 提交于 2021-02-19 03:36:47

问题


I have 2 threads. I want to tell one of them to run on first cpu and the second one on the second cpu for example in a machine with two cpu. how can I do that?

this is my code

UCI UCIMain = new UCI();
Thread UCIThread = new Thread(new ThreadStart(UCIMain.main));
UCIThread.Priority = ThreadPriority.BelowNormal;
UCIThread.Start();

and for sure the class UCI has a member function named main. I want to set this thread in 1st processor for example


回答1:


I wouldn't recommend this, but if you really need to: it is possible by tapping into the native Win32 system calls, specifically SetThreadAffinityMask. You will need to do some DllImports:

[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentThread();
[DllImport("kernel32.dll")]
static extern IntPtr SetThreadAffinityMask(IntPtr hThread, IntPtr dwThreadAffinityMask);

And then use the them inside each spawned thread (with a different parameter for the mask, of course):

// set affinity of current thread to the given cpuID
SetThreadAffinityMask(GetCurrentThread(), new IntPtr(1)); // CPU 0



回答2:


On .NET, you have ProcessThread.ProcessorAffinity and ProcessThread.IdealProcessor

But since you are talking about a Thread and not Process, I believe there is no directly available way of doing this in .NET.

There is Thread.SetProcessorAffinity() but it's only available for XNA on Xbox.




回答3:


Don't do this. OS task scheduler is much more clever than manual tweaks. You can technically use thread affinity, but it's not usually a good idea. Instead use thread pool or TPL library.

If one core is super busy and another one is not. Then one thread will be starving for processing power, whereas another core will not be loaded at all.



来源:https://stackoverflow.com/questions/12427265/specify-a-special-cpu-for-a-thread-in-c-sharp

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