POSIX 線程 是 Unix/Linux 多線程編程的標準接口。本文通過創建 5 個線程並發執行同一線程函數的完整示例,講解 pthread_create 參數詳解、線程參數傳遞、線程退出與主線程同步基礎。
#include#include #include #include #include // 線程函數原型:void* (*)(void*) void* thread_func(void* arg) { char* msg = (char*)arg; printf("%s\n", msg); pthread_exit(NULL); // 正常退出,返回值可被 join 獲取 return NULL; } int main() { pthread_t threads[5]; char* params[5] = { "This is Thread:1", "This is Thread:2", "This is Thread:3", "This is Thread:4", "This is Thread:5" }; printf("Create multi thread\n"); // 創建 5 個線程 for (int i = 0; i < 5; i++) { int ret = pthread_create(&threads[i], NULL, thread_func, params[i]); if (ret != 0) { fprintf(stderr, "pthread_create failed: %s\n", strerror(ret)); return 1; } sleep(1); // 錯開創建時間,觀察併發效果 } // 等待所有線程結束(關鍵:否則主線程退出導致進程終止) for (int i = 0; i < 5; i++) { pthread_join(threads[i], NULL); } printf("All threads finished\n"); return 0; }
Create multi thread This is Thread:1 This is Thread:2 This is Thread:3 This is Thread:4 This is Thread:5 All threads finished
int pthread_create(
pthread_t* thread, // 輸出:線程 ID
const pthread_attr_t* attr, // 屬性:NULL=默認(可加入、非分離、默認棧大小)
void* (*start_routine)(void*), // 線程入口函數
void* arg // 傳給線程函數的唯一參數
);
| 概念 | 說明 |
|---|---|
| 線程函數簽名 | 必須為 void* func(void*),單參數、單返回值 |
| 參數傳遞 | 通過 void* arg 傳遞任意類型指針,線程內強轉回原類型 |
| 線程退出 | pthread_exit(retval) 或 return retval,返回值被 pthread_join 獲取 |
| 主線程同步 | 必須 調用 pthread_join 等待子線程,否則進程提前退出 |
| 分離態 | pthread_detach(tid) 或屬性 PTHREAD_CREATE_DETACHED,無需 join,資源自動回收 |
| 編譯鏈接 | gcc -pthread demo.c -o demo (GCC/Clang 自動鏈接 pthread) |
char buf[32]; pthread_create(..., buf); — 主線程修改/銷毀導致子線程讀到垃圾數據。解決:動態分配或靜態存儲參數。pthread_create(..., (void*)(long)val) — 強轉為 intptr_t 而非指針,線程內 (long)arg 還原。typedef struct {
int id;
double threshold;
const char* name;
} ThreadArg;
void* worker(void* arg) {
ThreadArg* a = (ThreadArg*)arg;
printf("Thread %d (%s) started, threshold=%.2f\n", a->id, a->name, a->threshold);
// ... 工作邏輯
free(a); // 線程負責釋放參數內存
return NULL;
}
int main() {
for (int i = 0; i < 3; i++) {
ThreadArg* arg = malloc(sizeof(ThreadArg));
*arg = (ThreadArg){i, 0.5*i, "worker"};
pthread_create(&tid, NULL, worker, arg);
}
// ... join
}
線程創建後的執行順序由操作系統調度器決定,受優先級、時間片、負載、CPU 核心數影響。sleep(1) 僅增加可觀測性,**不能**保證執行順序。同步機制(互斥鎖、條件變量、信號量、屏障)是下一階段學習重點。
掌握 pthread_create/join/exit 基礎三件套,是 C 多線程編程的入門門檻。建議在 Linux/macOS/WSL 環境實際編寫、編譯、運行、調試,體會併發的非確定性本質。