pthread_setaffinity_np

 

// bindcpu.c
// gcc bindcpu.c -o bind -lpthread -std=c99
#define _GNU_SOURCE //该宏定义必须有 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sched.h> #include <unistd.h> #include <pthread.h> #define CREATE_THREAD_NUMBER 2 #define JUDGE_IS_SUCCESS(RET) (RET == -1) struct thread_info { pthread_t thread_id; int thread_num; }; void do_thing_busy_cpu() { int j = 0; int buf[10240]; while(j++ < 1024*1024) { memset(buf, 0, sizeof(buf)); } } void *threadFunc(void *arg) { struct thread_info *subThreadInfo = (struct thread_info *)arg; pthread_t subThreadID = subThreadInfo->thread_id; printf("begin\n"); cpu_set_t g_cpuset; //定义cpu集合 CPU_ZERO(&g_cpuset); //初始化cpu集合 CPU_SET(subThreadInfo->thread_num, &g_cpuset); //将编号为subThreadInfo->thread_num的cpu核加到cpuset集合中 if(JUDGE_IS_SUCCESS(pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t),&g_cpuset))) { printf("ERROR:set CPU affinity fail!\n"); } printf("while()\n"); while(1) { cpu_set_t getCpuset; CPU_ZERO(&getCpuset); if(JUDGE_IS_SUCCESS(pthread_getaffinity_np(pthread_self() ,sizeof(cpu_set_t),&getCpuset))) { printf("ERROR:get CPU affinity fail!\n"); } for(int i=0; i<CREATE_THREAD_NUMBER; i++) { if(CPU_ISSET(i,&getCpuset)) { sleep(1); printf("thread %d is running on cpu: %d\n",subThreadInfo->thread_id,i); do_thing_busy_cpu(); } } } return NULL; } int main(int argc, char *argv[]) { struct thread_info threadInfo[CREATE_THREAD_NUMBER]; int cpuNum = sysconf(_SC_NPROCESSORS_CONF); printf("cpu number:%d\n",cpuNum); //创建2个线程 for(int i=0; i<CREATE_THREAD_NUMBER; i++) { threadInfo[i].thread_num = i; pthread_create(&threadInfo[i].thread_id,NULL,threadFunc,&threadInfo[i]); } for(int i=0; i<CREATE_THREAD_NUMBER; i++) { pthread_join(threadInfo[i].thread_id,NULL); } }

~/test/now$ ./bind
cpu number:48
begin
begin
while()
while()
thread 641070848 is running on cpu: 0
thread 632678144 is running on cpu: 1
thread 632678144 is running on cpu: 1
thread 641070848 is running on cpu: 0
thread 641070848 is running on cpu: 0
thread 632678144 is running on cpu: 1
thread 641070848 is running on cpu: 0

..........

posted @ 2023-12-02 17:55  牧 天  阅读(10)  评论(0)    收藏  举报