//------------------------------------------------------------------------ // Filename: // ProducerConsumer.cpp // PROGRAM DESCRIPTION // Class implementation file for producer and consumer thread class. // This program uses Hoare style monitor. //------------------------------------------------------------------------ #include #include "ThreadClass.h" #include "ProducerConsumer-mon.h" //------------------------------------------------------------------------ // BufferMonitor::BufferMonitor() // constructor //------------------------------------------------------------------------ BufferMonitor::BufferMonitor(char* Name) :Monitor(Name, HOARE), NotFull("Notfull"), NotEmpty("NotEmpty") { NumberOfItems = 0; // no data items yet In = Out = 0 ; }; //------------------------------------------------------------------------ // BufferMonitor::Put(Item_t item) // Add 'item' into the buffer //------------------------------------------------------------------------ void BufferMonitor::Put(Item_t item) { MonitorBegin(); if (NumberOfItems == BUFFER_SIZE) // buffer is full NotFull.Wait(); Buffer[In] = item; // add item into the buffer In = (In + 1) % BUFFER_SIZE; // advance input pointer NumberOfItems++; // have one more item NotEmpty.Signal(); // release a waiting consumers MonitorEnd(); } //------------------------------------------------------------------------ // BufferMonitor::Get(Item_t *item) // Retrieve an item from the buffer //------------------------------------------------------------------------ void BufferMonitor::Get(Item_t *item) { MonitorBegin(); if (NumberOfItems == 0) // buffer is empty NotEmpty.Wait(); *item = Buffer[Out]; // retrieve data Out = (Out + 1) % BUFFER_SIZE; // advance out pointer NumberOfItems--; // have one less item NotFull.Signal(); // release a waiting producer MonitorEnd(); } // end of ProducerConsumer-mon.cpp