Set processor affinity for current thread on Mono (Linux)

泪湿孤枕 提交于 2019-12-10 20:12:59

问题


I'm writing a custom task scheduler, and I would like to know if there is any way of setting the processor affinity for the current thread on Mono (running on Linux).

For the .NET runtime running on Windows, I've managed to get this to work by following Lenard Gunda's Running .NET threads on selected processor cores article; however, his approach fails on Mono (and Linux) because:

  1. It requires a P/Invoke call to GetCurrentThreadId in the Kernel32.dll library.
  2. The Process.Threads property currently returns an empty collection on Mono.

Does anyone please have a workaround for this?


回答1:


lupus's answer was on the right track, but it took me some further research to get this implemented (such as the P/Invoke signature for sched_setaffinity and the resolution of libc.so.6). Here's the working code (excluding error-handling) in case anyone needs it:

[DllImport("libc.so.6", SetLastError=true)]
private static extern int sched_setaffinity(int pid, IntPtr cpusetsize, 
                                            ref ulong cpuset);

private static void SetAffinity(int processorID)
{
    ulong processorMask = 1UL << processorID;
    sched_setaffinity(0, new IntPtr(sizeof(ulong)), ref processorMask);
}

Edit: The above signature worked fine for my experiments, but refer to David Heffernan's answer (under my other question) for a suggested correction.




回答2:


Note that you don't really have control of when a task gets run, that is up to the kernel. Anyway, on Linux you will need to P/Invoke to sched_setaffinity() to bind a thread to a specific cpu.

See man sched_setaffinity for the interface.



来源:https://stackoverflow.com/questions/15687342/set-processor-affinity-for-current-thread-on-mono-linux

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