CSE 120: Synchronization Practice Solutions

Spring 2025
  1. Event
    class Event {
      boolean signaled;
      Lock lock;
      Condition cv;
    
      Event () {
        signaled = false;
        lock = new Lock();
        cv = new Condition(lock);
      }
    
      void wait () {
        lock.acquire();
        while (!signaled) {
          cv.sleep();
        }
        lock.release();
      }
    
      void signal () {
        lock.acquire();
        signaled = true;
        cv.wakeAll();
        lock.release();
      }
    }
    
  2. CountdownEvent
    class CountdownEvent {
      int counter;
      bool signalled;
      Lock lock;
      Condition cv;
    
      CountdownEvent (int count) {
        counter = count;
        if (counter > 0) {
          signalled = false;
        } else {
          signalled = true;
        }
        lock = new Lock();
        cv = new Condition(lock);
      }
    
      void Increment () {
        lock.acquire();
        if (signalled == false) {
          counter++;
        } // otherwise do nothing if already signalled
        lock.release();
      }
    
      void Decrement () {
        lock.acquire();
        if (signalled == false) {
          counter--;
          if (counter == 0) {
            signalled = true;
            cv.wakeAll();
          }
        } // otherwise do nothing if already signalled
        lock.release();
      }
    
      void Wait () {
        lock.acquire();
        if (signalled == false) {
          cv.sleep();
        } // otherwise do nothing if already signalled
        lock.release();
      }
    }
    
  3. sleepUntil
    // a method of the Condition class
    public void sleepUntil (Callable<boolean> predicate) {
      do {
        this.sleep();  // normal sleep method of the condition variable class
      } while (predicate.call() == false) {
    }