` Printed Icetips Article

Icetips Article



Par2: Set Processor Affinity
2007-03-02 -- Bjorn Holm
 
I have added this code to my programs:

 MAP
   Module('winapi')
     SetProcessAffinityMask(UNSIGNED,LONG),LONG,PASCAL,RAW
     GetCurrentProcess(),LONG,PASCAL,RAW
     GetSystemInfo(LONG),PASCAL,RAW
   End
 End

SYSTEM_INFO     GROUP,TYPE
dwOemId                     LONG
dwPageSize                  LONG
pMinimumApplicationAddress ULONG
lpMaximumApplicationAddress ULONG
dwActiveProcessorMask       LONG
dwNumberOfProcessors        LONG
dwProcessorType             LONG
dwAllocationGranularity     LONG
dwReserved                  LONG
wProcessorLevel            USHORT
wProcessorRevision        USHORT
wProcessorArchitecture      USHORT
              END


SystemInfo      LIKE(SYSTEM_INFO),AUTO
Loc:ProcCount   Long
Loc:ProcNo      Long

  GetSystemInfo(ADDRESS(SystemInfo))
  Loc:ProcCount = SystemInfo.dwNumberOfProcessors
  If Loc:ProcCount > 1 Then
    Loc:ProcNo = Random(1, Loc:ProcCount)
    A# = SetProcessAffinityMask(GetCurrentProcess(),Loc:ProcNo)
  End


takes care of multiprocessor systems for me. : )

Carl Barnes notes:

Your code is wrong if there are more then 2 processores. It's a "bit-mask" and 
not processor number. So if there are 4 processors and you pick processor 3 you 
are using a mask of 3 which is 011b and you are assigning your EXE to 
processors 1 and 2. Or if you pick 4 which is 0100b you are asigning processor 
3. You'll never assign to processor 4 since that mask value is 8.

Your code should be (untested)
BSHIFT long
    Loc:ProcNo = Random(1, Loc:ProcCount)
    CPUBM = BSHIFT(1,Loc:ProcNo-1)  !or 2^(Loc:ProcNo-1)
    A# = SetProcessAffinityMask(GetCurrentProcess(),CPUBM)


If your going to add runtime affinity code to the EXE that way IMO the right 
way is to use GetProcessorAffinity() and not GetSystemInfo(). Then select a 
processor from the affinity mask your Process has been assigned, not the system 
mask.  

Assigning processor affinity at runtime from dwNumberOfProcessors will ignore 
an affinity assigned in the EXE header (by the compiler or ImageCfg.exe) or by 
the Windows loader that already is a subset of the maximum processors in the 
system.



Printed November 21, 2024, 11:23 am
This article has been viewed/printed 35222 times.