最近遇到些比較語法糖的知識,記錄下來防止忘記。
1. likely與unlikely
likely與unlikely是Kernel中提供的兩個宏,在Linux 2.6版本中,兩個宏的定義如下:
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
由于現(xiàn)代CPU都使用流水線的技術,在執(zhí)行當前機器指令時,下一條機器指令已經(jīng)被讀入寄存器;因此,使用likely與unlikely宏,使得程序員可以把條件判斷的分支概率分布情況告訴編譯器,從而提高流水線中指令命中的概率,提高執(zhí)行效率。
以下面一段代碼為例:
// 使用likely
#include <stdio.h>
#include <stdlib.h>
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
int main(int argc, char** argv)
{
int num;
num = atoi(argv[1]);
int a = 1;
int b = 2;
if(likely(num == 0xFF))
{
printf("a=%d", a);
}
else
{
printf("b=%d", b);
}
return 0;
}
//使用unlikely
#include <stdio.h>
#include <stdlib.h>
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
int main(int argc, char** argv)
{
int num;
num = atoi(argv[1]);
int a = 1;
int b = 2;
if(unlikely(num == 0xFF))
{
printf("a=%d", a);
}
else
{
printf("b=%d", b);
}
return 0;
}
上面兩個源碼文件唯一的差異就是在進行條件判斷的時候,使用了likely/unlikely,由此編譯產(chǎn)生的匯編機器碼差異如下:

可以看出,在likely/unlikely加持之下,GCC會有傾向性地安排匯編碼順序,提高執(zhí)行效率。
2. pthread_once執(zhí)行多線程唯一的初始化
有時候我們需要對一些posix變量只進行一次初始化,如果我們進行多次初始化程序就會出現(xiàn)錯誤。通常,一次性初始化經(jīng)常通過使用布爾變量來管理。控制變量被靜態(tài)初始化為0,而任何依賴于初始化的代碼都能測試該變量:如果變量值仍然為0,則它能實行初始化,然后將變量置為1。以后檢查的代碼將跳過初始化。
但是在多線程程序設計中,事情就變的復雜的多。如果多個線程并發(fā)地執(zhí)行初始化序列代碼,可能有2個線程發(fā)現(xiàn)控制變量為0,并且都實行初始化,而該過程本該僅僅執(zhí)行一次。pthread_once就可以解決這個問題。
int pthread_once(pthread_once_t *once_control, void (*init_routine) (void));
功能:pthread_once使用初值為PTHREAD_ONCE_INIT的once_control變量保證init_routine()函數(shù)在本進程執(zhí)行序列中僅執(zhí)行一次。
在多線程編程環(huán)境下,盡管pthread_once()調(diào)用會出現(xiàn)在多個線程中,init_routine()函數(shù)僅執(zhí)行一次,究竟在哪個線程中執(zhí)行是不定的,是由內(nèi)核調(diào)度來決定。
Linux Threads使用互斥鎖和條件變量保證由pthread_once()指定的函數(shù)執(zhí)行且僅執(zhí)行一次,而once_control表示是否執(zhí)行過。具體使用方法請參考以下代碼:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_once_t once_instance = PTHREAD_ONCE_INIT;
void once_func(void)
{
printf("once_func run in thread:%ld\n", pthread_self());
return;
}
void * thread1(void* arg)
{
pthread_t tid = pthread_self();
printf("enter thread-%ld\n", tid);
pthread_once(&once_instance, once_func);
printf("leave thread-%ld\n", tid);
}
void * thread2(void* arg)
{
pthread_t tid = pthread_self();
printf("enter thread-%ld\n", tid);
pthread_once(&once_instance, once_func);
printf("leave thread-%ld\n", tid);
}
int main()
{
pthread_t tid1, tid2;
printf("test start\n");
pthread_create(&tid1, NULL, thread1, NULL);
pthread_create(&tid2, NULL, thread2, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
printf("main thread exit\n");
return 0;
}
運行結果如下:
test start
enter thread-140572446230272
once_func run in thread:140572446230272
leave thread-140572446230272
enter thread-140572437837568
leave thread-140572437837568
main thread exit
可見,once_func在多線程環(huán)境下只執(zhí)行了一次,證明pthread_once適用于多線程環(huán)境下只執(zhí)行一次(常見于初始化)的語義。