Example usage of SetProcessAffinityMask in C++?

As already mentioned, it's a bitmask. You may want to use the result of GetProcessAffinityMask, incase your process or system doesn't have access to all the cores already. Here's what I came up with.

#include <Windows.h>
#include <iostream>
using namespace std; 
 
int main () { 
 
    HANDLE process = GetCurrentProcess(); 
 
    DWORD_PTR processAffinityMask;
    DWORD_PTR systemAffinityMask;

    if (!GetProcessAffinityMask(process, &processAffinityMask, &systemAffinityMask))
        return -1;

    int core = 2; /* set this to the core you want your process to run on */
    DWORD_PTR mask=0x1;
    for (int bit=0, currentCore=1; bit < 64; bit++)
    {
        if (mask & processAffinityMask)
        {
            if (currentCore != core)
            {
                processAffinityMask &= ~mask;
            } else
            {
                if ( !(systemAffinityMask & mask) )
                {
                    cerr << "Core " << core << " not enabled in system." << endl;
                }
            }
            currentCore++;
        }
        mask = mask << 1;
    }

    BOOL success = SetProcessAffinityMask(process, processAffinityMask & systemAffinityMask); 
 
    cout << success << endl; 
 
    return 0; 
 
} 

The second parameter is a bitmask, where a bit that's set means the process can run on that proceesor, and a bit that's clear means it can't.

In your case, to have each process run on a separate core you could (for one possibility) pass a command line argument giving each process a number, and use that number inside the process to determine the processor to use:

#include <Windows.h>
#include <iostream>

using namespace std;

int main (int argc, char **argv) {
    HANDLE process = GetCurrentProcess();
    DWORD_PTR processAffinityMask = 1 << atoi(argv[1]);

    BOOL success = SetProcessAffinityMask(process, processAffinityMask);

    cout << success << endl;
    return 0;
}

Then you'd run this with something like:

for %c in (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) do test %c

Tags:

Windows

C++