在很早之前就瞭解一項技術:線程綁定cpu。該項技術也應用到各種應用軟件,來提高性能。這裏把自己做的一個實驗記錄下來,方便日後查閱。
一、進程綁定cpu
我們通過系統調用sched_setaffinity進行綁定,通過sched_getaffinity獲取綁定關係。注意這對方法是進程級別的綁定。代碼中指定cpu0和cpu3,我們可以通過htop查看,兩個cpu使用達到了100%,其他的cpu均不會(正常場景)。
#define _GNU_SOURCE /* See feature_test_macros(7) */
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sched.h>
#include <pthread.h>
void* testfunc(void* t) {
while(1);
return NULL;
}
int main()
{
cpu_set_t mask;
printf("pid=%d\n", getpid());
CPU_ZERO(&mask);
CPU_SET(0, &mask);//將cpu0綁定
CPU_SET(3, &mask);//將cpu3綁定
sched_setaffinity(0, sizeof(cpu_set_t), &mask) ;
pthread_t tid1;//創建線程1
if (pthread_create(&tid1, NULL, (void *)testfunc, NULL) != 0)
{
fprintf(stderr, "thread create failed\n");
return -1;
}
pthread_t tid2;//創建線程2
if (pthread_create(&tid2, NULL, (void *)testfunc, NULL) != 0)
{
fprintf(stderr, "thread create failed\n");
return -1;
}
pthread_join(tid1, NULL);
pthread_join(tid1, NULL);
return 0;
}
二、線程綁定
對於線程綁定,我們需要藉助pthread庫,通過函數pthread_setaffinity_np來設置綁定cpu關係。我們通過htop查看,會放發現cpu0和cpu3使用率達到100%。
#define _GNU_SOURCE /* See feature_test_macros(7) */
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sched.h>
#include <pthread.h>
void* testfunc(void* t) {
int i = 3;
while(i) {
sleep(5);
printf("tid=%d,cpu=%d\n",pthread_self(), sched_getcpu());
i--;
}
while(1);
return NULL;
}
int main()
{
cpu_set_t mask;
printf("pid=%d\n", getpid());
CPU_ZERO(&mask);
pthread_t tid1;
if (pthread_create(&tid1, NULL, (void *)testfunc, NULL) != 0)
{
fprintf(stderr, "thread create failed\n");
return -1;
}
pthread_t tid2;
if (pthread_create(&tid2, NULL, (void *)testfunc, NULL) != 0)
{
fprintf(stderr, "thread create failed\n");
return -1;
}
printf("tid1=%d,tid2=%d\n", tid1,tid2);
CPU_SET(0, &mask);//綁定cpu0
pthread_setaffinity_np(tid1, sizeof(cpu_set_t), &mask) ;
//清除之前設置,重新設置綁定cpu3
CPU_ZERO(&mask);
CPU_SET(3, &mask);
pthread_setaffinity_np(tid2, sizeof(cpu_set_t), &mask) ;
pthread_join(tid1, NULL);
pthread_join(tid1, NULL);
return 0;
}
三、獨佔cpu
上面的設置只能保證進程或者線程運行在特定的cpu上,但仍然不能獨自享有,時間片到了也是有可能被切換出去。那麼有什麼方法將可以獨佔某個cpu呢?答案是肯定。我們可以設置linux 啓動參數grub,在啓動參數後面增加isolcpus=a,b,c。具體修改如下:
編輯grub文件後再執行該命令grub2-mkconfig -o /boot/grub2/grub.cfg更新grub,重要,重要,重要。
這樣在系統啓動後,操作系統就不會把任務調度到cpu0和cpu3上。但是我通過htop觀察cpu0、cpu3使用率,並非始終是0,而是有略微的變化,後來經過查詢相關說明,內核線程任然會調度到cpu0和cpu3上。也就是說這種方式只能控制用戶進程。
接下我們就可以通過sched_setaffinity方式進行綁定,以達到獨佔效果,但是操作grub要非常謹慎,搞不好系統會起不來啊。