参考了这篇文章:https://blog.csdn.net/lanyzh0909/article/details/50404664
大体的代码如下:
#include <pthread.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/sysinfo.h>
#include <sys/types.h>
#include <unistd.h>
void* _thread_func(void* param){
int thread_index = *(int*)param;
int cpu_count = sysconf(_SC_NPROCESSORS_CONF);
cpu_set_t mask; // CPU核的集合
cpu_set_t get; //获取在集合中的CPU
CPU_ZERO(&mask); //置空
CPU_SET(thread_index, &mask); //设置亲和力值
//设置线程CPU亲和力
if (sched_setaffinity(0, sizeof(mask), &mask) == -1) {
printf("warning: could not set CPU %d affinity, continuing...
", thread_index);
} else {
printf("thread %d set to cpu %d
", thread_index, thread_index);
}
}
在高通骁龙835处理器上,始终打印如下内容:
warning: could not set CPU 7 affinity, continuing...
thread 1 set to cpu 1
thread 0 set to cpu 0
thread 3 set to cpu 3
thread 2 set to cpu 2
warning: could not set CPU 4 affinity, continuing...
thread 5 set to cpu 5
thread 6 set to cpu 6
猜测是系统故意让其中的两个核无法被设置亲缘性,原因未知。