Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Operating Systems
Operating Systemsmedium

Mutex vs semaphore vs read-write lock — when do you use each?

Tags
#mutex#semaphore#rw-lock
Back to categoryPractice quiz

Answer

A mutex provides exclusive access, a semaphore controls access to a limited number of resources, and a read-write lock allows multiple readers or one writer. Use them based on contention and access patterns.

Advanced answer

Deep dive

Pick the right primitive for the pattern:

  • Mutex: single owner, simplest, good for short critical sections.
  • Semaphore: throttle concurrency (e.g., DB connections).
  • RW lock: many readers, few writers; watch for writer starvation.

Examples

Use a semaphore for connection pooling:

max 20 DB connections -> semaphore(20)

Common pitfalls

  • Using RW locks when writes are frequent (worse than mutex).
  • Forgetting to release semaphores on errors.
  • Holding locks too long (contention).

Interview follow-ups

  • How do you avoid writer starvation?
  • When is a mutex faster than an RW lock?
  • What is a spinlock and when is it useful?