assign each thread a cpu core

前端 未结 2 1984
梦毁少年i
梦毁少年i 2021-02-06 06:17

i have a windows service written in .net 4 which doing jobs periodically using Threads. the server has more than 20 cpu core.

i create 10 threads in my windows service.

相关标签:
2条回答
  • 2021-02-06 06:25

    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 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 << (int)cpuID));
    

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

    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 Fiber API to schedule many managed threads against the same operating system thread, or to move a managed thread among different operating system threads.

    0 讨论(0)
  • 2021-02-06 06:35

    The OS already does precisely that for you. It doesn't guarantee that each thread will stay on the same core forever (and in nearly all cases, there's no need for that either), but it does try to keep as many cores busy as possible. Which means giving all available threads their own core as much as possible.

    0 讨论(0)
提交回复
热议问题