Coordination Primitive Workshop
Retrieval Prompts
- State from memory what
pthread_cond_waitdoes atomically. - Give the three rules for correct condition-variable usage.
- State the difference between counting and binary semaphores.
- Write in one line why a binary semaphore is not a drop-in replacement for a mutex.
- 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?)
signalversusbroadcast(when does broadcast help, when is it a thundering-herd bug?)- semaphore versus future/promise for one-shot signaling
- Java
synchronizedversusReentrantLock+Condition - Mesa versus Hoare signaling
Common Mistake Check
Identify the bug in each:
-
pthread_mutex_lock(&m);
if (count == 0) pthread_cond_wait(&cv, &m); -
pthread_mutex_lock(&m);
ready = true;
pthread_mutex_unlock(&m);
pthread_cond_signal(&cv); // outside the lock -
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 -
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:
- A barrier for
Nthreads using one mutex and one condition variable. Threads callbarrier_wait()and all are released onceNhave arrived. - A bounded semaphore pool limiting concurrent DB connections to
K, with graceful shutdown that drains in-flight borrows before exiting. - A one-shot event (
Eventin Python terms) using mutex + condvar. Many waiters block onwait_event(); oneset_event()wakes all of them; the event is set-once. - A monitor in the language of your choice that implements a bounded buffer with separate
not_fullandnot_emptycondition 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
broadcastoversignalor vice versa