生產者-消費者問題(Linux-C版本實現)

生產者消費者問題(英語:Producer-consumer problem),也稱有限緩衝問題(英語:Bounded-buffer problem),是一個多線程同步問題的經典案例。該問題描述了共享固定大小緩衝區的兩個線程——即所謂的“生產者”和“消費者”——在實際運行時會發生的問題。生產者的主要作用是生成一定量的數據放到緩衝區中,然後重複此過程。與此同時,消費者也在緩衝區消耗這些數據。該問題的關鍵就是要保證生產者不會在緩衝區滿時加入數據,消費者也不會在緩衝區中空時消耗數據。
.
要解決該問題,就必須讓生產者在緩衝區滿時休眠(要麼乾脆就放棄數據),等到下次消費者消耗緩衝區中的數據的時候,生產者才能被喚醒,開始往緩衝區添加數據。同樣,也可以讓消費者在緩衝區空時進入休眠,等到生產者往緩衝區添加數據之後,再喚醒消費者。通常採用進程間通信的方法解決該問題。如果解決方法不夠完善,則容易出現死鎖的情況。出現死鎖時,兩個線程都會陷入休眠,等待對方喚醒自己。該問題也能被推廣到多個生產者和消費者的情形。

代碼實現:(線程版&條件變量&互斥鎖)

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
struct msg {
    struct msg *next;
    int num;
};
struct msg *head; //數據結構使用的時隊列

pthread_cond_t has_product = PTHREAD_COND_INITIALIZER;  //判斷是否有產品
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

void *consumer(void *p)
{
    struct msg *mp;
    for (;;) {
        pthread_mutex_lock(&lock);
        while (head == NULL) {           //頭指針爲空,說明沒有節點,處理有多個消費者的問題
            pthread_cond_wait(&has_product, &lock);
        }
        mp = head;      
        head = mp->next;    			//模擬消費掉一個產品
        pthread_mutex_unlock(&lock);

        printf("-Consume ---> %d\n", mp->num);
        free(mp);
        sleep(rand() % 5);
    }
}
void *producer(void *p)
{
    struct msg *mp;
    while (1) {
        mp = malloc(sizeof(struct msg));
        mp->num = rand() % 1000 + 1;        //模擬生產一個產品
        printf("-Produce ---> %d\n", mp->num);

        pthread_mutex_lock(&lock);
        mp->next = head;  
        head = mp;
        pthread_mutex_unlock(&lock);

        pthread_cond_signal(&has_product);  //將等待在該條件變量上的一個線程喚醒,叫醒阻塞的進程
        sleep(rand() % 5);
    }
}
int main(int argc, char *argv[])
{
    pthread_t pid, cid;
    srand(time(NULL));

    pthread_create(&pid, NULL, producer, NULL);
    pthread_create(&cid, NULL, consumer, NULL);

    pthread_join(pid, NULL);
    pthread_join(cid, NULL);
    return 0;
}					

線程&信號量版本:

/*信號量實現 生產者 消費者問題*/
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
#define NUM 10               
int queue[NUM];                                     //全局數組實現環形隊列
sem_t blank_number, product_number;                 //空閒空間信號量, 產品信號量
void *producer(void *arg)
{
    int i = 0;
    while (1) {
        sem_wait(&blank_number);                    //p操作 生產者將空格子數--,爲0則阻塞等待
        queue[i] = rand() % 1000 + 1;               //生產一個產品
        printf("----Produce---%d\n", queue[i]);        
        sem_post(&product_number);                  //v操作 將產品數++

        i = (i+1) % NUM;                            //藉助下標實現環形
        sleep(rand()%3);
    }
}

void *consumer(void *arg)
{
    int i = 0;

    while (1) {
        sem_wait(&product_number);                  //消費者將產品數--,爲0則阻塞等待
        printf("-Consume---%d\n", queue[i]);
        queue[i] = 0;                               //消費一個產品 
        sem_post(&blank_number);                    //消費掉以後,將空閒空間數++

        i = (i+1) % NUM;
        sleep(rand()%3);
    }
}

int main(int argc, char *argv[])
{
    pthread_t pid, cid;

    sem_init(&blank_number, 0, NUM);                //初始化空閒空間信號量爲10
    sem_init(&product_number, 0, 0);                //產品數爲0

    pthread_create(&pid, NULL, producer, NULL);
    pthread_create(&cid, NULL, consumer, NULL);

    pthread_join(pid, NULL);
    pthread_join(cid, NULL);

    sem_destroy(&blank_number);
    sem_destroy(&product_number);

    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章