生产消费1

#include "stdio.h"
#include "string.h"
#include <iostream>
#include <pthread.h>
 
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
 
class Product
{
private:
    int  mId;
public:
    Product( int id ):mId(id){}
Product( ):mId(-1){};
    //Product( const Product &p){mId = p.mId;}
    int GetId( ){return mId;}
};
 
class ProductPool
{
private:
    int mCount;
int mPoint;
Product *maProductQueue;
public:
    ProductPool(int iCount):mPoint(0),mCount(iCount)
{
   maProductQueue = new Product[iCount];
}
~ProductPool()
{
   delete maProductQueue;
}
bool IsFull(){return mPoint == mCount? true:false;}
bool IsEmpty(){return mPoint == 0?true:false;}
bool putProduct()
{
   //sleep(1);
   if ( IsFull() )
{
   std::cout<<"Is Full!!!"<<std::endl;
return false;
}
std::cout<<"Produce a product:id = "<<mPoint<<std::endl;
maProductQueue[mPoint++] = Product(mPoint);
   return true;
}
Product* getProduct()
{
        //sleep(1);
   if ( IsEmpty() )
{
   std::cout<<"Is Empty!!!"<<std::endl;
return NULL;
}
        std::cout<<"Consume a product:id = "<<mPoint-1<<std::endl;
return &maProductQueue[--mPoint];
}    
};
 
 
 
class Producer
{
private:
    int mId;
ProductPool *mProductPool;
public:
    Producer( int id ,ProductPool *rProductPool):mId(id),mProductPool(rProductPool){};
void Produce( )
{
   while( true )
{
   pthread_mutex_lock(&mutex);
std::cout<<"I am producer,id = "<<mId<<",I produce a product"<<std::endl;
mProductPool->putProduct();
pthread_mutex_unlock(&mutex);
 
   }
}
static void* ProduceThreadProc( void *rThis)
{
        Producer *p = (Producer*)rThis;
p->Produce();
}
};
 
 
class Consumer
{
private:
    int mId;
    ProductPool *mProductPool;
public:
    Consumer(int id,ProductPool *rProductPool):mId(id),mProductPool(rProductPool){};
void Consume()
{
   while( true )
{
   pthread_mutex_lock(&mutex);
std::cout<<"I am consumer,id = "<<mId<<",I consume a product"<<std::endl;
mProductPool->getProduct();
pthread_mutex_unlock(&mutex);
   }
}
static void* ConsumeThreadProc(void *rThis)
{
        Consumer *p = (Consumer*)rThis;
p->Consume();
}
};
int main()
{
pthread_t tids[2];
ProductPool aProductPool(10);
Producer *aP = new Producer(1,&aProductPool);
Consumer *aC = new Consumer(2,&aProductPool);
    pthread_create(&tids[0],NULL,Producer::ProduceThreadProc,(void*)aP);
    pthread_create(&tids[1],NULL,Consumer::ConsumeThreadProc,(void*)aC);
pthread_join(tids[0],NULL);
pthread_join(tids[1],NULL);
    return 0;
}
posted @ 2016-05-26 09:11  bshaozi  阅读(93)  评论(0编辑  收藏  举报