100 likes | 106 Views
CS 241 Section Week #6. Topics This Section. Midterm next Tuesday March 8 th 7:00pm to 9:00pm DCL 1310 and 1320 Semaphore Condition Variable Synchronization problems Bounded Buffer (Producer/Consumer) Semaphore Condition Variable (CV) Reader/Writer Dining Philosopher. 2.
E N D
CS 241 Section Week #6
Topics This Section • Midterm next Tuesday March 8th • 7:00pm to 9:00pm • DCL 1310 and 1320 • Semaphore • Condition Variable • Synchronization problems • Bounded Buffer (Producer/Consumer) • Semaphore • Condition Variable (CV) • Reader/Writer • Dining Philosopher • 2
Two operations: semWait(s), semSignal(s). typedef struct { int count; queue q; } SEMAPHORE Used as a mutex: semaphore s = 1;Pi { while(1) { semWait(s); /* Critical Section */ semSignal(s); /* remainder */ }} Semaphore - Review
void semWait(semaphore s) {s.count--;if (s.count < 0) { place P in s.queue; block P; }} void semSignal(semaphore s) { s.count++; if (s.count ≤ 0) { remove P from s.queue; place P on ready list; }} Semaphore - Review
Three operations: wait, signal and broadcast. Wait: Blocked on this condition variable. Signal: Wake up one of the thread waiting on this condition variable. Broadcast: Wake up all threads waiting on this condition variable. Condition Variable and semaphores are both powerful synchronization primitives. You can use either one, but don't use both of them in your project. Harder to understand and harder to debug. Conditional Variable
void semWait(mutex m, CV c) {mutex_lock(&m);count--;while (count < 0) { // pay attention to the while cond_wait(&c, &m); }mutex_unlock(&m);} void semSignal(mutex m, CV c) { mutex_lock(&m); count++; if (s.count ≤ 0) { cond_signal(&c); } mutex_unlock(&m);} Use CV to implement semaphore
Why use while instead of if? Imagine the following situation: Thread A is woke up, put to scheduler. At this time, thread B enters the system (either newly spawn or woke up because of broadcast), pass through the while condition, and enters the critical section. Thread A resumes execution, but thread B already cause the condition to be false again! Thread A must recheck the condition! Condition Variable
Bounded Buffer - Semaphore • Limited number of slots. • Producer fill in slots one at a time. • Consumer consumes slots one at a time. • Needs to synchronize among multiple producers/consumers as well as between producers and consumers. • Use semaphore to keep track of number of available slots. • Mutex to protect critical section. • 8
Bounded Buffer - CV • You can simulate a semaphore with a counter and CVs. • Multiple CVs and an associated mutex is called a monitor. • If counter becomes negative or exceeds threshold. • Wait on corresponding CVs. • When to wake threads up? • Try it out! • 9 • 9
Reader/Writer • Multiple readers, single writer allowed. • What variables you need to protect by lock in this case? • How to give readers priority? • How about writers? • 10 • 10