110 likes | 264 Views
Thread Synchronization - Semaphores, Conditional Variable. Tingxin Yan 2/23/2011. TA office hour this week. Wed 4-6 pm. Goal: Review design documents. Ways to synchronize threads. Low-level mechanisms Disable/Enable interrupts C onstraints on preemptions … High-level primitives
E N D
Thread Synchronization- Semaphores, Conditional Variable Tingxin Yan 2/23/2011
TA office hour this week • Wed 4-6 pm. • Goal: • Review design documents.
Ways to synchronize threads • Low-level mechanisms • Disable/Enable interrupts • Constraints on preemptions • … • High-level primitives • Semaphores • Mutexes (Binary Semaphores) • Conditional Variables (CV)
Use Semaphores and CV as examples of OS design/implementation process
Semaphores in Nachos • nachos.threads.Semaphore • Suppose you are asked to implement Semaphores. • What is a semaphore? • What need to be implemented? • P() • V() • What data structures are used? • Integer value; • ThreadQueuewaitQueue;
Implementation of Semaphores(1) • P() • Atomic operations if (value is zero) Put current thread to waitQueue; Current thread goes to sleep; else decrease value by 1
Implementation of Semaphores(2) • V() • Atomic operations If (waitQueue is not empty) wake up the first waiting thread by adding it to the ready queue. else increase value by 1
Test of Semaphores • Ping-pong test. • Create two threads; • Create two semaphores – ping and pong. • Let the status of thread alter between ping and pong. Sequence matters?
Conditional Variables in Nachos • nachos.threads.Condition • nachos.threads.Condition2 (Yours!) • Suppose you are asked to implement CVs. • What is a CV? • What need to be implemented? • Sleep() • Wake()/Wakeall() • What data structures are used? • Lock (an alternative for atomic) • waitQueue of Semaphores. Each thread waiting for CV is synced by a semaphore.
Implementation of CV • Left for you…
Test of CV • ConditionTest.java • Producer-consumer buffer • N producers • M consumers • What CVs are needed? • Buffer empty • Buffer full • Consumer finished