/* prodConTaS.c++ Producer-Consumer Problem on shared memory - mutual exclusion using test and set (btsl) $ g++ -Wall prodConTaS.c++ queue1c.o */ #include using namespace std; #include #include #include #include #include #include #include #include "queue1c.h" void producer(queue *); void consumer(queue *); int *countC, *countP; int *lockP; // Global 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); countC = (int *)(qP+1); countP = countC+1; lockP = countP+1; *lockP = 0; // lock initialized to 0 *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); if(dataOK == OK){ qP -> deleteQ() ; cout << "\tConsumed Data " << ++(*countC) << " " << data << "\n" ; } } }