直接上代码:
点击(此处)折叠或打开
-
/*
-
生产者消费者模型模拟,循环队列、互斥量条件量维护缓冲池,多线程实现
-
*/
-
#include <stdio.h>
-
#include <pthread.h>
-
#include <stdlib.h>
-
-
#define BUFFERSIZE 100
-
#define OVER (-1)
-
-
/*建立缓冲区,里面包含一个队列,队列包含数据区,两个模拟指针(队头和队尾指针)
-
一个互斥量(mutex),两个条件量用来判断缓冲区的两种状态:full,empty
-
*/
-
typedef struct prodBuffer{
-
int buffer[BUFFERSIZE];//数据区
-
int front;//头指针,拿数据
-
int rear;//尾指针,写数据
-
int count;//计数器
-
pthread_mutex_t mutex;//互斥锁
-
pthread_cond_t nofull;//缓冲区满的条件量
-
pthread_cond_t noempty;//缓冲区空的条件量
-
}prodBuffer;
-
-
//初始化缓冲区
-
void init(prodBuffer *p)
-
{
-
p->front=0;
-
p->rear=0;
-
p->count=0;
-
pthread_mutex_init(&p->mutex,0);
-
pthread_cond_init(&p->nofull,0);
-
pthread_cond_init(&p->noempty,0);
-
}
-
//撤销
-
void destroy(prodBuffer *p)
-
{
-
pthread_mutex_destroy(&p->mutex);
-
pthread_cond_destroy(&p->noempty);
-
pthread_cond_destroy(&p->nofull);
-
}
-
//往缓冲区写数据的函数
-
void put(prodBuffer *p,int data)
-
{
-
//加锁,不能同时对缓冲区操作
-
pthread_mutex_lock(&p->mutex);
-
//缓冲区是否以已满
-
if(p->count==BUFFERSIZE){
-
pthread_cond_wait(&p->nofull,&p->mutex);//缓冲区已满,阻塞等待
-
}
-
//写数据
-
p->buffer[p->rear]=data;
-
//移动队尾指针
-
p->rear=(p->rear+1)%BUFFERSIZE;
-
p->count++;
-
// if(p->count>=BUFFERSIZE)
-
// p->rear=(p->rear+1)%BUFFERSIZE;
-
//做出通知可以读数据,有数据了
-
pthread_cond_signal(&p->noempty);
-
//解锁
-
pthread_mutex_unlock(&p->mutex);
-
-
}
-
-
//往缓冲区读数据的函数
-
int get(prodBuffer *p)
-
{
-
int data;
-
pthread_mutex_lock(&p->mutex);
-
//判断是否缓冲区空
-
if(p->count==0){
-
//等待有数据
-
pthread_cond_wait(&p->noempty,&p->mutex);
-
}
-
//读数据
-
data=p->buffer[p->front];
-
//移动指针
-
p->front=(p->front+1)%BUFFERSIZE;
-
p->count--;
-
// if(p->count>=BUFFERSIZE)
-
// p->front=0;
-
pthread_cond_signal(&p->nofull);
-
pthread_mutex_unlock(&p->mutex);
-
return data;
-
}
-
-
prodBuffer buf;
-
-
//生成者线程模拟
-
void *producter(void *d)
-
{
-
int i;
-
for(i=0;i<1000;i++){
-
put(&buf,i);
-
printf("%d ",i);
-
}
-
printf("\n");
-
// put(&buf,OVER);
-
return NULL;
-
}
-
-
-
//消费者线程模拟
-
void *consumer(void *d)
-
{
-
while(1){
-
int d=get(&buf);
-
printf("%d ",d);
-
}
-
printf("\n");
-
return NULL;
-
}
-
int main()
-
{
-
pthread_t th_a,th_b;
-
init(&buf);
-
pthread_create(&th_a,NULL,producter,0);
-
pthread_create(&th_b,NULL,consumer,0);
-
pthread_join(th_a,(void**)0);
-
pthread_join(th_b,(void**)0);
-
destroy(&buf);
-
return 0;
- }