Reputation: 1405
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
Upvotes: 3
Views: 1033
Reputation: 62479
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 DllImport
s:
[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
Upvotes: 5
Reputation: 35935
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.
Upvotes: 2
Reputation: 4304
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.
Upvotes: 2