在多CPU环境下将一个进程绑定到指定的一个CPU上[转]

Q:在多CPU环境下,如何将一个进程,绑定到指定的一个CPU上呢?即让它只在一个CPU上跑.

A:
//Thread 0 can only run on CPU 0.
SetThreadAffinityMask(hThread0, 0x00000001);

//Threads 1, 2, 3 run on CPUs 1, 2, 3.
SetThreadAffinityMask(hThread1, 0x0000000E);
SetThreadAffinityMask(hThread2, 0x0000000E);
SetThreadAffinityMask(hThread3, 0x0000000E);


BOOL SetProcessAffinityMask(HANDLE hProcess,
DWORD_PTR dwProcessAffinityMask);
第一个参数h P r o c e s s用于指明要影响的是哪个进程。
第二个参数d w P r o c e s s A ff i n i t y M a s k是个位屏蔽,用于指明线程可以在哪些C P U上运行。
例如,传递0 x 0 0 0 0 0 0 0 5表示该进程中的线程可以在CPU 0和CPU 2上运行,但是不能在CPU 1和C P U 3至3 1上运行。


在c#中也可以做到,下面是某软件被Reflector反编译过来的代码:
[MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType=MethodCodeType.Native), SuppressUnmanagedCodeSecurity, DllImport("", EntryPoint="", CallingConvention=CallingConvention.StdCall, SetLastError=true)]
public static extern unsafe int modopt(CallConvStdcall) SetProcessAffinityMask(void*, uint modopt(IsLong));
 SetProcessAffinityMask(GetCurrentProcess(), (uint modopt(IsLong)) ProcessorConfig);
posted on 2007-01-04 17:11  sss  阅读(1768)  评论(0)    收藏  举报