我有2个线程。我想告诉其中一个在第一个cpu上运行,第二个在第二个cpu上运行,例如在一台具有两个cpu的计算机上运行。我怎样才能做到这一点?

这是我的代码

UCI UCIMain = new UCI();
Thread UCIThread = new Thread(new ThreadStart(UCIMain.main));
UCIThread.Priority = ThreadPriority.BelowNormal;
UCIThread.Start();

并且可以肯定的是,UCI类具有一个名为main的成员函数。我想例如在第一个处理器中设置此线程

最佳答案

我不建议这样做,但是如果您确实需要:可以通过利用 native Win32系统调用(特别是SetThreadAffinityMask)来实现。您将需要执行一些DllImport:

[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentThread();
[DllImport("kernel32.dll")]
static extern IntPtr SetThreadAffinityMask(IntPtr hThread, IntPtr dwThreadAffinityMask);

然后在每个生成的线程中使用它们(当然,对于 mask 使用不同的参数):
// set affinity of current thread to the given cpuID
SetThreadAffinityMask(GetCurrentThread(), new IntPtr(1)); // CPU 0

09-30 18:11
查看更多