How to set CPU affinity for a process from C or C++ in Linux?

You need to use sched_setaffinity(2). For example, to run on CPUs 0 and 2 only: #define _GNU_SOURCE #include <sched.h> cpu_set_t mask; CPU_ZERO(&mask); CPU_SET(0, &mask); CPU_SET(2, &mask); int result = sched_setaffinity(0, sizeof(mask), &mask); (0 for the first parameter means the current process, supply a PID if it’s some other process you want to control). See also … Read more

how to set CPU affinity of a particular pthread?

This is a wrapper I’ve made to make my life easier. Its effect is that the calling thread gets “stuck” to the core with id core_id: // core_id = 0, 1, … n-1, where n is the system’s number of cores int stick_this_thread_to_core(int core_id) { int num_cores = sysconf(_SC_NPROCESSORS_ONLN); if (core_id < 0 || core_id … Read more