Counter in Java class Counter { private integer count = 0; public void Increment() synchronized { ++count; } public integer GetCount() synchronized { return count; } } void main() { // one process Counter aCounter; while( true ) { // ... Do other things aCounter.Increment(); // ... continue on integer n = aCounter.GetCount(); } } void main() { // another process while( true ) { // ... Do other things aCounter.Increment(); } } 12/28/2018 Crowley OS Chap. 8
Signal in Java class Signal { private int IsSignaled = 0; public void SendSignal() synchronized { IsSignaled = true; notify(); } public void WaitForSignal() synchronized { while(!IsSignaled) wait(); IsSignaled = false; } } 12/28/2018 Crowley OS Chap. 8
Using the Signal in Java void main() { // the Signal Sender // ... Do things up to the signal point aSignal.SendSignal(); // ... continue on } void main() { // the Signal Receiver // ... Do things up to the signal point aSignal.WaitForSignal(); // ... continue on when the signal is receive } 12/28/2018 Crowley OS Chap. 8
Bounded buffer monitor (1 of 2) class BoundedBuffer { private BufferItem * buffer; private integer NumberOfBuffers; private integer next_in, nextout; private integer current_size; private Integer NotEmpty, NotFull; public BoundedBufferType(int size) { buffers = new BufferItem[size]; NumberOfBuffers = size; next_in = 0; next_out = 0; current_size = 0; } 12/28/2018 Crowley OS Chap. 8
Bounded buffer monitor (2 of 2) void Put( BufferItem item ) synchronized { if( current_size == NumberOfBuffers ) NotFull.Wait(); buffer[next_in] = item; next_in = (next_in+1) % NumberOfBuffers; NotEmpty.Notify(); } BufferItem Get( void ) synchronized { if( current_size == 0 ) NotEmpty.Wait(); BufferItem item = buffer[next_out]; next_out = (next_out+1) % NumberOfBuffers; NotFull.Notify(); return item; } } 12/28/2018 Crowley OS Chap. 8
Using a bounded buffer monitor BoundedBuffer aBoundedBuffer; void main() { // the Producer while( true ) { BufferItem item = ProduceItem(); aBoundedBuffer.Put( item ); } } void main() { // the Consumer while( true ) { BufferItem item = aBoundedBuffer.Get(); ConsumeItem( item ); } } 12/28/2018 Crowley OS Chap. 8
Counting semaphore monitor monitor Semaphore { private: int count = 0; condition NotBusy; public: void Signal( void ) { if( ++count > 0 ) signal( NotBusy ); } void Wait( void ) { while( count <= 0 ) wait( NotBusy ); --count; } } 12/28/2018 Crowley OS Chap. 8
Using a semaphore monitor int main() { // one process while( 1 ) { // do other stuff // enter critical section Semaphore.Wait(); // do critical section Semaphore.Signal(); } } int main() { // another process while( 1 ) { // do other stuff // enter critical section Semaphore.Wait(); // do critical section Semaphore.Signal(); } } 12/28/2018 Crowley OS Chap. 8