1128

生产者将它生产的产品放入一个缓冲区中,消费者可以从缓冲区中取走产品进行消费,所有生产者和消费者都是异步方式运行的,但它们必须保持同步,即不允许消费者到一个空的缓冲区中取产品,也不允许生产者向一个已经装满产品且尚未被取走的缓冲区中投放产品。


#include <stdio.h>
#include <pthread.h>


#define BUFFER_SIZE 16


struct prodcons
{
    int buffer[BUFFER_SIZE];
    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) % BUFFER_SIZE == b->readpos)
    {
        pthread_cond_wait(&b->notfull,&b->lock);
    }
    b->buffer[b->writepos] = data;
    b->writepos++;
    if(b->writepos >= BUFFER_SIZE)
    {
        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(b->readpos >= BUFFER_SIZE)
    {
        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++)
    {
        printf("%d----->\n",n);
        put(&buffer,n);
    }
    put(&buffer,OVER);
    return NULL;
}


void * consumer(void *data)
{
    int d;
    while(1)
    {
        d = get(&buffer);
        if(d == OVER)
            break;
        printf("----->%d\n",d);
    }
    return NULL;
}


int main()
{
    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;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值