What is the difference between mutex, semaphore, and condition variable?
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.
Previous
What is the Linux kernel scheduling (CFS)?
Next
What is virtual memory in detail — TLB, page tables, huge pages?