Linux 编程绑定特定CPU运行
2020-10-20 16:50 宋海宾 阅读(674) 评论(0) 编辑 收藏 举报为了让程序拥有更好的性能,有时候需要将进程或线程绑定到特定的CPU上,这样可以减少调度的开销和保护关键进程或线程。
1、绑定进程到指定的CPU
Linux提供一个接口,可以将进程绑定到特定的CPU:
#include <sched.h>
int sched_setaffinity(pid_t pid, size_t cpusetsize, const cpu_set_t *set);
int sched_getaffinity(pid_t pid, size_t cpusetsize, cpu_set_t *set);
参数:
pid:进程的id号,如果pid为0,则表示本进程
cpusetsize:set的大小
set:运行进程的CPU,可以通过以下函数操作set:
void CPU_ZERO(cpu_set_t *set); // Clears set, so that it contains no CPUs.
void CPU_SET(int cpu, cpu_set_t *set); // Add CPU cpu to set.
void CPU_CLR(int cpu, cpu_set_t *set); // Remove CPU cpu from set.
int CPU_ISSET(int cpu, cpu_set_t *set); // Test to see if CPU cpu is a member of set.
int CPU_COUNT(cpu_set_t * mask); //Return the number of CPUs in set.
进程绑定到指定CPU的演示程序如下:
测试:编译程序,之后运行,我编译出的文件名为a.out,执行下列命令,得到a.out的PID:ps –elf | grep a.out,之后输入命令:top -p 进程ID,接着输入f,选择P选项(移到P处,按下空格),按ESC退出,具体过程如下:
2、绑定线程到指定的CPU
不仅仅进程可以绑定到CPU,线程也可以。Linux提供一个接口,可以将线程绑定到特定的CPU:
#include <pthread.h>
int pthread_setaffinity_np(pthread_t thread, size_t cpusetsize, const cpu_set_t *cpuset);
int pthread_getaffinity_np(pthread_t thread, size_t cpusetsize, cpu_set_t *cpuset);
该接口与进程绑定到CPU的接口的使用方法基本一致。
当进程绑定到特定的CPU之后,线程还是可以绑定到其他的CPU的,没有冲突。
示例代码如下:
测试:编译程序,之后运行,我编译出的文件名为a.out,执行下列命令,得到a.out的PID:ps –elf | grep a.out,之后输入命令:top -H -p 进程ID,接着输入f,选择P选项(移到P处,按下空格)和nTH选项,按ESC退出,具体过程如下:
可以看到主线程一直保持在cpu0,一个线程在cpu12之前切换,另一个线程一直保持在cpu3: