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

Use sched_setaffinity at the process level, or pthread_attr_setaffinity_np for individual threads.


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 sched_getcpu(3).