linux下使用线程实现生产者消费者问题

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#define size_of_buffer 10

sem_t full;//缓冲区内现有的产品数
sem_t empty;//缓冲区内可存有的最大产品数
sem_t mutex;//缓互斥信号灯

int buffer[size_of_buffer];//定义缓冲区
int in = 0;//生产者放入缓冲区指针
int out = 0;//消费者取出产品

void *consumer(){
    int ConsumerID = 0;
    while(1){
        sem_wait(&full);
        sem_wait(&mutex);
        ConsumerID = buffer[out];//取出产品
        out = (out+1)%size_of_buffer;
        sem_post(&mutex);
        sem_post(&empty);
        printf("\tConsumed a consume: %d\n",ConsumerID);

    }
}

void *producer(){
    int ProductID=0;      
    while(1){
        ProductID++;//加1代表生产了一个产品
        sem_wait(&empty);
        sem_wait(&mutex);
        buffer[in] = ProductID;//把产品放入缓冲区
        in = (in+1)%size_of_buffer;//指针循环
        sem_post(&mutex);
        sem_post(&full);
        printf("Producted a product: %d\n",ProductID);
        sleep(1);
    }
}


int main(){

    sem_init(&full,0,0);//初始化信号量
    sem_init(&empty,0,10);
    sem_init(&mutex,0,1);

    pthread_t p1ID;//声明线程id
    pthread_t p2ID;

    pthread_create(&p1ID,0,consumer,0);//穿创建一个线程
    pthread_create(&p2ID,0,producer,0);

    pthread_join(p1ID,NULL);//以阻塞方式等待指定进程结束
    pthread_join(p2ID,NULL);
    return 0;
}

执行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值