/* prodCon1a.c++ Producer-Consumer Problem on shared memory $ g++ -Wall prodCon1a.c++ queue1a.o */ #include using namespace std; #include #include #include #include #include #include #include #include "queue1a.h" void producer(queue *) ; void consumer(queue *) ; int *countP, *countC; 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; *countC = *countP = 0; 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) ; // Child 2: consumer } else consumer(qP) ; // Child I: producer return 0 ; } void producer(queue *qP){ int added = 1, i ; for(i=1;i<=5000000;++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<= 5000000; ++i) { int data, dataOK; dataOK = qP -> deleteQ(data); if(dataOK == OK) cout << "\tConsumed Data " << ++(*countC) << " " << data << "\n" ; } }