ppt

Monitors
• A monitor is a higher level construct for synchronizing
multiple threads’ access to a common code segment
– Can implement within an object (Monitor Object Pattern)
– E.g., built with mutexes, condition variables (and threads)
• At most one thread may be active within a monitor
–
–
–
–
I.e., all other threads within the monitor must be suspended
Synchronization is based on a common shared lock
Active thread may (atomically) signal, release lock, suspend
Signaled thread then may (atomically) resume, acquire lock
• Monitors introduce conditional scopes for concurrency
– E.g., a consumer suspends unless a queue is non-empty
– E.g., producers suspend if queue reaches “high-water-mark”,
until queue again reaches “low-water-mark” condition
CSE 425: Concurrency III
Desired Internal Behavior
Queue empty - wait
Queue
CSE 425: Concurrency III
notify
(Passive) Monitor Objects
• “Monitor Object” Pattern Approach
– Methods run in callers’ threads
– Condition variables arbitrate use of a
common shared lock
• E.g., using a std::mutex, a
std::unique_lock (must be able to
unlock and re-lock it) and a
std::condition_variable
Client Proxy List
(Monitor Object)
add()
– Ensures incremental progress while
avoiding race conditions
• Threads wait on condition
• Condition variable performs thread-safe
lock/wait and wake/unlock operations
• Thread released when it can proceed
• E.g., when queue isn’t empty/full
– Blocks caller until request can be
handled, coordinates callers
CSE 425: Concurrency III
Condition
lookup()
Lock
A Few Variations
• Can notify_one() or notify_all()
– If it doesn’t matter which thread, just wake one up
– If all need to see if it’s their turn, wake all of them
• Can limit waiting time
– Use wait_for() to return after a specified interval
– Use wait_until() to return at a specified time
• Can pass a predicate to wait (or wait_*) method(s)
– Won’t return until predicate is satisfied (or call times out)
– Helps to avoid spurious wake cases
CSE 425: Concurrency III
Today’s Studio Exercises
• We’ll code up ideas from Scott Chapter 12.4 to 12.4.3
– Again via C++11 concurrency/synchronization types/features
– Looking at higher-level concurrency/synchronization ideas
like condition variables being used to implement monitors
• Today’s exercises are again in C++
– Please take advantage of the on-line tutorial and reference
manual pages that are linked on the course web site
– The provided Makefile also may be helpful
– As always, please ask us for help as needed
• When done send email with your answers to the
[email protected] account with subject line
“Concurrency Studio III”
CSE 425: Concurrency III