如何使用SetProcessAffinityMask选择多个逻辑处理器?
在Windows任务管理器中,您可以将此作为示例:
我更新了我的CreateProcess程序来执行此操作:
type TProcessPriority = (ptLow = $00000040,ptBelowNormal = $00004000,ptNormal = $00000020,ptAboveNormal = $00008000,ptHigh = $00000080,ptRealtime = $00000100); procedure RunProcess(FileName: string; Priority: TProcessPriority); var StartInfo: TStartupInfo; ProcInfo: TProcessInformation; CmdLine: string; Done: Boolean; begin FillChar(StartInfo,SizeOf(TStartupInfo),#0); FillChar(ProcInfo,SizeOf(TProcessInformation),#0); StartInfo.cb := SizeOf(TStartupInfo); CmdLine := FileName; UniqueString(CmdLine); try Done := CreateProcess(nil,PChar(CmdLine),nil,False,CREATE_NEW_PROCESS_GROUP + Integer(Priority),StartInfo,ProcInfo); if Done then begin // Todo: Get actual cpu core count before attempting to set affinity! // 0 = <All Processors> // 1 = cpu 0 // 2 = cpu 1 // 3 = cpu 2 // 4 = cpu 3 // 5 = cpu 5 // 6 = cpu 6 // 7 = cpu 6 // 8 = cpu 7 // this sets to cpu 0 - but how to allow multiple parameters to // set more than one logical processor? SetProcessAffinityMask(ProcInfo.hProcess,1); end else MessageDlg('Could not run ' + FileName,mtError,[mbOk],0) finally CloseHandle(ProcInfo.hProcess); CloseHandle(ProcInfo.hThread); end; end;
请注意我在那里的评论.最好更新我的过程以包含一个新的Affinity参数,我可以将其传递给SetProcessAffinityMask.
由于显而易见的原因,调用其中任何一个都不会选择相应的处理器,它们会给出我想要做的事情的想法:
SetProcessAffinityMask(ProcInfo.hProcess,1 + 2); SetProcessAffinityMask(ProcInfo.hProcess,1 and 2);
例如,为进程选择任何cpu,如任务管理器中所示.
我应该怎么做,使用数组,集合或其他?我无法使用多个值.
谢谢.
@H_403_20@解决方法
它是
documentation中描述的位掩码.
A process affinity mask is a bit vector in which each bit represents a logical processor on which the threads of the process are allowed to run.
>处理器0是01美元.
>处理器1是02美元.
>处理器2是04美元.
>处理器3是08美元.
>处理器4是10美元.
等等.您可以使用逻辑或组合它们.因此处理器0和1将是$01或$02,等于$03.
我将使用shift运算符shl为特定处理器创建值.像这样:
function SingleProcessorMask(const ProcessorIndex: Integer): DWORD_PTR; begin Result := 1 shl (ProcessorIndex-1); end;
您可以轻松地扩展它,以使用逻辑或循环为处理器列表生成掩码.
function CombinedProcessorMask(const Processors: array of Integer): DWORD_PTR; var i: Integer; begin Result := 0; for i := low(Processors) to high(Processors) do Result := Result or SingleProcessorMask(Processors[i]); end;
您可以测试处理器位于这样的位掩码中:
function ProcessorInMask(const ProcessorMask: DWORD_PTR; const ProcessorIndex: Integer): Boolean; begin Result := (SingleProcessorMask(ProcessorIndex) and ProcessorMask)<>0; end;
注意:我正在使用DWORD_PTR,因为对于64位目标,位掩码是64位宽.在XE上,这种细微差别对你来说并不重要,但是为了使未来的代码移植更容易,这是值得的.
@H_403_20@ @H_403_20@