Skip to content

Affinity Priority Fiber

A console snippet that pins a process and thread to a specific CPU using affinity masks and ideal-processor calls.

Published Jun 15, 1998

A compact demonstration of the Win32 processor-affinity API. It sets an ideal processor for the current thread, locks both the thread and the whole process onto CPU 0 with SetThreadAffinityMask and SetProcessAffinityMask, reads the resulting masks back with GetProcessAffinityMask, and enables priority boosting on both handles. Use it when you want to keep latency-sensitive work off other cores, or as a reference for how the affinity bitmasks map to physical processors.

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define WIN32_LEAN_AND_MEAN
#define _WIN32_WINNT 0x0500

#include <Windows.H>
#include <WinBase.H>
#include <WindowsX.H>
#include <StdIO.H>
#include <StdLib.H>

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

int main(void)
{
    int Processor = 0;

    DWORD dwProcessAffinity = 0;
    DWORD dwSystemAffinity  = 0;

    HANDLE ProcessHandle = GetCurrentProcess();
    HANDLE ThreadHandle  = GetCurrentThread();

    // A value of MAXIMUM_PROCESSORS tells the system that the thread has no preferred processor.
    if(SetThreadIdealProcessor(ThreadHandle, 1) == -1)
        printf("SetThreadIdealProcessor\n");

    if(!SetThreadAffinityMask(ThreadHandle, 1))
        printf("SetThreadAffinityMask\n");

    if(!SetProcessAffinityMask(ProcessHandle, 1))
        printf("SetProcessAffinityMask\n");

    if(!GetProcessAffinityMask(ProcessHandle, &dwProcessAffinity, &dwSystemAffinity))
        printf("GetProcessAffinityMask\n");

    dwProcessAffinity = 1 << Processor;
    if(dwProcessAffinity & dwSystemAffinity)
    {
        if(!SetProcessAffinityMask(ProcessHandle, dwProcessAffinity))
            printf("Warning: Could not set processor affinity mask.\n");
    }
    else printf("Warning: Illegal processor specified, using default.\n");

    if(!SetProcessPriorityBoost(ProcessHandle, TRUE))
        printf("SetProcessPriorityBoost\n");

    if(!SetThreadPriorityBoost(ThreadHandle, TRUE))
        printf("SetThreadPriorityBoost\n");

    printf("dwProcessAffinity: %d\n", dwProcessAffinity);
    printf("dwSystemAffinity: %d\n", dwSystemAffinity);

	return 0;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
An unhandled error has occurred. Reload 🗙