← Concepts

阅读中文版本

Mutex

A mutex is a mutual-exclusion lock that lets only one thread enter a critical section at a time, protecting shared state.

concurrency

Definition

A mutex is a synchronisation primitive that grants exclusive ownership of a critical section: a thread locks it, performs its work on shared state, and unlocks it, while other threads wait. It provides mutual exclusion, not ordering or fairness, and it is not re-entrant by default in most languages — locking twice from the same thread can deadlock. Its correctness depends on every access to the protected state taking the same lock.

Context and scope

The workhorse primitive for protecting shared mutable state in threaded and asynchronous programs, from in-process data structures to cross-process file locks.

Common misconceptions

  • A mutex guarantees order — it guarantees exclusion only; which waiter is served next is unspecified
  • Mutexes are interchangeable with semaphores — a semaphore counts permits for several holders, while a mutex allows exactly one
  • Holding a lock briefly is always cheap — contention and lock overhead can dominate when the critical section is hot

Anti-patterns

  • Locking after reading the shared value, leaving a check-then-act gap
  • Holding a lock across I/O or a call that itself waits on a lock, inviting deadlock
  • Forgetting to release on every exit path, so the lock leaks and the program hangs

Related concepts

Related examples

Authoritative source

https://en.wikipedia.org/wiki/Lock_(computer_science)

What it is

A mutex, short for mutual exclusion, is a lock with two states. A thread that acquires it may enter the protected region; any other thread that tries while it is held blocks or fails, depending on the API. Releasing lets a waiter proceed. The guarantee is narrow and precise: at most one holder at a time. Everything else — fairness, ordering, what happens after a crash — depends on the implementation and the caller discipline.

Why it matters

Shared mutable state without a lock is a race condition by construction. A mutex is the smallest tool that makes a read-modify-write sequence atomic with respect to other threads. In-process, it protects counters and caches; across processes, a file or database lock extends the same idea to a wider boundary. Nearly every higher-level construct — thread pools, actor mailboxes, connection pools — uses one internally.

How to use it well

Define the invariant the lock protects and ensure every access to that state takes the same lock. Keep critical sections short and free of I/O, and acquire locks in a consistent global order to avoid deadlock. Prefer scoped guards that unlock automatically so no exit path leaks the lock, and consider whether an atomic operation or an immutable design would remove the need for the lock altogether.