/* * prodConPth1.c++ Producer-Consumer Problem on * pthread * $ g++ -Wall prodCon1.c++ queuePth1.o -lpthread */ #include using namespace std; #include #include #include "queuePth1.h" void *thread1(void *); void *thread2(void *); void producer(queue *); void consumer(queue *); int countP = 0, countC = 0; int main(int count, char *vect[]) { pthread_t thID1, thID2; // thread ID queue *qP; qP = new queue; pthread_create(&thID1, NULL, thread1, (void *) qP); pthread_create(&thID2, NULL, thread2, (void *) qP); pthread_join(thID1, NULL); pthread_join(thID2, NULL); cout << countP << " data produced\n"; cout << countC << " data consumed\n"; return 0; } void *thread1(void *p){ queue *qP = (queue *)p; producer(qP); pthread_exit(NULL); } void * thread2(void *p){ queue *qP = (queue *)p; consumer(qP); pthread_exit(NULL); } void producer(queue *qP){ int added = 1, i ; for(i=1;i<=500000;++i) { int data, err; if(added) { data = rand() ; added = 0 ; } err = qP->addQ(data) ; if(err == OK) { added = 1 ; cout << "Produced Data " << ++countP << " " << data << "\n" ; } } } void consumer(queue *qP) { int i ; for(i=1; i<= 500000; ++i) { int data, dataOK; dataOK = qP -> frontQ(data); if(dataOK == OK){ qP -> deleteQ() ; cout << "\tConsumed Data " << ++countC << " " << data << "\n" ; } } }