一个生产者生产产品,多个消费者同时获得产品

#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
 
using namespace std;
 
struct{
    pthread_rwlock_t rwlock;
    int product;
}sharedData = {PTHREAD_RWLOCK_INITIALIZER, 0};
 
sem_t bin_sem1;
sem_t bin_sem2;
sem_t bin_sem3;


void * produce(void *ptr)
{
    for (int i = 0; i < 20; ++i)
    {
        pthread_rwlock_wrlock(&sharedData.rwlock);
        sharedData.product = i;
        pthread_rwlock_unlock(&sharedData.rwlock);
     sem_post(&bin_sem1);
     sem_post(&bin_sem2);
     sem_post(&bin_sem3);
        sleep(1);
    }
}
 
void * consume1(void *ptr)
{
    while(1)
    {
    sem_wait(&bin_sem1);
        pthread_rwlock_rdlock(&sharedData.rwlock);
        cout<<"consume1:"<<sharedData.product<<endl;
        pthread_rwlock_unlock(&sharedData.rwlock);
    }
}
 
void * consume2(void *ptr)
{
    while(1)
    {
    sem_wait(&bin_sem2);
        pthread_rwlock_rdlock(&sharedData.rwlock);
        cout<<"consume2:"<<sharedData.product<<endl;
        pthread_rwlock_unlock(&sharedData.rwlock);
    }
}
 
void * consume3(void *ptr)
{
    while(1)
    {
    sem_wait(&bin_sem3);
        pthread_rwlock_rdlock(&sharedData.rwlock);
        cout<<"consume3:"<<sharedData.product<<endl;
        pthread_rwlock_unlock(&sharedData.rwlock);
   }
}

int main()
{
    pthread_t tid1, tid2, tid3,tid4;
     
    sem_init(&bin_sem1,0,5);
    sem_init(&bin_sem2,0,5);
    sem_init(&bin_sem3,0,5);
    pthread_create(&tid1, NULL, produce, NULL);
    pthread_create(&tid2, NULL, consume1, NULL);
    pthread_create(&tid3, NULL, consume2, NULL);
    pthread_create(&tid4, NULL, consume3, NULL);
 
    void *retVal;
 
    pthread_join(tid1, &retVal);
    pthread_join(tid2, &retVal);
    pthread_join(tid3, &retVal);
    pthread_join(tid4, &retVal);
 
    sem_destroy(&bin_sem1);
    sem_destroy(&bin_sem2);
    sem_destroy(&bin_sem3);
    
    return 0;
}

 

猜你喜欢

转载自blog.csdn.net/yinhua405/article/details/82116278
今日推荐