码迷,mamicode.com
首页 > 其他好文 > 详细

生产者消费者问题

时间:2015-07-30 13:37:50      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:生产者   消费者   c   

#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\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。
    
        

版权声明:本文为博主原创文章,未经博主允许不得转载。

生产者消费者问题

标签:生产者   消费者   c   

原文地址:http://blog.csdn.net/qianligaoshan/article/details/47147539

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!