5.4.1 Concept of Monitors(7/10) Condition variable: is a queue of threads waiting for something inside a critical section Q Queues associated with x, y conditions Shared data Entry queue procedures
5.4.1 Concept of Monitors(7/10) • Condition variable: is a queue of threads waiting for something inside a critical section. 12
5.4.1 Concept of Monitors(8/10) Condition variables support three operations 1. Wait(Lock lock, Condition c): atomic (release lock go to sleep), when the process wakes up it re- acquires lock 2. Signal( Condition c): wake up waiting thread, if one exists. Otherwise, it does nothing 3. Broadcast(: wake up all waiting threads Rule: thread must hold the lock when doing condition variable operations
5.4.1 Concept of Monitors(8/10) • Condition variables support three operations: • 1. Wait(Lock lock,Condition c): atomic (release lock, go to sleep), when the process wakes up it reacquires lock. • 2. Signal(Condition c): wake up waiting thread, if one exists. Otherwise, it does nothing. • 3. Broadcast(): wake up all waiting threads • Rule: thread must hold the lock when doing condition variable operations. 13
5.4.1 Concept of Monitors(9/10) Implementation of Condition Class Condition I int numWaiting =0 WaitQueue q Condition: Wait(lock)t Condition Signalo t numWaiting++ if((numWaiting >0) Add this thread t to g Remove a thread t from q release(lock) wakeup(t); / need mutex schedule(; /need mutex numWaiting-- require(lock)
5.4.1 Concept of Monitors(9/10) • Implementation of Condition 14 Class Condition { int numWaiting = 0; WaitQueue q; } Condition::Wait(lock) { numWaiting++; Add this thread t to q; release(lock); schedule(); // need mutex require(lock); } Condition::Signal() { if ((numWaiting > 0) { Remove a thread t from q; wakeup(t); //need mutex numWaiting--; } }
5.4.1 Concept of Monitors(10/ 10) a monitor is similar to a class that ties the data, operations, and in particular, the synchronization operations all together Unlike classes monitors guarantee mutual exclusion, i. e. only one thread may execute a given monitor method at a time monitors require all data to be private 15
5.4.1 Concept of Monitors(10/10) • A monitor is similar to a class that ties the data, operations, and in particular, the synchronization operations all together. • Unlike classes, • monitors guarantee mutual exclusion, i.e., only one thread may execute a given monitor method at a time. • monitors require all data to be private. 15
5.4 Monitors 5.4.1 Concept of monitors 5.4.2 Producer-Consumer with monitors
5.4 Monitors • 5.4.1 Concept of Monitors • 5.4.2 Producer-Consumer with Monitors 16