1. GLibc API:
#include <sched.h>
int sched_setaffinity(pid_t pid, unsigned int cpusetsize,
cpu_set_t *mask);
int sched_getaffinity(pid_t pid, unsigned int cpusetsize,
cpu_set_t *mask);
Example:
unsigned int cpu_mask;
unsigned int pid = 1;
unsigned int mask = 0x1; // 绑定到 CPU0,0x2 则绑定到 CPU1
if (sched_getaffinity (pid, 4, &mask) < 0)
fprintf (stderr, "failed to get cpu affinity: %s\n", strerror (errno));
else
{
printf ("setting cpu affinity of pid=%d to %x\n", pid, cpu_mask);
if (sched_setaffinity (pid, 4, &cpu_mask) < 0)
fprintf (stderr, "failed to get cpu affinity: %s\n", strerror (errno));
else
if (sched_getaffinity (pid, 4, &mask) < 0)
fprintf (stderr, "failed to get cpu affinity: %s\n", strerror (errno));
else
printf ("cpu affinity of pid=%d is %x\n", pid, mask);
}
Other macros to manipulate the bitset (set, reset bits):
void CPU_CLR(int cpu, cpu_set_t *set);
int CPU_ISSET(int cpu, cpu_set_t *set);
void CPU_SET(int cpu, cpu_set_t *set);
void CPU_ZERO(cpu_set_t *set);
Reference:
http://www.gnu.org/software/libc/manual/html_node/CPU-Affinity.html
2. Kernel interface (CPU Sets)
运行一个无限循环程序 setaffinity_test (pid = 22580),top 的输出为:
......
Cpu0 : 24.1%us, 0.3%sy, 0.0%ni, 96.4%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Cpu1 : 77.8%us, 0.0%sy, 0.0%ni, 0.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Mem: 2033068k total, 1120456k used, 912612k free, 17348k buffers
Swap: 0k total, 0k used, 0k free, 125876k cached
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+COMMAND
22580 comcat 25 0 1496 312 252 R 100 0.0 2:54.74 setaffinity_test
......
其 status 为:
$ cat /proc/22580/status | grep allow
Cpus_allowed: 03 ----------> 可运行于 CPU0 和 CPU1
Mems_allowed: 1
$ mkdir /dev/cpuset
$ mount -t cpuset x /dev/cpuset
$ cd /dev/cpuset
$ mkdir my_cpuset && cd my_cpuset # 创建自己的设置
$ echo 1 > cpus # 绑定到 CPU1
$ echo 0 > mems
$ echo 22580 > tasks # 让 pid 为 22580 的进程绑定到 CPU1
cpuset 设置后,top 的输出为:
......
Cpu0 : 3.3%us, 0.3%sy, 0.0%ni, 96.4%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Cpu1 : 100%us, 0.0%sy, 0.0%ni, 0.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Mem: 2033068k total, 1120456k used, 912612k free, 17348k buffers
Swap: 0k total, 0k used, 0k free, 125876k cached
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+COMMAND
22703 comcat 25 0 1496 312 252 R 100 0.0 2:54.74 setaffinity_test
......
此时其 status 为:
$ cat /proc/22580/status | grep allow
Cpus_allowed: 02 ----------> 只可运行于 CPU1
Mems_allowed: 1
Reference:
http://www.bullopensource.org/cpuset/
http://www.mjmwired.net/kernel/Documentation/cpusets.txt
http://www.mjmwired.net/kernel/Documentation/cpu-hotplug.txt