生产者消费者问题

来源:互联网 发布:b2c站内优化和站外优化 编辑:程序博客网 时间:2024/06/08 00:57
#include <pthread.h>#include <stdio.h>#include <semaphore.h>#include <string.h>#include <stdlib.h>#define BUFF_SIZE 10char buffer[BUFF_SIZE];char count = 0; //缓冲池里的信息数目sem_t sem_mutex; //生产者和消费者的互斥锁sem_t p_sem_mutex; //空的时候,对消费者不可进sem_t c_sem_mutex; //满的时候,对生产者不可进/* * @brief 步骤,用sem_mutex锁住count,判断count的大小,是否可以继续放数据,如果count = 10则锁住p_sem_mutex *        如果count < 10则释放p_sem_mutex锁 */void* produce(){    while (1)    {        sem_wait(&sem_mutex); //等待缓冲池空闲        if (count == BUFF_SIZE)        {            sem_post(&c_sem_mutex);            sem_post(&sem_mutex);            continue;        }        sem_wait(&p_sem_mutex); //当缓冲池未满        buffer[count] = 'A';        printf("produce: buffer: %s  count: %d\n", buffer, count);        fflush(stdout);        count++;        if (count < BUFF_SIZE) //缓冲池未满        {            sem_post(&p_sem_mutex);        }        if (count > 0) //缓冲池未空        {            sem_post(&c_sem_mutex);        }        sem_post(&sem_mutex);        //sleep(1);    }}void* consumer(){    while (1)    {        sem_wait(&sem_mutex);        if (count == 0)        {            sem_post(&p_sem_mutex);            sem_post(&sem_mutex);            continue;        }        sem_wait(&c_sem_mutex);<pre name="code" class="cpp">  buffer[count] = '\0';        printf("consumer: buffer: %s  count: %d\n", buffer, count);        fflush(stdout);        count--;        if (count > 0)        {            sem_post(&c_sem_mutex);        }        /*        if (count == BUFF_SIZE - 1)        {            sem_post(&p_sem_mutex);        }        */        /*         * 这里差一个判断,如果p_sem_mutex锁住了,则解锁         */        sem_post(&sem_mutex);    }}int main(void){    pthread_t ptid, ctid;    memset(buffer, 0, BUFF_SIZE);    //initialize the semaphores    sem_init(&sem_mutex, 0, 1);    sem_init(&p_sem_mutex, 0, 1);    sem_init(&c_sem_mutex, 0, 0);    //create producer and consumer threads    if (pthread_create(&ptid, NULL, produce, NULL))    {        printf("\n Error creating thread 1\n");        exit(1);    }    if (pthread_create(&ctid, NULL, consumer, NULL))    {        printf("\n Error creating thread 1\n");        exit(1);    }    //wait for the producer to finish    pthread_join(ptid, NULL);    pthread_join(ctid, NULL);    sem_destroy(&p_sem_mutex);    sem_destroy(&c_sem_mutex);    //exit the main thread    pthread_exit(NULL);    return 0;}

该程序使用的posix的信号量机制,而不是System V。                                             
0 0