萬盛學電腦網

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

Linux 多線程同步機制:條件變數 詳解與生產者-消費者模型實戰

條件變數 是利用共享全域變數實現線程同步的機制,核心動作只有兩個:等待條件成立 (阻塞釋放鎖) 與 發出條件成立信號 (喚醒等待者)。為避免競態條件,條件變數必須配合互斥鎖 使用。

核心 API (POSIX pthread)

1. 定義與初始化/銷毀

#include <pthread.h>

pthread_cond_t cond_pro, cond_con;  // 定義兩個條件變數:生產者、消費者

// 初始化 (attr 通常為 NULL 使用預設屬性)
pthread_cond_init(&cond_pro, NULL);
pthread_cond_init(&cond_con, NULL);

// 銷毀 (確保無線程等待在此條件上)
pthread_cond_destroy(&cond_pro);
pthread_cond_destroy(&cond_con);

2. 等待與喚醒

// 阻塞等待條件成立
// 原子操作:解鎖 mutex -> 進入等待隊列 -> 休眠
// 被喚醒後:重新獲取 mutex -> 返回
int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);

// 喚醒「至少一個」等待該條件的線程 (通常喚醒隊列頭部)
int pthread_cond_signal(pthread_cond_t *cond);

// 喚醒「所有」等待該條件的線程 (廣播)
int pthread_cond_broadcast(pthread_cond_t *cond);

經典模型:生產者-消費者 (有界緩衝區)

共享變數 int i = 0 表示當前產品數量,上限 CELL=10,下限 FLOOR=0。
生產者:滿了等待 (cond_pro),生產後若從空變非空則 signal(cond_con)。
消費者:空了等待 (cond_con),消費後若從滿變非滿則 signal(cond_pro)。

完整可編譯代碼 (my_con.c)

/*************************************************************************
> File Name: my_con.c
> Author: KrisChou
> Compile: gcc my_con.c -o my_con -lpthread
> Run: ./my_con <生產者數量> <消費者數量>
***********************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>

#define CELL 10
#define FLOOR 0

int i = 0;                      // 共享資源
pthread_mutex_t mutex;          // 互斥鎖
pthread_cond_t cond_pro, cond_con; // 條件變數

void* producer(void *arg) {
    pthread_detach(pthread_self());
    while (1) {
        pthread_mutex_lock(&mutex);
        while (i >= CELL) {                 // **必須用 while,防止虛假喚醒**
            pthread_cond_wait(&cond_pro, &mutex);
        }
        i++;
        if (i == 1) {                       // 由空變非空,喚醒消費者
            pthread_cond_signal(&cond_con);
        }
        printf("produce: %d\n", i);
        pthread_mutex_unlock(&mutex);
        sleep(rand() % 5 + 1);
    }
    return NULL;
}

void* consumer(void *arg) {
    pthread_detach(pthread_self());
    while (1) {
        pthread_mutex_lock(&mutex);
        while (i <= FLOOR) {                // **必須用 while**
            pthread_cond_wait(&cond_con, &mutex);
        }
        i--;
        if (i == CELL - 1) {                // 由滿變非滿,喚醒生產者
            pthread_cond_signal(&cond_pro);
        }
        printf("consume: %d\n", i);
        pthread_mutex_unlock(&mutex);
        sleep(rand() % 5 + 1);
    }
    return NULL;
}

int main(int argc, char *argv[]) {
    if (argc != 3) {
        fprintf(stderr, "Usage: %s <producer_count> <consumer_count>\n", argv[0]);
        return 1;
    }
    srand(getpid());
    int pro_cnt = atoi(argv[1]);
    int con_cnt = atoi(argv[2]);

    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond_pro, NULL);
    pthread_cond_init(&cond_con, NULL);

    pthread_t *threads = calloc(pro_cnt + con_cnt, sizeof(pthread_t));
    int idx = 0;
    while (pro_cnt--) pthread_create(&threads[idx++], NULL, producer, NULL);
    while (con_cnt--) pthread_create(&threads[idx++], NULL, consumer, NULL);

    // 主線程永久休眠,讓分離線程持續運行
    while (1) sleep(100);

    // 理論上不會執行到這裡,正常關閉需加入信號處理
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond_pro);
    pthread_cond_destroy(&cond_con);
    free(threads);
    return 0;
}

關鍵細節深度解析

為什麼等待條件要用 while 而非 if?

虛假喚醒:線程可能在未收到 signal/broadcast 的情況下被喚醒 (POSIX 允許)。
競態窗口:signal 發出後,被喚醒線程需重新搶鎖才能真正繼續。在此間隙,其他線程可能已改變共享狀態 (如再次變滿/空)。
結論: while (條件不滿足) pthread_cond_wait(...) 是唯一正確模式,醒來後重新檢查條件。

signal vs broadcast 選擇

  • signal:喚醒一個線程。適用於「單一資源、單一等待者受益」場景 (如生產者消費者,一次只產生一個產品,喚醒一個消費者即可),效能較好。
  • broadcast:喚醒所有等待者。適用於「狀態變化可能滿足多個不同條件的等待者」或「不確定喚醒誰」的場景。濫用會導致「驚群效應」,大量線程同時搶鎖、檢查條件、再次休眠,效能驟降。

鎖的保護範圍

共享變數 i 的所有讀寫、條件判斷、signal 呼叫,必須在鎖保護下 進行。代碼中 pthread_mutex_lock 到 unlock 之間涵蓋了完整邏輯,確保原子性。

編譯與運行

gcc my_con.c -o my_con -lpthread
./my_con 2 3   # 2個生產者,3個消費者

觀察輸出,i 值將始終維持在 0~10 區間,無競態錯誤。

copyright © 萬盛學電腦網 all rights reserved