24 - Concurrency II (2)OutlineRecapMonitorsAnnouncementsReading:Other Concurrency PrimitivesMonitorsWhat we've covered so far:A monitor is a synchronization primitive provided(whole or in-part) by the programming language.Essentially a special package/module/classReaders-Writers Problem1)3)2)MOS 2.4.4 - 2.4.7Midterms and PA 3 will be graded this weekWe'll do midterm review after grades releasedPA 4 instructions releasedApproachesRace ConditionsCritical SectionsInterrupt DisableLock VariablesStrict AlternationPeterson's SolutionBusy-Waiting SolutionsSleeping SolutionsSleep & WakeupSemaphoresMutexesMonitors----Shared instance variables/fieldsCondition VariablesCompiler keeps a hidden mutex lock that allmonitor procedures must acquire before executing.Condition variables are used to manage sleepingprocesses.Calling process mustbe holding therelevant mutex beforedoing conditionvariable operations.Processes invokescheduler onwait/signal.Mutually exclusive functions/procedures/methodsSingle process/threadallowed to call monitorproceduresMonitor variables arealways privateAll critical sectionsencapsulated in monitorproceduresReduce complexity of writing correct solutionsby localizing related critical sections and sharedvariablesCompiler implements mutual exclusion for criticalsections>>>monitor example integer i condition c procedure producer() ... end procedure consumer() ... endend monitorOperations:(like down)(like up)wait(cond)signal(cond)-----add process to condition's wait queueprocess releases monitor mutex and blocksmove to ready queue when woken upwake up a blocked process from the queuecurrent process yields (release monitor mutex)also see wikipedia: Monitors (synchronization)Blocking Condition VariablesMonitor with Condition VariablesNote the differences:Programmer is responsible for identifying conditionvariables.Alas, they aren't perfect for all situations.Consider a situation where we have many readerand writer processes sharing a data structure.Using mutual exclusion with monitors, only oneprocess can access the structure at a time.Finding a solution that allows multiple simultaneousreaders while ensuring mutually exclusive writers iscalled the Readers-Writers problem.Then, there are 3 variants to consider:Readers do not modify the structure, sosimultaneous read-only access does not causerace conditions.We can get performance improvements by observing:Writers modify data, so no other reader orwriter may run when a process has write access.reader processes only read from the structureaccessing the structure becomes a bottleneckand limits performancewriter processes modify the structureUsing monitors where applicable makes concurrentcode easier to reason about.Instead of 2 semaphores tracking buffer state,only need to maintain count variable, usecondition variable to signal on conditions.No mutex on the buffer, since the monitorguarantees mutual exclusion.Same pseudocode will extend to arbitrarynumber of producers and consumers.monitor ProdCons condition full, empty integer count buffer buf procedure insert(item) if count == N then wait(full) buf.insert(item) count = count + 1 if count == 1 then signal(empty) end procedure remove() if count == 0 then wait(empty) item = buf.remove() count = count - 1 if count == N - 1 then signal(full) return item endend monitorprocedure producerbegin while true do item = produce_item() ProdCons.insert(item) endendprocedure consumerbegin while true do item = ProdCons.remove() consume(item) endend---Java Example:Readers-Writers ProblemOther Concurrency PrimitivesMultiple Reader, Single Writer (MRSW) Locks-----Main Constraint:Reader's PreferenceReader's Preference SolutionWriter's Preference SolutionNo StarvationWriter's PreferenceNo StarvationNo thread may access a sharedresource if another thread iswriting to it.No reader shall be kept waiting if the shareddata is currently open for reading.Many readers can read at once, but writersare potentially starved.Many readers can read at once, but only ifthere are no writers.Writers have priority, and readers can starve.Many potential solutions that optimize differently.Solutions to readers-writers problem have beenimplemented as "Read-Write Locks"bound number of readers served when a writeris presentuse a priority queueconditionally switch between reader's preferenceand writer's preferenceother ideas?No writer shall be kept waiting longer thanabsolutely necessary.No reader or writer shall be allowed to starve.1.2.3.Courtois, Heymans, and Parnas. "Concurrent control with "readers" and "writers"." 1971w1critical sectioncritical sectionw3w3w2w2r8r8r7r7r6r6r5r5----Linux implements these asLinux also has a number of other types of locks:Acquired differently for readers and writers:rwlock_tread_lockread_trylockread_unlockwrite_lockwrite_trylockwrite_unlock--------Sleeping locksFutex (Fast Userspace Mutex)Read-copy-update (RCU)Synchronization BarrierLockless algorithmsMessage passing(different from Memory Barrier)CPU local locks (single core only)Spinlockssee kernel.org on "locking"