pthread 实现生产者消费者问题

经典的生产者消费者问题,在这里用信号量和互斥量来实现生产和消费者模型
 
#include<cstdlib>
#include<cstdio>
#include<unistd.h>
#include<pthread.h>
#include<semaphore.h>
int t = 0;
sem_t empty,full;
pthread_mutex_t mutex;
void*  producer(void* arg){
    int* time=(int*) arg;
    while(true){
        sem_wait(&empty);
        pthread_mutex_lock(&mutex);
        //add
        t++;
        printf("producer add 1 to %d\n", t);
        pthread_mutex_unlock(&mutex);
        sem_post(&full);
        sleep(*time);
    }
}
 
void* customer(void* arg){
 
    while(true){
        sem_wait(&full);
        pthread_mutex_lock(&mutex);
        //delete
        t--;
        printf("customer delete 1 to %d\n", t);
        pthread_mutex_unlock(&mutex);
        sem_post(&empty);
        sleep(4);
    }
}
 
int main(){
    pthread_t pthread_producer,pthread_producer_2;
    pthread_t pthread_customer;
    pthread_mutex_init(&mutex,NULL);
    sem_init(&full,0,0);
    sem_init(&empty,0,10);
    int a = 2;
    int b = 3;
    pthread_create(&pthread_producer,NULL,producer,&a);
    pthread_create(&pthread_producer_2,NULL,producer,&b);
    pthread_create(&pthread_customer,NULL,customer,NULL);
    pthread_join(pthread_customer,NULL);
    pthread_join(pthread_producer,NULL);
    pthread_join(pthread_producer_2,NULL);
    return 0;
}
 
 

  

转载于:https://www.cnblogs.com/clyskyblue/p/3572405.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值