Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there a programmatic method to set CPU affinity for a process in c/c++ for the Linux operating system?

like image 490
jcodeninja Avatar asked Nov 11 '08 13:11

jcodeninja


People also ask

Which command is used to set affinity of a process to a specific CPU?

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.

How do you launch a process with CPU affinity set?

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”.

What is CPU affinity in Linux?

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.


2 Answers

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).

like image 108
Alnitak Avatar answered Sep 20 '22 07:09

Alnitak


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

like image 33
puetzk Avatar answered Sep 18 '22 07:09

puetzk