CPU affinity means that one or more processes can be bound to one or more processors in Linux.
The CPU affinity mask of a process determines which or which CPUs the process will run on. In a multi-processor system,
Setting the CPU affinity mask may provide better performance.
The affinity mask of one CPU uses oneCpu_set_tStruct to represent a CPU set,
The following macros operate on the mask set respectively:
1. cpu_zero ()Clear a set
2. cpu_set () and cpu_clr ()Add a given CPU number to a set or remove it from a set.
3. cpu_isset ()Check whether a CPU number is in this collection.
In fact, the usage of these functions is similar to that of the select () function.
The following two functions are the most important ones:
Sched_setaffinity (pid_t PID, unsigned int cpusetsize, cpu_set_t * mask)
This function sets the process as PID and runs on the CPU set by the mask. if the PID value is 0, it indicates that the current process is specified, so that the current process runs on the CPU set by the mask. the second parameter cpusetsize is the length of the number specified by the mask. usually set to sizeof (cpu_set_t ). if the CPU specified by the current PID does not run on any CPU specified by the mask, the specified process will be migrated from other CPUs to the specified CPU of the mask.
Sched_getaffinity (pid_t PID, unsigned int cpusetsize, cpu_set_t * mask)
This function obtains the CPU mask of the Process indicated by the PID and returns the mask to the structure pointed to by the mask. obtain the CPU on which the specified PID can run. similarly, if the PID value is 0. it also indicates the current process.
Example:
Through the sched_setaffinity function, you can set the CPU affinity so that the specified process runs on the specified CPU.
Cc smp. C-o SMP
./SMP> SMP. Log
How to view results:
Run top and press 1 to see: (of course, your CPU must be multi-core)
Top-13:03:30 up 3 days, 3 users, load average: 0.88, 0.28, 0.16
Tasks: 123 total, 3 running, 120 sleeping, 0 stopped, 0 zombie
Cpu0:0.0% us, 3.5% Sy, 0.0% Ni, 24.9% ID, 71.1% wa, 0.0% hi, 0.5% Si, 0.0% St
Cpu1:25.1% us, 19.6% Sy, 0.0% Ni, 0.0% ID, 62.8% wa, 0.0% hi, 0.0% Si, 0.0% St
Mem: 1023980 k total, 1008392 K used, 15588 K free, 56520 K Buffers
Swap: 979956 k total, 5172 K used, 974784 K free, 808188 K cached
Code SMP. c
# DEFINE _ gnu_source
# Include <sched. h>
# Include <stdio. h>
Int main (){
Cpu_set_t mask;
Cpu_zero (& Mask );
Cpu_set (1, & Mask); // In the CPU1Run on
If (sched_setaffinity (0, sizeof (cpu_set_t), & Mask) =-1)
Printf ("error happend ");
While (1 ){
Printf ("running on CPU 1 \ n ");
}
Return 0;
}
Refer:
Http://www.chinaunix.net/jh/4/904906.html
Http://hankjin.blog.163.com/blog/static/3373193720107191428377/