使用 sched_setaffinity 将线程绑到CPU核上运行
生活随笔
收集整理的這篇文章主要介紹了
使用 sched_setaffinity 将线程绑到CPU核上运行
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
linux 提供CPU調度函數,可以將CPU某一個核和指定的線程綁定到一塊運行。
這樣能夠充分利用CPU,且減少了不同CPU核之間的切換,尤其是在IO密集型壓力之下能夠提供較為友好的性能。
通過sched_setaffinity 設置 CPU 親和力的掩碼,從而將該線程或者進程和指定的CPU綁定
一個CPU的親合力掩碼用一個cpu_set_t結構體來表示一個CPU集合,下面的幾個宏分別對這個掩碼集進行操作:
CPU_ZERO() 清空一個集合
CPU_SET()與CPU_CLR()分別對將一個給定的CPU號加到一個集合或者從一個集合中去掉.
CPU_ISSET()檢查一個CPU號是否在這個集合中
- 頭文件
sched.h sched_setaffinity(pid_t pid, unsigned int cpusetsize, cpu_set_t *mask)
該函數設置進程為pid的這個進程,讓它運行在mask所設定的CPU上.- 如果pid的值為0,則表示指定的是當前進程,使當前進程運行在mask所設定的那些CPU上.
- 第二個參數cpusetsize是mask所指定的數的長度.通常設定為sizeof(cpu_set_t).如果當前pid所指定的進程此時沒有運行在mask所指定的任意一個CPU上,則該指定的進程會從其它CPU上遷移到mask的指定的一個CPU上運行.
- mask 即用戶 通過
CPU_SET接口,線程ID 綁定刀片集合中的一個CPU上,使用mask來表示cpu集合中的CPU
- sched_getaffinity(pid_t pid, unsigned int cpusetsize, cpu_set_t *mask)
該函數獲得pid所指示的進程的CPU位掩碼,并將該掩碼返回到mask所指向的結構中.即獲得指定pid當前可以運行在哪些CPU上.同樣,如果pid的值為0.也表示的是當前進程
使用方式如下:
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <signal.h>
#include <string.h>#define __USE_GNU
#include <sched.h>
#include <pthread.h>int num;void *thread_func1(void *arg) {cpu_set_t mask; //CPU核的集合cpu_set_t get; //獲取在集合中的CPUint *a = (int*)arg; printf("the a is:%d\n",*a); //顯示是第幾個線程CPU_ZERO(&mask); //置空CPU_SET(*a,&mask); // 將當前線程和CPU綁定if(sched_setaffinity(0, sizeof(mask), &mask)) {printf("warning ! set affinity failed! \n"); } else {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;
}void *thread_func2(void *arg) {cpu_set_t mask; //CPU核的集合cpu_set_t get; //獲取在集合中的CPUint *a = (int*)arg; printf("the a is:%d\n",*a); //顯示是第幾個線程CPU_ZERO(&mask); //置空CPU_SET(*a,&mask); // 將當前線程和CPU綁定if(sched_setaffinity(0, sizeof(mask), &mask) == -1) {printf("warning ! set affinity failed! \n"); } else {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() {pthread_t t1;pthread_t t2;int t_1 = 0;int t_2 = 1;// 獲取CPU核數num = sysconf(_SC_NPROCESSORS_CONF);// 需要傳入t_1,t_2,來作為線程的參數,用來核CPU核綁定pthread_create(&t1, NULL, (void *)thread_func1,&t_1);pthread_create(&t2, NULL, (void *)thread_func2,&t_2);pthread_join(t1, NULL);pthread_join(t2, NULL);printf("main thread end\n");return 0;
}
如果使用到pthread,則需要將pthread.h 放到sched.h之后,并在sched.h之前聲明#define __USE_GNU,
否則會出現undefined reference CPU_ZERO等錯誤
編譯:
gcc sched_cpu.c -o sched_cpu -pthread
以上代碼將兩個線程分別綁定到0,1號CPU上
運行后的CPU 效果圖如下:
總結
以上是生活随笔為你收集整理的使用 sched_setaffinity 将线程绑到CPU核上运行的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 天子多少钱啊?
- 下一篇: 关于 Rocksdb 性能分析 需要知