linux生產者,消費者問題

   pthread_cond_wait() :用於阻塞當前線程,等待別的線程使用pthread_cond_signal()或pthread_cond_broadcast來喚醒它。 pthread_cond_wait() 必須與pthread_mutex 配套使用。pthread_cond_wait()函數一進入wait狀態就會自動release mutex。當其他線程通過pthread_cond_signal()或pthread_cond_broadcast,把該線程喚醒,使pthread_cond_wait()通過(返回)時,該線程又自動獲得該mutex。


  pthread_cond_signal():函數的作用是發送一個信號給另外一個正在處於阻塞等待狀態的線程,使其脫離阻塞狀態,繼續執行.如果沒有線程處在阻塞等待狀態,pthread_cond_signal也會成功返回。

  
#include <stdio.h>
#include <pthread.h>
#define MAX 10 //需要生產的數量
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int buffer = 0;//生產者、消費者使用的緩衝區

void *producer(void *ptr)
{
    int i;
    for(i=1; i<=MAX; i++)
    {
        pthread_mutex_lock(&the_mutex); //互斥使用緩衝區
        while(buffer !=0) pthread_cond_wait(&condp, &the_mutex);
        printf("procucer produce item %d\n",i);
        buffer = i; //將數據插入緩衝區
        pthread_cond_signal(&condc);//喚醒消費者
        pthread_mutex_unlock(&the_mutex);//釋放緩衝區
    }
    
    pthread_exit(0);

}

void *consumer(void *ptr)
{

    int i;
    for(i=1; i<=MAX; i++)
    {
        pthread_mutex_lock(&the_mutex);//互斥使用緩衝區
        while(buffer ==0) pthread_cond_wait(&condc, &the_mutex);
        printf("consumer consume item %d\n",i);
        buffer = 0;//從緩衝區中取出數據
        pthread_cond_signal(&condp);//喚醒生產者
        pthread_mutex_unlock(&the_mutex);//釋放緩衝區
    }
    pthread_exit(0);

}

int main(int argc, char *argv[])
{
    pthread_t pro, con;
    pthread_mutex_init(&the_mutex, 0);
    pthread_cond_init(&condc,0);
    pthread_cond_init(&condp,0);
    pthread_create(&con, 0, consumer, 0);
    pthread_create(&pro, 0, producer, 0);
    pthread_join(pro,0);
    pthread_join(con,0);
    pthread_cond_destroy(&condc);
    pthread_cond_destroy(&condp);
    pthread_mutex_destroy(&the_mutex);
    return 0;    
}

gcc -o consumer-producer -lpthread consumer-producer.c

運行結果:
 
發佈了87 篇原創文章 · 獲贊 28 · 訪問量 23萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章