mutex semaphore

Mutex and Semaphore — synchronization primitives that control access to shared resources in concurrent programs.

Mutex (Mutual Exclusion Lock)

  • Binary: locked or unlocked
  • Only the owner thread can unlock it
  • Protects a critical section — one thread at a time
  • Use when: Exactly one thread should access the resource
mutex.lock()
// critical section — only one thread here
mutex.unlock()

Semaphore

  • Counter-based: initialized to N (number of concurrent accesses allowed)
  • `wait()` / `P()`: Decrement counter; block if counter = 0
  • `signal()` / `V()`: Increment counter; wake one waiting thread
  • Use when: Multiple threads can share (e.g., connection pool of size N)

Other Synchronization Primitives

  • Spinlock: Busy-wait loop instead of sleeping (fast for very short critical sections, wastes CPU otherwise)
  • Read-Write Lock (RWLock): Multiple readers OR one writer. Great for read-heavy workloads
  • Condition Variable: Thread waits until a condition becomes true (paired with mutex)
  • Barrier: All threads must arrive before any can proceed

Performance Tip

  • Minimize time spent inside critical sections
  • Use lock-free data structures when possible (atomic CAS operations)

Choosing the right synchronization primitive is critical for both correctness and performance.

Go deeper with CFSGPT

Get AI-powered deep-dives, save terms, and run advanced simulations — free account.

Create Free Account