Skip to main content

Coordination Primitive Workshop

Retrieval Prompts

  1. State from memory what pthread_cond_wait does atomically.
  2. Give the three rules for correct condition-variable usage.
  3. State the difference between counting and binary semaphores.
  4. Write in one line why a binary semaphore is not a drop-in replacement for a mutex.
  5. State what Mesa signaling semantics forces waiters to do.

Compare and Distinguish

Separate these pairs cleanly:

  • mutex + condition variable versus counting semaphore (when is each natural?)
  • signal versus broadcast (when does broadcast help, when is it a thundering-herd bug?)
  • semaphore versus future/promise for one-shot signaling
  • Java synchronized versus ReentrantLock + Condition
  • Mesa versus Hoare signaling

Common Mistake Check

Identify the bug in each:

  1. pthread_mutex_lock(&m);
    if (count == 0) pthread_cond_wait(&cv, &m);
  2. pthread_mutex_lock(&m);
    ready = true;
    pthread_mutex_unlock(&m);
    pthread_cond_signal(&cv); // outside the lock
  3. sem_t s; sem_init(&s, 0, 1);
    // Thread A:
    sem_wait(&s); critical(); sem_post(&s);
    // Thread B, from elsewhere, never locks it but calls:
    sem_post(&s); // extra credit given
  4. synchronized void put(T x) {
    while (full) { wait(); }
    buf[n++] = x;
    notify(); // only one condition, many waiters
    }

Mini Application

Design and sketch code for each:

  1. A barrier for N threads using one mutex and one condition variable. Threads call barrier_wait() and all are released once N have arrived.
  2. A bounded semaphore pool limiting concurrent DB connections to K, with graceful shutdown that drains in-flight borrows before exiting.
  3. A one-shot event (Event in Python terms) using mutex + condvar. Many waiters block on wait_event(); one set_event() wakes all of them; the event is set-once.
  4. A monitor in the language of your choice that implements a bounded buffer with separate not_full and not_empty condition queues.

For each, note the predicates, the signaling choice (signal vs broadcast), and one failure mode the choice prevents.

Evidence Check

This page is complete only if you can:

  • show working pseudocode for all four designs
  • explain, for each, which condition a waiter is testing and why the test must be in a loop
  • name at least one bug you avoided by choosing broadcast over signal or vice versa