Course contentsShow
← Computer Science
Lesson 1303 of 2,87230. Process SynchronizationFree lesson

Semaphores vs Mutexes vs Condition Variables

Comparing semaphores with mutexes and condition variables: strengths, weaknesses, and appropriate usage contexts.

Semaphores vs Mutexes vs Condition Variables

You'll learn when to choose semaphores, mutexes, or condition variables for different synchronization problems.

Core Differences

Though all three mechanisms provide synchronization, they serve different purposes and have distinct strengths:

Mutexes are designed specifically for mutual exclusion — protecting critical sections. They have clear ownership: the thread that locks a mutex must be the one to unlock it. This ownership model catches bugs at runtime and makes code intent obvious. Use mutexes when you need simple lock/unlock protection around shared data.

Semaphores are more flexible counters that support both mutual exclusion (binary semaphores) and resource counting (counting semaphores). Unlike mutexes, any thread can signal a semaphore — there's no ownership. This flexibility makes semaphores excellent for signaling between threads and managing resource pools, but it also makes them easier to misuse (forgetting a signal, double-signaling, etc.).

Condition Variables work together with mutexes to enable threads to wait for specific conditions. They efficiently put threads to sleep until another thread signals that something has changed. Without condition variables, you'd need busy-waiting loops. Condition variables are ideal for producer-consumer scenarios where threads need to wait for state changes (e.g., "wait until queue is not empty").

When to Use What

  • Mutex: Protecting shared data structures; simple lock-and-unlock patterns
  • Semaphore: Counting available resources; signaling between threads; no ownership needed
  • Condition Variable: Waiting for complex conditions; avoiding busy-waiting; coordinating state changes

The trend in modern code is toward mutexes + condition variables for clarity and safety, reserving semaphores for specialized counting scenarios.

Key Takeaway: Mutexes provide ownership-based locking, semaphores offer flexible counting and signaling, and condition variables enable efficient waiting for conditions — choose based on your specific synchronization need.