所谓绑核,其实就是设定某个进程/线程与某个CPU核的亲和力(affinity)。设定以后,Linux调度器就会让这个进程/线程只在所绑定的核上面去运行。但并不是说
该进程/线程就独占这个CPU的核,其他的进程/线程还是可以在这个核上面运行的。如果想要实现某个进程/线程独占某个核,就要使用cpuset命令去实现。
其实,很多情况下,为了提高性能,Linux调度器会自动的实现尽量让某个进程/线程在同样的CPU上去运行。所以,除非必须,我们没有必要显式的去进程绑核操作。给出测试代码:
#include
#include
#include
#include
#include
#define __USE_GNU
#include
#include
#include
#include
#define THREAD_MAX_NUM 100 //1个CPU内的最多进程数
int num=0; //cpu中核数
void* threadFun(void* arg) //arg 传递线程标号
{
cpu_set_t mask; //CPU核的集合
cpu_set_t get; //获取在集合中的CPU
int *a = (int *)arg;
printf("the a is:%d\n",*a); //显示是第几个线程
CPU_ZERO(&mask); //置空
CPU_SET(*a,&mask); //设置亲和力值
if (sched_setaffinity(0, sizeof(mask), &mask) == -1)//设置线程CPU亲和力
{
printf("warning: could not set CPU affinity, continuing...\n");
}
while (1)
{
CPU_ZERO(&get);
if (sched_getaffinity(0, sizeof(get), &get) == -1)//获取线程CPU亲和力
{
printf("warning: cound not get thread affinity, continuing...\n");
}
int i;
for (i = 0; i < num; i++)
{
if (CPU_ISSET(i, &get))//判断线程与哪个CPU有亲和力
{
printf("this thread %d is running processor : %d\n", i,i);
}
}
}
return NULL;
}
int main(int argc, char* argv[])
{
num = sysconf(_SC_NPROCESSORS_CONF); //获取核数
pthread_t thread[THREAD_MAX_NUM];
printf("system has %i processor(s). \n", num);
int tid[THREAD_MAX_NUM];
int i;
for(i=0;i
编译:gcc bind.c -o bind -lpthread
执行:./bind
特别注意:
#define __USE_GNU不要写成#define _USE_GNU
#include
查看你的线程情况可以在执行时在另一个窗口使用top -H来查看线程的情况,查看各个核上的情况请使用top命令然后按数字“1”来查看。
如图: