From http://linux.die.net/man/2/sched_setaffinity
Name
sched_setaffinity, sched_getaffinity - set and get a process's CPU affinity mask
Synopsis
#define _GNU_SOURCE /* See feature_test_macros(7) */ #include <sched.h> int sched_setaffinity(pid_t pid, size_t cpusetsize, cpu_set_t *mask); int sched_getaffinity(pid_t pid, size_t cpusetsize, cpu_set_t *mask);
Description
A process's CPU affinity mask determines the set of CPUs on which it is eligible to run. On a multiprocessor system, setting the CPU affinity mask can be used to obtain performance benefits. For example, by dedicating one CPU to a particular process (i.e., setting the affinity mask of that process to specify a single CPU, and setting the affinity mask of all other processes to exclude that CPU), it is possible to ensure maximum execution speed for that process. Restricting a process to run on a single CPU also avoids the performance cost caused by the cache invalidation that occurs when a process ceases to execute on one CPU and then recommences execution on a different CPU.
A CPU affinity mask is represented by the cpu_set_t structure, a "CPU set",(是一个掩码数组,一共有1024位,每一位都可以对应一个cpu core)pointed bymask. A set of macros for manipulating CPU sets is described in cpu_set(3).
sched_setaffinity() sets the CPU affinity mask of the process whose ID ispid to the value specified by mask. If pid is zero, then the calling process is used(指当前正在执行的进程/线程). The argumentcpusetsize is the length (in bytes) of the data pointed to by mask. Normally this argument would be specified assizeof(cpu_set_t).
If the process specified by pid is not currently running on one of the CPUs specified inmask, then that process is migrated to one of the CPUs specified in mask.
sched_getaffinity() reads the affinity mask of the process whose ID ispid from the cpu_set_t structure pointed to by mask. Thecpusetsize argument specifies the size (in bytes) of mask. If pid is zero, then the mask of the calling process is returned.
Return Value
On success, sched_setaffinity() and sched_getaffinity() return 0. On error, -1 is returned, anderrno is set appropriately.
Errors
-
EFAULT
A supplied memory address was invalid.
EINVAL
The affinity bit mask mask contains no processors that are currently physically on the system and permitted to the process according to any restrictions that may be imposed by the "cpuset" mechanism described incpuset(7).
EINVAL
(sched_getaffinity() and, in kernels before 2.6.9, sched_setaffinity())cpusetsize is smaller than the size of the affinity mask used by the kernel.
EPERM
(sched_setaffinity()) The calling process does not have appropriate privileges. The caller needs an effective user ID equal to the real user ID or effective user ID of the process identified bypid, or it must possess the CAP_SYS_NICE capability.
ESRCH
The process whose ID is pid could not be found.