執行緒是 CPU 排程基本單位,共享進程位址空間,建立/切換開銷遠小於進程。POSIX 執行緒 (pthread) 提供標準化跨平台介面,是高併發伺服器開發核心技術。
| 函數 | 用途 | 關鍵點 |
|---|---|---|
pthread_create | 建立執行緒 | 需 -pthread 編譯連結,傳入啟動函數 void*(*)(void*) |
pthread_join | 等待執行緒結束 (收屍) | 任意執行緒可 join 任意執行緒,無父子關係 |
pthread_exit | 主動結束執行緒 | 返回值透過 join 的 void** 取得 |
pthread_cancel | 請求取消執行緒 | 非立即生效,需到達取消點 (如 pthread_testcancel、I/O 系統呼叫) |
pthread_detach | 分離執行緒 | 資源自動回收,不可 join |
pthread_self/pthread_equal | 取得/比較執行緒 ID | 不直接操作 pthread_t,不透明類型 |
pthread_cleanup_push(routine, arg); // 註冊 // ... 程式碼區塊 ... pthread_cleanup_pop(execute); // 執行並彈出 (execute=1) 或 僅彈出 (0)
do { ... } while(0) 結構atexitpthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // 靜態初始化 pthread_mutex_init(&mutex, NULL); // 動態初始化 pthread_mutex_lock(&mutex); // 阻塞式加鎖 pthread_mutex_trylock(&mutex); // 非阻塞嘗試 pthread_mutex_unlock(&mutex); // 解鎖 pthread_mutex_destroy(&mutex); // 銷毀 (釋放資源)
臨界區原則:加鎖→最小操作→解鎖。鎖保護的是程式碼區段,非變數本身。
四執行緒循環列印 a/b/c/d,使用條件變數比鎖鏈更優雅:
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int num = 0; // 當前應列印的執行緒編號 0-3
void* thr_func(void* arg) {
int n = (int)arg; char ch = 'a' + n;
while (1) {
pthread_mutex_lock(&mut);
while (num != n) pthread_cond_wait(&cond, &mut); // 原子解鎖+等待
putchar(ch);
num = (num + 1) % 4;
pthread_cond_broadcast(&cond); // 喚醒所有等待者
pthread_mutex_unlock(&mut);
}
}
| 函數 | 語義 |
|---|---|
pthread_cond_wait | 原子:解鎖 mutex + 睡眠等待 + 重新加鎖 |
pthread_cond_timedwait | 帶超時的等待 |
pthread_cond_signal | 喚醒一個等待者 |
pthread_cond_broadcast | 驚群:喚醒所有等待者 |
選擇原則:明確知道誰該工作用 signal,不確定或多對多用 broadcast。
支援 1024 個獨立桶,每桶固定速率 (CPS) 與突發上限:
job[MAX] + 全域鎖 mut_job 保護桶陣列cps, burst, token, pos, mut, condthr_alrm 每秒 sleep(1) 遍歷所有桶填充 token,pthread_cond_broadcast 通知等待者mytbf_fetchtoken:while(token<=0) pthread_cond_wait(&cond, &mut); 非忙等待pthread_once 確保填充執行緒只啟動一次pthread_cancel + join 回收執行緒,銷毀所有鎖/條件變數ulimit -s 調整)trylock 避免死鎖gcc -Wall -pthread thread_demo.c -o thread_demo ps ax -L # 查看 LWP (執行緒 ID) 驗證建立成功
掌握 pthread 同步原語與設計模式,是構建高效能、高可靠性併發系統的關鍵能力。