Assign cpu core to each thread

I have a Windows service written in .net 4 that periodically runs Threads jobs. The server has more than 20 cpu cores.

I am creating 10 threads in my windows service. Is it possible to assign a cpu core to each thread?

+6
source share
2 answers

The OS is already doing just that for you. This does not guarantee that each thread will remain on the same core forever (and in almost all cases, there is no need for this), but it tries to save as many kernels as possible. This means that make the most of all available threads in your core.

+7
source

Perhaps by clicking on Win32's own system calls, in particular 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 them inside each spawned stream (of course, with a different parameter for the mask):

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

Warning. Direct correlation between .NET threads and OS threads is not guaranteed, at least in accordance with this: http://msdn.microsoft.com/en-us/library/74169f59.aspx

The ThreadId operating system does not have a fixed relationship with a managed thread, because an unmanaged host can control the relationship between managed and unmanaged threads. In particular, a complex host can use the Fiber API to schedule many managed threads against the same operating system thread, or move a managed thread between different operating system threads.

+6
source

Source: https://habr.com/ru/post/911268/


All Articles