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

#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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值