Reputation: 191
How are threads distributed between CORES in a multithreaded system. Lets say i have a program that creates 6 threads. My system has 3 CORES. In this case will the threads be distributed between the 3 COREs or will all the threads execute on the same CORE?
Upvotes: 2
Views: 1610
Reputation: 10950
I found a decent explanation on this blog post. You can use some pinvoke calls to set the thread affinity:
[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentThread();
[DllImport("kernel32.dll")]
static extern IntPtr SetThreadAffinityMask(IntPtr hThread, IntPtr dwThreadAffinityMask);
You can then use it like this:
SetThreadAffinityMask(GetCurrentThread(), new IntPtr(1 << processorNumber));
But you must be aware that the managed thread can switch from one unmanaged thread to another, and the upper method works with unmanaged threads, so there is no guarantee it will work 100%. From MSDN documentation on the Thread class:
An operating-system ThreadId has no fixed relationship to a managed thread, because an unmanaged host can control the relationship between managed and unmanaged threads. Specifically, a sophisticated host can use the CLR Hosting API to schedule many managed threads against the same operating system thread, or to move a managed thread between different operating system threads.
However you can circumvent this by calling Thread.BeginThreadAffinity()
before executing the pinvoke calls.
Upvotes: 2