UNIVERSITY OF WISCONSIN-MADISON
Computer Sciences Department
CS 537
Spring 2001
A. Arpaci-Dusseau
Quiz #3: Feb 21th -- Synchronization
Name: Student ID #:

Problem 1: 88 points

The following Java code samples describe a Lock class two methods: acquire() and release(). You can assume that the application calls lock.acquire() before entering a critical section and lock.release() after exiting the critical section. For the implementations that require a tid (i.e., thread id), you can assume that the tid of each thread is either 0 or 1. Hint: Remember to consider how variables are initialized!

For each code sample, answer the following questions:

  1. Does the code guarantee mutual exclusion? (Simply answer yes or no)
  2. Does the code guarantee progress? (Simply answer yes or no)
  3. List all other limitations that exist for each implementation. Issues you might consider include (but are not limited to) the following: generality, efficiency, and fairness. (Note: You can skip this part of the question when the implementation fails to provide mutual exclusion or progress.)

class Lock {

    private int turn = 0;

    public void acquire(int tid) {
        while (turn == (1 - tid));
    }
    public void release(int tid) {
        turn = (1 - tid);
    }
}




class Lock {

    public void acquire() {
       disableInterrupts();
    }
    public void release() { 
       enableInterrupts();	
    }
}



class Lock {

    private int turn = 0;
    private boolean lock[2] = {false, false};

    public void acquire(int tid) { 
        lock[tid] = true;
        turn = 1 - tid;
        while (lock[1-tid] && turn == (1 - tid));
    }

    public void release(int tid) { 
        lock[tid] = false;
    }
}






class Lock {

    private boolean lock = true;

    public void acquire() {
        while (TestAndSet(lock, true);
    }
    public void release() { 
        lock = false;
    }
}






Problem 2: 12 points

Locks are often implemented by maintaining a list of processes (or threads) that are waiting to acquire the lock. What are all of the advantages of this approach (compared to a correct implementation of a lock that does not use a list)? Be precise in your answer.