Microsoft Docs

SetProcessAffinityMask

Syntax

#include <windows.h>

BOOL SetProcessAffinityMask(
    HANDLE hProcess,
    DWORD_PTR dwProcessAffinityMask
);

Description

Sets a processor affinity mask for the specified process. The affinity mask determines the processors that the threads of the process are allowed to run on.

Parameters

ParameterTypeDescription
hProcess HANDLE Handle to the process whose affinity mask is to be set. The handle must have the PROCESS_SET_INFORMATION access right.
dwProcessAffinityMask DWORD_PTR Bit mask that specifies the processors that the process's threads are allowed to run on. Each bit set to 1 represents a logical processor that is allowed.

Return value

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

  • The affinity mask must be a subset of the system affinity mask retrieved via GetProcessAffinityMask.
  • Setting an affinity mask that excludes all available processors results in failure.
  • Affinity changes affect all existing threads in the process.
  • When a process has multiple threads, each thread can also have its own affinity mask using SetThreadAffinityMask.

Example

#include <windows.h>
#include <stdio.h>

int main(void)
{
    HANDLE hProcess = GetCurrentProcess();
    DWORD_PTR mask = 0x00000003; // Use CPU 0 and 1

    if (!SetProcessAffinityMask(hProcess, mask)) {
        printf("SetProcessAffinityMask failed. Error: %lu\n", GetLastError());
        return 1;
    }

    printf("Affinity mask set to 0x%llx\n", (unsigned long long)mask);
    return 0;
}

See Also