/* * prodCon1.c++ Producer-Consumer Problem on * shared memory * $ g++ -Wall prodCon1.c++ queue.o */ #include using namespace std; #include #include #include #include #include #include #include #include "queue.h" void producer(queue *); void consumer(queue *); int *countP, *countC; // global counters int main() { int shmID, chID1, chID2, status ; struct shmid_ds buff ; queue *qP ; shmID = shmget(IPC_PRIVATE, sizeof(queue), IPC_CREAT | 0777); if(shmID == -1) { perror("Error in shmget\n") ; exit(1) ; } qP = (queue *) shmat(shmID, 0, 0777); countP = (int *)(qP+1); countC = countP+1; *countP = *countC = 0; // counter init if((chID1 = fork()) != 0) { // Parent if((chID2 = fork()) != 0) { // Parent now waitpid(chID1, &status, 0); waitpid(chID2, &status, 0); cout << *countP << " data produced\n"; cout << *countC << " data consumed\n"; shmdt(qP) ; shmctl(shmID, IPC_RMID, &buff); } else producer(qP); // consumer(qP) ; // Child 2: producer } else consumer(qP); // producer(qP) ; // Child I: consumer return 0 ; } 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); qP -> deleteQ(); // where to put this code if(dataOK == OK){ // qP -> deleteQ() ; cout << "\tConsumed Data " << ++(*countC) << " " << data << "\n" ; } } }