#define_GNU_SOURCE#include<sched.h>voidset_affinity(int cord_id){long total_cpus =sysconf(_SC_NPROCESSORS_ONLN);printf("total cpus: %ld\n", total_cpus);//core index: 0 ~ total_cpus-1pid_t pid =getpid();cpu_set_t cpu_mask;CPU_ZERO(&cpu_mask);// 初始化set集,将set置为空CPU_SET(cord_id,&cpu_mask);//选择core_idint ret =sched_setaffinity(pid,sizeof(cpu_mask),&cpu_mask);if(ret !=0){printf("fail to set CPU affinity, error:%s\n",strerror(errno));}cpu_set_t cpu_get;sched_getaffinity(pid,sizeof(cpu_get),&cpu_get);for(int i =0; i < total_cpus; i++){if(CPU_ISSET(i,&cpu_get))printf("%d set core %d successfully\n", pid, i);}}
线程绑核
#define_GNU_SOURCE#include<pthread.h>voidset_pthread_affinity(int core_id){pthread_t tid =pthread_self();cpu_set_t cpu_mask;CPU_ZERO(&cpu_mask);// 初始化set集,将set置为空CPU_SET(core_id,&cpu_mask);//选择core_idint ret =pthread_setaffinity_np(tid,sizeof(cpu_set_t),&cpu_mask);if(ret !=0){printf("fail to bind core\n");}cpu_set_t cpu_get;pthread_getaffinity_np(tid,sizeof(cpu_set_t),&cpu_get);if(CPU_ISSET(core_id,&cpu_get)){printf("pthread %lu set core %d successfully\n", tid, core_id);}}//this is a pthreadvoid*worker(void*arg)//arg is core_id{int core_id =*((int*)arg);set_pthread_affinity(core_id);}