Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

用 POSIX 執行緒實作「生產者/消費者」問題

「生產者/消費者」是多執行緒程式設計的經典題目:一邊負責生產資料、一邊負責消費資料,兩者透過一個緩衝佇列溝通。核心難題在於——當佇列已滿時生產者必須停下等待,當佇列為空時消費者必須阻塞,而且全程都要避免資料競爭(data race)。本例以 pthread 的互斥鎖與條件變量,打造一個先進先出的管線。

/*
*   File    : pc.cpp
*   Title   : Demo Producer/Consumer.
*   Short   : A solution to the producer consumer problem using pthreads.
*             A simple FIFO pipe between two tasks. The producer blocks if
*             the FIFO is full, the consumer blocks if it is empty, while
*             avoiding data-races. A secondary concern is minimal interference
*             between the two tasks.
*   Author  : Andrae Muys
*   Date    : 18 September 1997
*/

#include <stdlib.h>
#include <pthread.h>
#include <assert.h>

#ifdef _WIN32
#   include <windows.h>
#   define SLEEP(ms) Sleep(ms)
#elif defined(LINUX)
#   include <unistd.h>
#   define SLEEP(ms) sleep(ms)
#endif

#define QUEUE_SIZE  10
#define LOOP        20

void* producer (void *args);
void* consumer (void *args);

typedef struct
{
    int buf[QUEUE_SIZE];
    long head, tail;
    bool full, empty;
    pthread_mutex_t *mutex;
    pthread_cond_t *notFull, *notEmpty;
} Queue;

Queue*  queueInit (void);
void    queueDelete (Queue *q);
void    queueAdd (Queue *q, int in);
void    queueDel (Queue *q, int *out);

int main(int argc, char* argv[])
{
    Queue* fifo = queueInit ();
    assert(fifo !=  NULL);

    pthread_t pro, con;
    pthread_create (&pro, NULL, &producer, fifo);
    pthread_create (&con, NULL, &consumer, fifo);
    pthread_join (pro, NULL);
    pthread_join (con, NULL);
    queueDelete (fifo);
    return 0;
}

void* producer (void *q)
{
    Queue* fifo = (Queue *)q;

    for (int i = 0; i < LOOP; i++)
    {
        // 臨界區操作:若佇列未滿,添加新資料
        pthread_mutex_lock (fifo->mutex);
        while (fifo->full)
        {
            printf ("producer: Queue FULL.\n");
            pthread_cond_wait (fifo->notFull, fifo->mutex);
        }
        queueAdd (fifo, i);
        pthread_mutex_unlock (fifo->mutex);

        // 資料添加結束,發「佇列有資料」信號
        pthread_cond_signal (fifo->notEmpty);
        SLEEP (100);
    }

    // 與上面類似
    for (int i = 0; i < LOOP; i++)
    {
        pthread_mutex_lock (fifo->mutex);
        while (fifo->full)
        {
            printf ("producer: Queue FULL.\n");
            pthread_cond_wait (fifo->notFull, fifo->mutex);
        }
        queueAdd (fifo, i);
        pthread_mutex_unlock (fifo->mutex);
        pthread_cond_signal (fifo->notEmpty);
        SLEEP (200);
    }
    return (NULL);
}

void* consumer (void *q)
{
    int d;

    Queue *fifo = (Queue *)q;

    for (int i = 0; i < LOOP; i++)
    {
        // 臨界區操作:若佇列不空,則取出資料
        pthread_mutex_lock (fifo->mutex);
        while (fifo->empty)
        {
            printf ("consumer: Queue EMPTY.\n");
            pthread_cond_wait (fifo->notEmpty, fifo->mutex);
        }
        queueDel (fifo, &d);
        pthread_mutex_unlock (fifo->mutex);

        // 取完資料,發「佇列不滿」信號
        pthread_cond_signal (fifo->notFull);
        printf ("consumer: recieved %d.\n", d);
        SLEEP(200);
    }

    // 與上面類似
    for (int i = 0; i < LOOP; i++)
    {
        pthread_mutex_lock (fifo->mutex);
        while (fifo->empty)
        {
            printf ("consumer: Queue EMPTY.\n");
            pthread_cond_wait (fifo->notEmpty, fifo->mutex);
        }
        queueDel (fifo, &d);
        pthread_mutex_unlock (fifo->mutex);
        pthread_cond_signal (fifo->notFull);
        printf ("consumer: recieved %d.\n", d);
        SLEEP (50);
    }
    return (NULL);
}

Queue *queueInit (void)
{
    Queue *q = (Queue *)malloc (sizeof (Queue));
    if (q == NULL) return (NULL);

    q->empty = true;
    q->full = false;
    q->head = 0;
    q->tail = 0;

    q->mutex = (pthread_mutex_t *) malloc (sizeof (pthread_mutex_t));
    pthread_mutex_init (q->mutex, NULL);
    q->notFull = (pthread_cond_t *) malloc (sizeof (pthread_cond_t));
    pthread_cond_init (q->notFull, NULL);
    q->notEmpty = (pthread_cond_t *) malloc (sizeof (pthread_cond_t));
    pthread_cond_init (q->notEmpty, NULL);

    return (q);
}

void queueDelete (Queue *q)
{
    pthread_mutex_destroy (q->mutex);
    free (q->mutex);

    pthread_cond_destroy (q->notFull);
    free (q->notFull);

    pthread_cond_destroy (q->notEmpty);
    free (q->notEmpty);

    free (q);
}

void queueAdd (Queue *q, int in)
{
    q->buf[q->tail] = in;
    q->tail++;
    if (q->tail == QUEUE_SIZE)     // 循環佇列
        q->tail = 0;

    if (q->tail == q->head)        // 添加資料時「觸頂」
        q->full = true;
    q->empty = false;

    return;
}

void queueDel (Queue *q, int *out)
{
    *out = q->buf[q->head];
    q->head++;
    if (q->head == QUEUE_SIZE)     // 循環佇列
        q->head = 0;

    if (q->head == q->tail)        // 取出資料時「觸底」
        q->empty = true;
    q->full = false;

    return;
}

設計重點

整個佇列採用環形緩衝區(circular buffer)思維,head 與 tail 兩個索引在到頭時歸零,形成首尾相連的邏輯環。生產者與消費者各自用 pthread_mutex_lock 保護臨界區,並以 while 迴圈搭配 pthread_cond_wait 應對「滿」與「空」兩種狀態——用 while 而非 if,是為了防範被喚醒後狀態又改變的偽喚醒(spurious wakeup)情形。任何一方完成操作後,都會用 pthread_cond_signal 通知對方,讓等待中的執行緒得以繼續,這是避免死鎖、維持流暢協作的關鍵。

Copyright © Linux教程網 All Rights Reserved