What is the difference between mutex, semaphore, and condition variable?

Why Interviewers Ask This

Advanced questions like this reveal whether a candidate has internalized Operating Systems deeply enough to make architectural decisions. Strong answers demonstrate both breadth and depth of experience.

Answer

These three synchronization primitives serve different purposes and have different semantics: Mutex (Mutual Exclusion lock): binary lock for exclusive access to a resource. Owner-based: only the thread that locked can unlock. Used for protecting critical sections from concurrent access. mutex.lock(); // Acquire exclusive access shared_data++; // Critical section mutex.unlock(); // Release. Properties: ownership (locking thread must unlock), no "available count," optional recursion (reentrant mutex). Semaphore: signaling primitive with a counter. No ownership — any thread can signal. Used for: limiting concurrent access (counting semaphore), signaling between threads (binary semaphore as event). // Producer-consumer signaling: sem_wait(&empty); // Decrement, block if 0 produce(); sem_post(&full); // Increment, wake waiter. Key difference from mutex: semaphore can be signaled by a thread different from the one that waited — used for producer-consumer coordination. Mutex cannot. Condition variable: allows a thread to wait for a specific condition to become true, atomically releasing a mutex while waiting. Always used WITH a mutex. // Consumer: mutex.lock(); while (queue.empty()) { // Check condition cond.wait(mutex); // Atomically release mutex + sleep } item = queue.dequeue(); mutex.unlock(); // Producer: mutex.lock(); queue.enqueue(item); cond.notify_one(); // Wake one waiter mutex.unlock();. Why while loop? Spurious wakeups (condition variable can wake up without notify). POSIX allows spurious wakeups — always re-check the condition. Summary: Mutex = exclusive access; Semaphore = counting/signaling; Condition variable = waiting for a condition within a mutex's protection.

Pro Tip

If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.