//compilation: gcc -o affinity affinity.c -lpthread
#define _GNU_SOURCE
#include //cpu_set_t , CPU_SET
#include //pthread_t
#include
void *th_func(void * arg);
int main(void) {
pthread_t thread; //the thread
pthread_create(&thread,NULL,th_func,NULL);
pthread_join(thread,NULL);
return 0;
}
void *th_func(void * arg)
{
//we can set one or more bits here, each one representing a single CPU
cpu_set_t cpuset;
//the CPU we whant to use
int cpu = 2;
CPU_ZERO(&cpuset); //clears the cpuset
CPU_SET( cpu , &cpuset); //set CPU 2 on cpuset
/*
* cpu affinity for the calling thread
* first parameter is the pid, 0 = calling thread
* second parameter is the size of your cpuset
* third param is the cpuset in which your thread will be
* placed. Each bit represents a CPU
*/
sched_setaffinity(0, sizeof(cpuset), &cpuset);
while (1);
; //burns the CPU 2
return 0;
}
在POSIX环境中,可以使用cpusets来控制进程或pthread可以使用哪些CPU。这种类型的控制称为CPU关联。
函数“ sched_setaffinity”接收pthread ID和cpuset作为参数。当您在第一个参数中使用0时,调用线程将受到影响