I have the following code running on Windows 10.
function SingleProcessorMask(const ProcessorIndex: Integer): DWORD_PTR;
begin
Result:= 1; Result:= Result shl (ProcessorIndex); //Make sure it works on processor 33 and up.
end;
procedure TForm2.BtnCreateLookup5x5to3x3UsingSpeculativeExplorationClick(Sender: TObject);
var
ThreadCount: integer;
Threads: TArray<TThread>;
CurrentProcessor: integer;
i,a: integer;
Done: boolean;
begin
ThreadCount:= System.CpuCount;
SetLength(Threads, ThreadCount);
CurrentProcessor:= GetCurrentProcessorNumber;
a:= 0;
for i:= 1 to ThreadCount-1 do begin
Threads[i]:= TThread.CreateAnonymousThread(procedure begin
CreateLookupUsingGridSolver(i, ThreadCount);
end);
Threads[i].FreeOnTerminate:= false;
if (CurrentProcessor = a) then Inc(a); //Skip the current processor.
Inc(a);
//if (SetThreadAffinityMask(Threads[i].handle, SingleProcessorMask(a))) = 0 then RaiseLastOSError; << fails here as well.
Threads[i].Start;
if (SetThreadAffinityMask(Threads[i].handle, SingleProcessorMask(a))) = 0 then RaiseLastOSError;
end; {for i}
CreateLookupUsingGridSolver(0, ThreadCount, NewLookup);
{Wait for all threads to finish}
.....
//Rest of the proc omitted to save space.
end;
I keep getting error 87, Incorrect parameter.
I'm fairly sure the SingleProcessorMask
is correct.
Is there perhaps an issue with the TThread.Handle
?
It does not matter if I call this code running as Administrator, running on a laptop or running on a i9. The result is always the same.
And yes, I really do need to force the threads, otherwise they all bunch up on the same core.
UPDATE
Once I fix the process affinity to match the system affinity, there is no need to muck around with assigning each thread to a specific core. In that case the automatic handling works. This is done using:
GetProcessAffinityMask(GetCurrentProcess(), ProcessAffinityMask, SystemAffinityMask);
SetProcessAffinityMask(GetCurrentProcess(), SystemAffinityMask);
//Error checking omitted for brevity