POSIX 執行緒庫把底層的執行緒操作包裝成一組跨平台介面。在目前主流的 x86 Linux 上,核心通常會把新建立的執行緒調度到與主執行緒不同的核心上執行,以求負荷平衡。但這只是「通常」——開發者既不能斷定新執行緒與主執行緒同核,也不能斷定不同核。
還好 POSIX 執行緒具備時間片輪詢調度(Round-Robin),即使真的與主執行緒同核,搭配 spinlock 使用時效能損失也有限。不過若真要榨乾多核效能,更理想的做法是採用類似 OS X 與 iOS 中 Grand Central Dispatch 那樣的機制,由開發者顯式指定調度隊列。
使用時記得連結 libpthread,也就是在連結器選項加上 -lpthread。
以下程式在聯想 Z475(AMD APU A6-3420M、4GB DDR3、Ubuntu 12.04)上完成測試。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define TOTAL_CALC_ITEMS 1000000
extern unsigned long getRealtimeCycles(void);
static volatile _Bool isFinished = 0;
static volatile int sum4Core2 = 0;
static int sourceArray[TOTAL_CALC_ITEMS];
static void* threadProc(void *param)
{
int sum = 0;
int *pSrc = (int*)param;
for(int i = TOTAL_CALC_ITEMS / 2; i < TOTAL_CALC_ITEMS; i++)
sum += pSrc[i];
sum4Core2 = sum;
isFinished = 1;
return NULL;
}
static void testOpt(void)
{
// 初始化陣列
for(int i = 0; i < TOTAL_CALC_ITEMS; i++)
sourceArray[i] = i + 1;
pthread_t threadHandle;
pthread_attr_t attr;
if(pthread_attr_init(&attr) != 0)
{
puts("Attribute failed to create!");
return;
}
pthread_attr_setschedpolicy(&attr, SCHED_OTHER);
if(pthread_create(&threadHandle, &attr, &threadProc, sourceArray) != 0)
{
puts("Thread failed to create!");
return;
}
int polacy = -1;
pthread_attr_getschedpolicy(&attr, &polacy);
printf("Current sched polacy is: %d\n", polacy);
int sum = 0;
unsigned long ticks = getRealtimeCycles();
// 主執行緒負責前半段
for(int i = 0; i < TOTAL_CALC_ITEMS / 2; i++)
sum += sourceArray[i];
// 以 pause 指令做自旋等待,避免頻繁切換
while(!isFinished)
__asm__("pause");
sum += sum4Core2;
ticks = getRealtimeCycles() - ticks;
printf("The number of cycles is: %lu\n", ticks);
printf("The sum is: %d\n", sum);
pthread_attr_destroy(&attr);
}
static void testNaive(void)
{
for(int i = 0; i < TOTAL_CALC_ITEMS; i++)
sourceArray[i] = i + 1;
int sum = 0;
unsigned long ticks = getRealtimeCycles();
for(int i = 0; i < TOTAL_CALC_ITEMS; i++)
sum += sourceArray[i];
ticks = getRealtimeCycles() - ticks;
printf("The number of cycles is: %lu\n", ticks);
printf("The sum is: %d\n", sum);
}
int main(void)
{
testOpt();
testNaive();
testOpt();
testNaive();
return EXIT_SUCCESS; // 1784293664
}
計時用 rdtsc 讀取時間戳記計數器,這比 gettimeofday 精度更高,適合量測這類微觀差異:
.text
.align 2
.globl getRealtimeCycles
getRealtimeCycles:
rdtsc
shl $32, %rdx
or %rdx, %rax
ret
程式的重點在於對照:testOpt 把 100 萬筆累加切成兩半,主執行緒跑前半、子執行緒跑後半,用 isFinished 這個 volatile 旗標同步,再以 pause 指令自旋等待;testNaive 則是單執行緒硬跑。兩者交替執行兩輪,藉此排除首次執行的快取與分支預測偏差,比較出來的 cycle 數才有參考價值。