/* prodConPeterson.c++ Producer-Consumer Problem with Peterson's algorithm $ g++ -Wall prodConPeterson.c++ queue1b.o */ #include using namespace std; #include #include #include #include #include #include #include #include "queue1b.h" void producer(queue *); void consumer(queue *); int *countC, *countP; int *turnP; // Peterson var bool *c0P, *c1P; // Peterson vars 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; turnP = countC+1; // Peterson c0P = (bool *)(turnP+1); // variables c1P = c0P+1; // in shared memory *c0P = *c1P = false; // false *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 consumer(qP); // Child 2: consumer } else producer(qP); // Child I: producer return 0 ; } void producer(queue *qP){ int added = 1, i ; for(i=1;i<=1000000;++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<= 1000000; ++i) { int data, dataOK; dataOK = qP -> frontQ(data); // qP -> deleteQ(); if(dataOK == OK){ qP -> deleteQ() ; cout << "\tConsumed Data " << ++(*countC) << " " << data << "\n" ; } } }