采用多线程技术解决生产者/消费者问题

采用多线程技术解决生产者/消费者问题

解决思路:

  1. 实现生产者,消费者的并发进程互斥操作(互斥问题)

解决办法:使用互斥锁,在进行生产,消费时将将互斥锁锁住,防止被抢占线程。

  1. 解决生产者生成上限和消费者消费下限(缓冲区问题)

解决办法:每次生产消费过程,判断缓冲区是否已慢或空;若缓冲区出现满或空的情况,让相应的生产消费进程进入等待状态,等待另一个进程传来的消费生产信号。

代码(C语言版):

#include<stdio.h>
#include<pthread.h>
#define BUFSIZE 10

struct prodcons{
    int buffer[BUFSIZE];
    pthread_mutex_t lock;
    int readpos,writepos;
    pthread_cond_t notempty;
    pthread_cond_t notfull;
};

void init(struct prodcons *b)
{
  pthread_mutex_init(&b->lock,NULL);
  pthread_cond_init(&b->notempty,NULL);
  pthread_cond_init(&b->notfull,NULL);
  b->readpos=0;
  b->writepos=0;
}
void put(struct prodcons *b,int data){
    pthread_mutex_lock(&b->lock);
    if((b->writepos+1)%BUFSIZE==b->readpos)
    {
        pthread_cond_wait(&b->notfull,&b->lock);
    }
    b->buffer[b->writepos]=data;
    b->writepos++;
    if(data!=-1)
    printf("生产了第%d个\n",data);
    if(b->writepos>=BUFSIZE)
    b->writepos=0;
    pthread_cond_signal(&b->notempty);
    pthread_mutex_unlock(&b->lock);
}
int get(struct prodcons *b)
{
    int data;
    pthread_mutex_lock(&b->lock);
    if(b->writepos==b->readpos)
    {
        pthread_cond_wait(&b->notempty,&b->lock);//阻塞时使锁解锁
    }
    data=b->buffer[b->readpos];
    b->readpos++;
    if(data!=-1)
    printf("消费了第%d个\n",data+1);
    if(b->readpos>=BUFSIZE)
    b->readpos=0;
    pthread_cond_signal(&b->notfull);
    pthread_mutex_unlock(&b->lock);
    return data;
}


#define OVER (-1)
struct prodcons buffer;
void *producer(void *data){
    int n;
    for(n=0;n<20;n++)
    {
        put(&buffer,n);
    }
    put(&buffer,OVER);
    return NULL;
}
void *consumer(void *data){
    int d;
    while(1)
    {
        d=get(&buffer);
        if(d==OVER)
        break;
    }
    return NULL;
}


int main(void){
    pthread_t th_a,th_b;
    void *retval;
    init(&buffer);
    pthread_create(&th_a,NULL,producer,0);
    pthread_create(&th_b,NULL,consumer,0);
    pthread_join(th_a,&retval);
    pthread_join(th_b,&retval);
    return 0;

}

效果图:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wizardAEI

喜欢就投喂一下吧O(∩_∩)O

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值