Is there a programmatic method to set CPU affinity for a process in c/c++ for the Linux operating system?
DESCRIPTION top. The taskset command is used to set or retrieve the CPU affinity of a running process given its pid, or to launch a new command with a given CPU affinity. CPU affinity is a scheduler property that "bonds" a process to a given set of CPUs on the system.
Method 1: System-wide System-wide we can set the boot. ini setting to use /numproc=4 so that the machine only uses 4 cores irrespective of the number of cores available (provided that there are 4 or more cores available) Method 2: Task Manager First, select a process from Task Manager. Then, click “Set affinity”.
As per Wikipedia, Processor affinity, or CPU pinning or “cache affinity”, enables the binding and unbinding of a process or a thread to a central processing unit (CPU) or a range of CPUs, so that the process or thread will execute only on the designated CPU or CPUs rather than any CPU.
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)
.
Use sched_setaffinity at the process level, or pthread_attr_setaffinity_np for individual threads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With