ConcurrencyverifiedVerified

Mutex / Lock

Guarantee that only one thread at a time can access a shared resource by requiring threads to acquire an exclusive lock before proceeding.

Coming Soon

errorWhat Problem Does the Mutex / Lock Pattern Solve?

When multiple threads read and write shared state concurrently without coordination, race conditions corrupt data in ways that are non-deterministic and nearly impossible to reproduce. Even a simple counter increment is not atomic at the machine-instruction level, making unsynchronised shared mutation dangerous.

check_circleHow the Mutex / Lock Pattern Works

Protect every access to shared state with a mutual-exclusion lock. A thread must acquire the mutex before entering the critical section; all other threads block at the acquire call until the lock is released. This serialises access to the shared resource while allowing threads to run concurrently everywhere else.

Mutex / Lock Pattern Architecture

hourglass_empty

Rendering diagram...

Implementation by Language

lightbulb

Mutex / Lock Pattern in the Real World

A single-occupancy public restroom with a door latch is a perfect mutex. The latch (lock) ensures only one person (thread) occupies the restroom (critical section) at a time. Anyone who finds the door locked must wait outside; when the occupant leaves and unlatches the door, one waiting person may enter.

Frequently Asked Questions

helpDo I need a Mutex in single-threaded JavaScript?

Not for synchronous code, but yes for async operations. If two async functions read-modify-write shared state (like a database counter), interleaved awaits can cause race conditions. An async mutex ensures only one async operation accesses the critical section at a time.

helpWhat is the difference between a Mutex and a Semaphore?

A Mutex allows exactly one thread/task to access a resource (binary lock). A Semaphore allows up to N concurrent accesses (counting lock). Use Mutex for exclusive access (one writer at a time); use Semaphore for limited concurrency (max 5 database connections).