最近在做專案效能優化,跑在多核平台上,因此研究了一下 process 與線程綁定 CPU 核的問題,把所學記錄下來。
不論線程或 process,都是透過設定親和性(affinity)來達成目的。process 的情況一般用 sched_setaffinity,網上討論很多;這裡主要講線程。
線程親和性的設定與取得靠這兩個函式:
int pthread_setaffinity_np(pthread_t thread, size_t cpusetsize,
const cpu_set_t *cpuset);
int pthread_getaffinity_np(pthread_t thread, size_t cpusetsize,
cpu_set_t *cpuset);
函式名與參數名都很直白,唯一需要解釋的是 cpu_set_t 這個結構體。它的概念類似 select 中的 fd_set,可以理解為「CPU 集合」,同樣透過約定好的巨集來清除、設定與判斷:
void CPU_ZERO(cpu_set_t *set); // 初始化,設為空 void CPU_SET(int cpu, cpu_set_t *set); // 把某個 cpu 加入集合 void CPU_CLR(int cpu, cpu_set_t *set); // 把某個 cpu 移出集合 int CPU_ISSET(int cpu, const cpu_set_t *set); // 判斷某 cpu 是否已在集合中
這個集合可以看作一個遮罩:每個被設定的位對應一個可合法調度的 CPU,未設定的位則對應不可調度的 CPU。換句話說,線程只能在那些被設定的處理器上運行。一般情況下遮罩所有位都會被置位,也就是可以在所有 CPU 之間自由調度。
測試程式碼如下:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sched.h>
void *myfun(void *arg)
{
cpu_set_t mask;
cpu_set_t get;
char buf[256];
int i;
int j;
int num = sysconf(_SC_NPROCESSORS_CONF);
printf("system has %d processor(s)\n", num);
for (i = 0; i < num; i++) {
CPU_ZERO(&mask);
CPU_SET(i, &mask);
if (pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask) < 0) {
fprintf(stderr, "set thread affinity failed\n");
}
CPU_ZERO(&get);
if (pthread_getaffinity_np(pthread_self(), sizeof(get), &get) < 0) {
fprintf(stderr, "get thread affinity failed\n");
}
for (j = 0; j < num; j++) {
if (CPU_ISSET(j, &get)) {
printf("thread %d is running in processor %d\n",
(int)pthread_self(), j);
}
}
j = 0;
while (j++ < 100000000) {
memset(buf, 0, sizeof(buf));
}
}
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
pthread_t tid;
if (pthread_create(&tid, NULL, (void *)myfun, NULL) != 0) {
fprintf(stderr, "thread create failed\n");
return -1;
}
pthread_join(tid, NULL);
return 0;
}
這段程式會讓 myfun 線程依序在每個 CPU 上各跑一段時間。在我的四核心機器上,輸出是:
system has 4 processor(s) thread 1095604544 is running in processor 0 thread 1095604544 is running in processor 1 thread 1095604544 is running in processor 2 thread 1095604544 is running in processor 3
在一些嵌入式裝置中,運行的 process 與線程比較單一,若指定它們跑在特定 CPU 核上、減少跨核切換,確實有機會拿到更高的效能。不過這招要慎用:把多個忙碌線程綁到同一核只會互相排擠,綁定的價值通常在「隔離中斷處理與關鍵服務」這類場景才看得出來。
延伸閱讀:IBM developerWorks 的 Linux affinity 文章。