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);
}
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:
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: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).