In a multi-core CPU, the CPU core on which the process thread runs depends on the OS scheduler, and the context may move to another CPU core depending on the situation. In Linux, you can set CPU affinity to prevent such movements and allow process threads to run only on specific CPU cores (mainly due to performance issues).
A collection of logical CPUs that the thread is allowed to execute. CPU affinity is represented by a bitmask.
As an example, CPU0 is 0x00000001
, CPU1 is 0x00000002
, and the set of CPU0,1,3 is 0x0000000b
.
You can check which CPU core CPU0 is actually by using cat / proc / cpuinfo
.
You can set the CPU affinity of a process with the command taskset.
# taskset -p mask pid
For mask, specify the CPU affinity, and for pid, specify the process you want to change.
Use the -a
option to change for all threads in the process pid.
# taskset -a -p mask pid
Only that process is allowed to run on that CPU, and all other processes are unallowed.
# ps -e -o pid= | xargs -n 1 taskset -p 0xFFFFFFFE
# taskset -p 0x00000001 PID
To set CPU affinity programmatically, use the function sched_setaffinity ().
#define _GNU_SOURCE /* feature_test_See macros*/
#include <sched.h>
void
func(void)
{
cpu_set_t mask;
int ret;
//Turn off all masks
CPU_ZERO(&mask);
// CPU_AFFINITY_Allow running on the core of MASK
CPU_SET(CPU_AFFINITY_MASK, &mask);
//Set CPU affinity
ret = sched_setaffinity(0, sizeof(mask), &mask);
if (ret != 0) {
// error
}
}
Recommended Posts