UNIVERSITY OF WISCONSIN-MADISON
Computer Sciences Department | ||
CS 537
Fall 2007 | A. Arpaci-Dusseau | |
Sample Quiz #4 -- Critical Sections and Condition Variables |
volatile int northbound; volatile int southbound; cv_t busy; // A condition variable lock_t lock; // A lock -- initialized to unlock'ed! northboundCarArrival() { /* A car wants to enter the tunnel going northbound */ lock_acquire(&lock); while (southbound > 0) cv_wait(&busy, &lock); northbound++; lock_release(&lock); } southboundCarArrival() { /* A car wants to enter the tunnel going southbound */ lock_acquire(&lock); while (northbound > 0) cv_wait(&busy, &lock); southbound++; lock_release(&lock); } northboundCarDeparture(){ /* A northbound car is exiting the tunnel */ lock_acquire(&lock); northbound--; // cv_broadcast signals ALL threads waiting on the busy cv if (northbound == 0) cv_broadcast(&busy); lock_release(&lock); } southboundCarDeparture(){ /* A southbound car is exiting the tunnel */ lock_acquire(&lock); southbound--; // cv_broadcast signals ALL threads waiting on the busy cv if (sounthbound == 0) cv_broadcast(&busy); lock_release(&lock); } |
You should assume that locks and condition variables have been implemented in a reasonable way with Mesa semantics.