生產者消費者是多線程編程中最經典的題目之一。
題目大意:有一個生產者在生產產品,這些產品提供給若干消費者消費。為了讓生產者與消費者能並發執行,在兩者之間設置一個具備多個緩衝區的緩衝池:生產者把產品放入某個緩衝區,消費者則從緩衝區取走產品消費。所有生產者與消費者都以異步方式運行,但必須保持同步——不允許消費者從空的緩衝區取產品,也不允許生產者往已裝滿且尚未被取走的緩衝區投放產品。
// producer_consumer.cpp
//////////////////////////////////////////////////////////////////////
// 有一個生產者在生產產品,這些產品將提供給若干個消費者去消費,為了使生產者和消費者能並發執行,
// 在兩者之間設置一個有多個緩衝區的緩衝池,生產者將它生產的產品放入一個緩衝區中,消費者可以從緩
// 沖區中取走產品進行消費,所有生產者和消費者都是異步方式運行的,但它們必須保持同步,即不允許消
// 費者到一個空的緩衝區中取產品,也不允許生產者向一個已經裝滿產品且尚未被取走的緩衝區中投放產品。
//////////////////////////////////////////////////////////////////////
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
const int BUFFER_LENGTH = 100;
int buffer[BUFFER_LENGTH];
int front = 0, rear = -1; // 緩衝區的前端和尾端
int size = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t empty_cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t full_cond = PTHREAD_COND_INITIALIZER;
bool producer_wait = false;
bool consumer_wait = false;
void *producer(void *arg);
void *consumer(void *arg);
int main(int argc, char **argv)
{
pthread_t producer_id;
pthread_t consumer_id;
pthread_create(&producer_id, NULL, producer, NULL);
pthread_create(&consumer_id, NULL, consumer, NULL);
sleep(1);
return 0;
}
void *producer(void *arg)
{
pthread_detach(pthread_self());
while (true)
{
pthread_mutex_lock(&mutex);
if (size == BUFFER_LENGTH) // 緩衝區已滿則等待;否則添加新產品
{
printf("buffer is full. producer is waiting...\n");
producer_wait = true;
pthread_cond_wait(&full_cond, &mutex);
producer_wait = false;
}
// 往尾端添加一個產品
rear = (rear + 1) % BUFFER_LENGTH;
buffer[rear] = rand() % BUFFER_LENGTH;
printf("producer produces the item %d: %d\n", rear, buffer[rear]);
++size;
if (size == 1) // size 由 0 變 1,說明消費者在等待,給消費者發信號
{
while (true)
{
if (consumer_wait)
{
pthread_cond_signal(&empty_cond);
break;
}
}
}
pthread_mutex_unlock(&mutex);
}
}
void *consumer(void *arg)
{
pthread_detach(pthread_self());
while (true)
{
pthread_mutex_lock(&mutex);
if (size == 0) // 緩衝區已空則等待;否則消費產品
{
printf("buffer is empty. consumer is waiting...\n");
consumer_wait = true;
pthread_cond_wait(&empty_cond, &mutex);
consumer_wait = false;
}
// 從前端消費一個產品
printf("consumer consumes an item%d: %d\n", front, buffer[front]);
front = (front + 1) % BUFFER_LENGTH;
--size;
if (size == BUFFER_LENGTH - 1) // 說明生產者原本在等待,給生產者發信號
{
while (true)
{
if (producer_wait)
{
pthread_cond_signal(&full_cond);
break;
}
}
}
pthread_mutex_unlock(&mutex);
}
}
整個模型是一條環形佇列:front 指向取出的位置,rear 指向放入的位置,兩者都透過取模運算在陣列上循環,因此固定大小的緩衝區可以重複使用。
同步靠兩組條件變量完成:empty_cond 表示「有空格可寫」,full_cond 表示「有產品可讀」。而 producer_wait/consumer_wait 這兩個旗標的作用,是確保 signal 只在對方真的睡著時才發出,避免信號被浪費。
若要把這個模型再推廣,可以改成多生產者多消費者,此時只需把「if 判斷」改為「while 判斷」重新檢查狀態,就能避免多個線程被喚醒後搶同一個資源的問題。