萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux 多線程程式設計入門:pthread 建立、互斥鎖同步與線程等待完整範例

核心概念

  • 線程 (Thread): 輕量級執行單元,共享進程地址空間 (堆、全域變數、代碼段),獨擁棧、寄存器、線程 ID。
  • Pthreads (POSIX Threads): 標準 C 線程庫 (pthread.h, -lpthread)。
  • 同步原語: 互斥鎖 (pthread_mutex_t)、條件變數 (pthread_cond_t)、讀寫鎖、屏障、自旋鎖。

完整可編譯範例:兩線程安全計數器

#include 
#include 
#include 
#include 
#include 

#define MAX 10

pthread_t threads[2];
pthread_mutex_t mutex;
int counter = 0;

void *thread_func(void *arg) {
    int id = *(int *)arg;
    printf("Thread %d: Started\n", id);

    for (int i = 0; i < MAX; i++) {
        // 加鎖保護共享變數
        pthread_mutex_lock(&mutex);
        printf("Thread %d: counter = %d\n", id, counter);
        counter++;
        pthread_mutex_unlock(&mutex);

        sleep(id == 0 ? 2 : 3); // 模擬不同工作負載
    }

    printf("Thread %d: Finished, waiting for main?\n", id);
    pthread_exit(NULL);
}

int main() {
    int ids[2] = {1, 2};
    int rc;

    // 初始化互斥鎖 (默認屬性)
    if (pthread_mutex_init(&mutex, NULL) != 0) {
        perror("Mutex init failed");
        return 1;
    }

    printf("Main: Creating threads...\n");

    // 建立線程
    for (int i = 0; i < 2; i++) {
        rc = pthread_create(&threads[i], NULL, thread_func, &ids[i]);
        if (rc != 0) {
            fprintf(stderr, "Thread %d creation failed: %s\n", i+1, strerror(rc));
            return 1;
        }
        printf("Main: Thread %d created\n", i+1);
    }

    printf("Main: Waiting for threads to finish...\n");

    // 等待線程結束 (回收資源)
    for (int i = 0; i < 2; i++) {
        if (threads[i] != 0) {
            pthread_join(threads[i], NULL);
            printf("Main: Thread %d joined\n", i+1);
        }
    }

    // 銷毀互斥鎖
    pthread_mutex_destroy(&mutex);

    printf("Main: Final counter = %d (expected %d)\n", counter, 2 * MAX);
    return 0;
}

編譯與執行

gcc -o pthread_demo pthread_demo.c -lpthread
./pthread_demo

關鍵 API 詳細解析

API原型關鍵點
pthread_createint pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);attr=NULL 用默認屬性 (可加入分離狀態、棧大小等);start_routine 返回 void* 傳給 pthread_join;arg 傳遞參數 (注意生命週期)
pthread_mutex_initint pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);動態初始化;靜態初始化用 PTHREAD_MUTEX_INITIALIZER (僅適用默認屬性)
pthread_mutex_lock/unlockint pthread_mutex_lock(pthread_mutex_t *mutex);阻塞式獲取/釋放;必須成對調用,建議用 pthread_cleanup_push/pop 或 C++ RAII 保證異常/提前返回時解鎖
pthread_joinint pthread_join(pthread_t thread, void **retval);阻塞等待目標線程結束,**必須調用** 否則線程變「殭屍」洩漏資源;retval 接收 pthread_exit / 返回值
pthread_detachint pthread_detach(pthread_t thread);分離狀態:線程結束自動回收資源,**不可再 join**;適用火燭忘型任務
pthread_exitvoid pthread_exit(void *retval);主動退出線程;main 調用僅結束主線程,進程持續直到所有線程結束

進階同步機制

條件變數 : 生產者-消費者模型

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int buffer = 0; // 共享資源

void *producer(void *arg) {
    for (int i = 0; i < 10; i++) {
        pthread_mutex_lock(&mutex);
        while (buffer != 0) pthread_cond_wait(&cond, &mutex); // 等待空槽
        buffer = i;
        printf("Produced: %d\n", buffer);
        pthread_cond_signal(&cond); // 喚醒消費者
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}

void *consumer(void *arg) {
    for (int i = 0; i < 10; i++) {
        pthread_mutex_lock(&mutex);
        while (buffer == 0) pthread_cond_wait(&cond, &mutex); // 等待資料
        printf("Consumed: %d\n", buffer);
        buffer = 0;
        pthread_cond_signal(&cond); // 喚醒生產者
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}

關鍵: pthread_cond_wait **原子性釋放鎖並休眠**,被喚醒後**重新獲取鎖**再返回。條件判斷**必須用 while 迴圈**防止虛假喚醒。

讀寫鎖 : 讀多寫少場景

pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
// 讀者
pthread_rwlock_rdlock(&rwlock); ... pthread_rwlock_unlock(&rwlock);
// 寫者
pthread_rwlock_wrlock(&rwlock); ... pthread_rwlock_unlock(&rwlock);

常見錯誤與避坑

錯誤後果修正
忘記 pthread_join線程資源洩漏、進程無法正常退出所有可連接線程必須 join 或 detach
鎖保護範圍過大並發度下降、死鎖風險縮小臨界區,僅保護共享變數存取
雙重鎖定 / 遺漏解鎖死鎖 / 未定義行為RAII 封裝 (C++), pthread_cleanup_push/pop (C)
傳遞棧上變數指針給線程主線程返回後指針失效malloc/靜態/全域/結構體傳遞,線程負責 free
條件變數用 if 而非 while虛假喚醒導致邏輯錯誤永遠用 while 檢查條件
未初始化 mutex/cond 直接使用未定義行為 (通常崩潰)動態 init 或靜態 INITIALIZER

C++11/17/20 現代替代 (強烈推薦)

#include 
#include 
#include 
#include 

std::mutex mtx;
std::condition_variable cv;
int counter = 0;

void worker(int id) {
    for (int i = 0; i < 10; i++) {
        std::lock_guard lock(mtx); // RAII 自動解鎖
        std::cout << "Thread " << id << ": " << counter++ << '\n';
    }
}

int main() {
    std::vector threads;
    for (int i = 1; i <= 2; ++i) threads.emplace_back(worker, i);
    for (auto &t : threads) t.join(); // RAII join
    std::cout << "Final: " << counter << '\n';
}

優勢: RAII 鎖管理、型別安全、lambda 捕獲參數、std::jthread (C++20) 自動 join、std::counting_semaphore, std::latch, std::barrier 更高階同步原語。

總結

Pthreads 是 Linux 多線程的基石。掌握 建立/等待/互斥鎖/條件變數/讀寫鎖 核心 API、理解 共享記憶體模型、臨界區保護、死鎖預防、線程生命週期管理,是系統程式設計師必備技能。現代 C++ 專案請優先使用 <thread>, <mutex>, <condition_variable> 等標準庫設施,獲得更安全、更具表達力的並發程式體驗。

copyright © 萬盛學電腦網 all rights reserved