Producer-consumer problem


//信号量---线程间通信
//“生产者消费者” 问题
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <pthread.h>

const int N = 100;
sem_t empty, full, mutex;
int item_num = 0;

void P(sem_t *s);
void V(sem_t *s);
void produce_item(void);
void consume_item(void);

inline void P(sem_t *s)
{
    sem_wait(s);
}

inline void V(sem_t *s)
{
    sem_post(s);
}

inline void produce_item(void)
{
    sleep(1);
}

inline void consume_item()
{
    sleep(1);
}

int insert_item()
{
    item_num++;
    printf("insert_item: item_num = %d\n", item_num);
    sleep(1);
    return item_num;
}

int remove_item()
{
    item_num--;
    printf("remove_item: item_num = %d\n", item_num);
    sleep(1);
    return item_num;
}

void *producer(void *arg)
{
    if(NULL == arg){} // avoid compiler warnning
    while(1)
    {
        produce_item();
        P(&empty);
        P(&mutex);
        insert_item();
        V(&mutex);
        V(&full);
    }
}

void *consumer(void *arg)
{
    if(NULL == arg){} // avoid compiler warnning
    while(1)
    {
        P(&full);
        P(&mutex);
        remove_item();
        V(&mutex);
        V(&empty);
        consume_item();
    }
}

int main()
{
    pthread_t tid1,tid2;
    sem_init(&empty, 0, N);
    sem_init(&full, 0, 0);
    sem_init(&mutex, 0, 1);

    pthread_create(&tid1,NULL,producer,NULL);
    pthread_create(&tid2,NULL,consumer,NULL);

    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);

    return 0;
}