apue.h是自己定义的头文件
里面包含
#include
#include <pthread.h>
#incldue
#include "apue.h"
#define BUFFER_SIZE 5
#define PRODUCT_CNT 30
using namespace std;
struct product_cons
{
int buffer[BUFFER_SIZE];
pthread_mutex_t lock; //互斥锁
int readposition;
int writeposition;//读写位置
pthread_cond_t notempty; //条件变量 非空
pthread_cond_t notfull; //条件变量 非满
}buffer;
void init(struct product_cons *p)
{
pthread_mutex_init(&p->lock,NULL);
pthread_cond_init(&p->notempty,NULL);
pthread_cond_init(&p->notfull,NULL);
p->readposition = 0 ;
p->writeposition = 0 ;
}
void finish(struct product_cons *p)
{
pthread_mutex_destroy(&p->lock);
pthread_cond_destroy(&p->notempty);
pthread_cond_destroy(&p->notfull);
p->readposition = 0 ;
p->writeposition = 0 ;
}
void put(struct product_cons *p,int data)
{
pthread_mutex_lock(&p->lock);
if(p->writeposition + 1 == p->readposition||p->writeposition - 4 == p->readposition)
{
cout << "producer wait for notfull" << endl;
pthread_cond_wait(&p->notfull,&p->lock);
}
p->buffer[p->writeposition]=data;
p->writeposition ++;
if(p->writeposition >= BUFFER_SIZE)
{
p->writeposition = 0 ;
}
pthread_cond_signal(&p->notempty);
pthread_mutex_unlock(&p->lock);
}
int get(struct product_cons *p)
{
int data;
pthread_mutex_lock(&p->lock);
if(p->readposition == p->writeposition)
{
cout << "consumer wait for notempty" << endl;
pthread_cond_wait(&p->notempty,&p->lock);
}
data = p->buffer[p->readposition];
p->readposition++;
if(p->readposition >= BUFFER_SIZE)
{
p->readposition = 0;
}
pthread_cond_signal(&p->notfull);
pthread_mutex_unlock(&p->lock);
return data;
}
void*producer(void*data)
{
for(int n = 1 ; n < 20 ; n ++ )
{
sleep(1);
cout << "put the" << " " << n <<" " << "product..." << endl;
put(&buffer,n);
cout << "finished put" << endl;
}
cout <<"the 20 producers has been producted successfully" << endl;
return NULL;
}
void*consumer(void*data)
{
int NeedNum = 0;
while(1)
{
sleep(2);
cout << "get product..."<< endl;
int num = get(&buffer);
cout <<"succeeded get the "<<" "<< num << "product"<< endl;
if(++NeedNum == PRODUCT_CNT)
{
break;
}
}
cout << "the 20 producers has been get successfully" << endl;
return NULL;
}
int main()
{
pthread_t tha,thb;
void*retval;
int err ;
init(&buffer);
pthread_create(&tha,NULL,producer,0);
pthread_create(&thb,NULL,consumer,0);
pthread_join(tha,&retval);
pthread_join(thb,&retval);
finish(&buffer);
return 0;
}