生产者与消费者

#代码:

#include<stdio.h>
#include<pthread.h>
#define N 20
#define OVER -1
struct strbuff//定义缓冲区结构体
{
    int buffer[N];//缓冲数组,每个数组仅存一个整数,装N个数组,装满就取,取出就装...
    pthread_mutex_t lock;//互斥体lock,用于对数组互斥操作
    int rpos,wpos;//读指针,写指针
    pthread_cond_t nempty;//数组未使用条件变量
    pthread_cond_t nfull;//数组未使用完条件变量
};
void init(struct strbuff *b)//初始化缓冲区结构体
{
    pthread_mutex_init(&b->lock,NULL);//初始化互斥体
    pthread_cond_init(&b->nempty,NULL);//初始化非空条件变量
    pthread_cond_init(&b->nfull,NULL);//初始化未满条件变量
    b->rpos=0;//初始化读指针
    b->wpos=0;//初始化写指针
}
void put(struct strbuff *b,int data)//存入一个整数,向缓冲区
{
    pthread_mutex_lock(&b->lock);//加锁
    if((b->wpos+1)%N==b->rpos)//等待缓冲区未满
        pthread_cond_wait(&b->nfull,&b->lock);
    b->buffer[b->wpos]=data;//写数据
    b->wpos++;//移动位置
    //printf("wpos:%d\n",b->wpos);
    if(b->wpos>=N)//写满,置零
        b->wpos=0;
    /*设置缓冲区非空条件变量*/
    pthread_cond_signal(&b->nempty);
    pthread_mutex_unlock(&b->lock);//解锁
}
int get(struct strbuff *b)//从缓冲区取整数
{
    int data;
    pthread_mutex_lock(&b->lock);
    if(b->wpos==b->rpos)//等待缓冲区装满
        pthread_cond_wait(&b->nempty,&b->lock);
    data=b->buffer[b->rpos];//读数据
    b->rpos++;//移动位置
    if(b->rpos>=N)//读完
        b->rpos=0;//置零
    pthread_cond_signal(&b->nfull);//设置缓冲区未满条件变量
    pthread_mutex_unlock(&b->lock);
    return data;
}

//测试线程1写入0,1,..,19的整数

struct strbuff *buff;
void *producer(void *data)
{
    int n;
    for(n=0;n<20;n++)
    {
        printf("%d--->\n",n);
        put(&buff,n);
    }
    put(buff,OVER);
    return NULL;
}
void *consumer(void *data)
{
    int d;
    while(1)
    {
        d=get(&buff);
        if(d==OVER)
            break;
        printf("--->%d\n",d);
    }
    pthread_exit(NULL);
}
int main()
{
    pthread_t th_a,th_b;
    init(&buff);
    pthread_create(&th_a,NULL,producer,0);
    sleep(3);
    pthread_create(&th_b,NULL,consumer,0);
    pthread_join(th_a,NULL);
   pthread_join(th_b,NULL);
    return 0;
}
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值