setting CPU affinity error on windows pthread_setaffinity_np

1.3k views Asked by At

I have a multithread project. I want to set CPU affinity to particular thread. I am working on Windows and using MinGW compiler. but when i initialize type cpu_set_t, i have an error "type cpu_set_t was not declared in this scope". I dont understand the reason. I look forward your help! thank you!

#define _GNU_SOURCE
#include <iostream>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sched.h>
int main() 
{
   int core_id = 1;
   cpu_set_t cpuset; // error here
   CPU_ZERO(&cpuset);
   CPU_SET(core_id, &cpuset);
   pthread_t current_thread = pthread_self();    
   pthread_setaffinity_np(current_thread, sizeof(cpu_set_t), &cpuset);
}
1

There are 1 answers

0
meta_cookie On

Windows does not support the pthreads standard natively. MinGW project use winpthreads library as wrapper around native Windows threads.

'_np' suffix - means non-portable. The pthreads(posix) standard does require these *_np functions.

The current version of winpthreads does not have many of the *_np functions that can be seen on other operating systems such as Linux.

You could write your own function to change Windows threads affinity and call it from your thread. Something like that:

#include <windows.h>

// Bind thread to CPUs
// Return previous mask value on success, 0 on failure
DWORD_PTR BindThreadToCPU(
                            DWORD mask // 1  -  bind to cpu 0
                                       // 4  -  bind to cpu 2
                                       // 15 -  bind to cpu 0,1,2,3
                          )
{
    HANDLE th = GetCurrentThread();
    DWORD_PTR prev_mask = SetThreadAffinityMask(th, mask);
    return prev_mask;
}

Note: A thread affinity mask must be a subset of the process affinity mask.

Also there is an interesting quote from the Microsoft documentation regarding SetThreadAffinityMask() and their scheduler:

Thread affinity forces a thread to run on a specific subset of processors. Setting thread affinity should generally be avoided, because it can interfere with the scheduler's ability to schedule threads effectively across processors. This can decrease the performance gains produced by parallel processing. An appropriate use of thread affinity is testing each processor.

In modern versions of Windows there is SetThreadIdealProcessor() function that more friendly to the scheduler and allows you set preferred CPU for thread (but without any strict guarantees for affinity).