Monitor monitor structure monitor monitor example

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: may wait in the monitor, allowing another thread to enter. P4() blocked wait() A thread in the monitor may signal a waiting thread, causing it to return from its wait and reenter the monitor. Monitor Monitor structure Monitor Monitor example SharedLock SharedLock: Reader/Writer Lock A reader/write lock or SharedLock is a new kind of “lock” that is similar similar to our old definition: • supports Acquire and Release primitives • guarantees mutual exclusion when a writer is present But: a SharedLock provides better concurrency for readers when no writer is present. OS uses: Unix file semantics class SharedLock { AcquireRead(); /* shared mode */ AcquireWrite(); /* exclusive mode */ ReleaseRead(); ReleaseWrite(); } Reader/Writer Reader/Writer Lock Illustrated Multiple readers may hold the lock concurrently in shared mode. Ar Rr Ar Aw If each thread acquires the lock in in exclusive (*write) mode, SharedLock functions exactly as an ordinary mutex. Rr Rw Writers always hold the lock lock in exclusive mode, and must wait for all readers or writer to exit. Reader/Writer Reader/Writer Lock: First Cut int i; /* # active readers, or -1 if writer */ Lock rwMx; SharedLock::ReleaseWrite() { Condition rwCv; rwMx.Acquire(); SharedLock::AcquireWrite() { rwMx.Acquire(); while (i != 0) rwCv.Wait(&rwMx); i = -1; rwMx.Release(); } SharedLock::AcquireRead() { rwMx.Acquire(); while (i < 0) rwCv.Wait(&rwMx); i += 1; rwMx.Release(); } i = 0; rwCv.Broadcast(&rwMx); rwMx.Release(); } SharedLock::ReleaseRead() { rwMx.Acquire(); i -= 1; if (i == 0) rwCv.Signal(&rwMx); rwMx.Release(); } Reader/Writer Reader/Writer Lock: First Cut int i; /* # active readers, or -1 if writer */ Lock rwMx; SharedLock::ReleaseWrite() { Condition rwCv; rwMx.Acquire(); SharedLock::AcquireWrite() { rwMx.Acquire(); while (i != 0) rwCv.Wait(&rwMx); i = -1; rwMx.Release(); } SharedLock::AcquireRead() { rwMx.Acquire(); while (i < 0) rwCv.Wait(&rwMx); i += 1; rwMx.Release(); } i = 0; rwCv.Broadcast(&rwMx); rwMx.Release(); } SharedLock::ReleaseRead() { rwMx.Acquire(); i -= 1; if (i == 0) rwCv.Signal(&rwMx); rwMx.Release(); } Limitations Limitations of the SharedLock Implementation This implementation has weaknesses • spurious wakeups ReleaseWrite awakens writers as well as readers. Solution: add a separate condition variable for writers. • starvation How can we be sure that a waiting writer will ever pass its acquire if faced with a continuous stream of arr...
View Full Document

This document was uploaded on 04/02/2014.

Ask a homework question - tutors are online