生产消费2
#include "stdio.h"
#include "string.h"
#include <iostream>
#include <pthread.h>
#include <vector>
#include <assert.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;
std::vector<Product *> mvProductQueue;
public:
ProductPool(int iCount):mCount(iCount)
{
mvProductQueue.reserve(iCount);
}
~ProductPool()
{
//delete mvProductQueue;
}
bool IsFull(){return mvProductQueue.size() == mCount?true:false;}
bool IsEmpty(){return mvProductQueue.empty();}
bool putProduct(Product *p)
{
if ( IsFull() )
{
std::cout<<"Is Full!!!"<<std::endl;
return false;
}
std::cout<<"Produce a product:id = \n";//<<mPoint<<std::endl;
mvProductQueue.push_back(p);
return true;
}
Product* getProduct()
{
if ( IsEmpty() )
{
std::cout<<"Is Empty!!!"<<std::endl;
return NULL;
}
std::cout<<"Consume a product:id = \n";//<<mPoint-1<<std::endl;
Product *pRet = mvProductQueue.back();
assert(pRet!=NULL);
mvProductQueue.pop_back();
return pRet;
}
};
class Producer
{
private:
int mId;
ProductPool *mProductPool;
public:
Producer( int id ,ProductPool *rProductPool):mId(id),mProductPool(rProductPool){};
void Produce( )
{
while( true )
{
sleep(1);
pthread_mutex_lock(&mutex);
Product *pP = new Product(1);
if (mProductPool->putProduct(pP))
{
std::cout<<"I am producer,id = "<<mId<<",I produce a product"<<std::endl;
}
else
{
std::cout<<"I can;t put a product.....\n";
delete pP;
}
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 )
{
sleep(3);
pthread_mutex_lock(&mutex);
Product *pP = mProductPool->getProduct();
if( pP == NULL) {std::cout<<"Warnning:I am not get a product....!!!!\n";}
else { std::cout<<"I am consumer,id = "<<mId<<",I consume a product"<<std::endl;delete pP;}
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;
}