生产者消费者问题

#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
#include <string.h>
#include <stdlib.h>

#define BUFF_SIZE 10
char 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
", 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] = '';
        printf("consumer: buffer: %s  count: %d
", 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("
 Error creating thread 1
");
        exit(1);
    }

    if (pthread_create(&ctid, NULL, consumer, NULL))
    {
        printf("
 Error creating thread 1
");
        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。

原文地址:https://www.cnblogs.com/slgkaifa/p/7374406.html