问题
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:
- It requires a P/Invoke call to
GetCurrentThreadId
in theKernel32.dll
library. - 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