在Mono上为当前线程设置处理器关联(Linux)

时间:2013-03-28 16:35:52

标签: c# linux mono affinity

我正在编写一个自定义任务调度程序,我想知道是否有任何方法可以在Mono上设置当前线程的处理器关联(在Linux上运行)。

对于在Windows上运行的.NET运行时,我已经设法通过遵循Lenard Gunda的Running .NET threads on selected processor cores文章来实现这一点;但是,他的方法在Mono(和Linux)上失败了,因为:

  1. 需要对GetCurrentThreadId库中的Kernel32.dll进行P / Invoke调用。
  2. Process.Threads属性当前在Mono上返回一个空集合。
  3. 有没有人请为此解决?

2 个答案:

答案 0 :(得分:2)

请注意,您无法控制任务何时运行,这取决于内核。 无论如何,在Linux上你需要P / Invoke到sched_setaffinity()来将一个线程绑定到一个特定的cpu。

请参阅man sched_setaffinity了解界面。

答案 1 :(得分:2)

lupus的回答是在正确的轨道上,但我需要进一步研究才能实现这一点(例如P/Invoke signature for sched_setaffinityresolution of libc.so.6)。这是工作代码(不包括错误处理),以防任何人需要它:

[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);
}

修改:上述签名适用于我的实验,但请参阅David Heffernan's answer(根据我的其他问题)进行建议更正。

相关问题