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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章