UNIVERSITY OF WISCONSIN-MADISON
Computer Sciences Department
CS 537
Fall 2007
A. Arpaci-Dusseau
Sample Quiz #4 -- Critical Sections and Condition Variables

Protecting Critical Sections

Monitors and Condition Variables

When a thread calls cv_wait(), what is the complete sequence of operations that must occur before the routine can return?

Classic Synchronization Problems: Traffic

The following code synchronizes traffic through a one-lane north-south tunnel, ensuring that only cars in one direction can proceed through the tunnel while the cars in the other direction must wait outside the tunnel.


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.

  1. To what value should northbound and southbound be initialized?
  2. To what value should the condition variable busy be initialized?
  3. Assume a northbound car is currently in the tunnel. Is it possible for a northbound car to be waiting on the busy condition variable?
  4. How many northbound cars can be in the tunnel simultaneously?
  5. Assume that southbound cars are waiting to enter the tunnel and that the last northbound car has just exited the tunnel and called northboundCarDeparture(). Is it guaranteed that a southbound car will enter the tunnel next?
  6. Does this code work correctly if the statement while (northbound > 0) cv_wait(&busy, &lock); is replaced with if (northbound > 0) cv_wait(&busy, &lock);? If so, why? If not, give an example of instruction interleavings which causes problems.
  7. Does this code work correctly if the northbound and southbound cars use separate lock variables? If so, why? If not, give an example of instruction interleavings which causes problems.