Note that I had to set CPU affinity for threads to do a certain experiment.
Process threads run on some CPU core depending on the OS. By setting the CPU affinity, the CPU cores to be executed can be arbitrarily restricted and specified.
Linux has a function sched_setaffinity for setting CPU affinity.
#define _GNU_SOURCE
#include <sched.h>
int main() {
pid_t pid;
cpu_set_t cpu_set;
int result;
pid = getpid;
CPU_ZERO(&cpu_set);
CPU_SET(2, &cpu_set);
result = sched_setaffinity(pid, sizeof(cpu_set_t), &cpu_set);
if (result != 0) {
//error
}
//processing
return 0;
}
The cpu_set_t structure represents a set of CPUs. Initialize the cpu_set_t structure with the CPU_ZERO function, and then specify the CPU core to be executed with the CPU_SET function. For a 4-core CPU, specify a value from 0 to 3 as the first argument. For details, refer to Manual.
sched_setaffinity The argument of the function is the process ID, the data size of cpu_set_t, and the pointer of cpu_set_t, in that order.
The first argument can be the getpid function. The second argument is basically sizeof (cpu_set_t). The third argument specifies the pointer of the cpu_set_t structure variable specified by CPU_SET.
With the above method, it is set in the process itself, so if you want to set affinity for each thread, it is a little different.
Depending on the environment, it is possible with pthread_setaffinity_np. The program example is omitted because it is described in Manual.
If the above function cannot be used, it can be set by passing the thread ID as the first argument of the sched_setaffinity function. If you can use the gettid function, you can just throw the pid_t structure variable obtained by the gettid function.
If the gettid function cannot be used, call the system call directly to get the thread ID.
#include <sched.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/types.h>
pid_t gettid(void) {
return syscall(SYS_gettid);
}
void* thread_main(void* args) {
pid_t pid;
cpu_set_t cpu_set;
int result;
pid = gettid;
CPU_ZERO(&cpu_set);
CPU_SET(2, &cpu_set);
result = sched_setaffinity(pid, sizeof(cpu_set_t), &cpu_set);
if (result != 0) {
//error
}
//processing
return NULL;
}
int main() {
pthread_t p;
pthread_create(&p, NULL, thread_main, NULL);
//processing
return 0;
}
Please point out any mistakes.
Recommended Posts