首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> 關於C

C語言多線程編程入門:pthread_create 創建多線程、參數傳遞與線程函數模型

     編輯:關於C

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

pthread_create 參數詳解

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)

常見錯誤與避坑

  1. 忘記 pthread_join:主線程跑完退出,子線程被強制終止,輸出不全或崩潰。
  2. 棧上數組作為參數:char buf[32]; pthread_create(..., buf); — 主線程修改/銷毀導致子線程讀到垃圾數據。解決:動態分配或靜態存儲參數。
  3. 傳遞整數值:pthread_create(..., (void*)(long)val) — 強轉為 intptr_t 而非指針,線程內 (long)arg 還原。
  4. 未檢查返回值:資源耗盡時創建失敗,後續邏輯錯誤。

進階:線程參數結構體模式

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 環境實際編寫、編譯、運行、調試,體會併發的非確定性本質。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved