pv操作 生产者消费者

#include <iostream>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
using namespace std;

#define NUM 5
#define Count 20
#define ProCount 40
sem_t mutex,full;


int  amount=0;
void *Producer(void *arg)
{
    int i=0;
   while(i<ProCount)
    {
        sem_wait(&mutex);
        if (amount>=NUM)
        {
            cout<<"已满"<<endl;
        }
        else
        {
            amount++;
            cout<<"余下:"<<amount<<endl;
            i++;
        }
        sem_post(&full);
    }

}

void *Consumer(void *arg)
{

    int i=0;
    while(i<Count)
    {
        sem_wait(&full);
        if (amount<=0)
        {
            cout<<"为空"<<endl;
        }
        else
        {
            amount--;
            cout<<"余下:"<<amount<<endl;
            i++;
        }
        sem_post(&mutex);
    }
}

int  main(int argc, char const *argv[])
{
    int test=sem_init(&mutex,0,10);
    test+=sem_init(&full,0,0);
    if (test!=0)
    {
        cout<<"sem error"<<endl;
        return -1;
    }

    pthread_t id[3];

    pthread_create(&id[0],NULL,Producer,NULL);
    pthread_create(&id[1],NULL,Consumer,NULL);
    pthread_create(&id[2],NULL,Consumer,NULL);
    pthread_join(id[0],NULL);
    pthread_join(id[1],NULL);
    pthread_join(id[2],NULL);

    sem_destroy(&mutex);
    sem_destroy(&full);
    return 0;
}
原文地址:https://www.cnblogs.com/lanye/p/3382504.html