Conceptcore
Mutual exclusion
Also called mutex, lock, critical section.
Mutual exclusion lets at most one thread at a time run a critical section, the code that uses a shared resource. A mutex, or lock, is the usual tool.
- Applies to
- core-languages
Idea
Threads that share memory can get in each other's way. A thread that adds to a shared balance reads the old value, computes the sum and writes the result. When two Thread do these steps at the same time, both can read the same old value. Then one write replaces the other, and one deposit is lost. This bug is a lost update. Data race describes the wider class of bugs.
A critical section is a part of a program that uses a shared resource. Mutual exclusion is the rule that at most one thread is in its critical section at any moment.1 The program below forces the bad interleaving with a barrier. Both threads read the balance, both wait at the barrier until the other has read, and then both write.
This code runs but gives a wrong answer on purpose.
import threading
balance = 100
both_have_read = threading.Barrier(2)
def deposit(amount):
global balance
seen = balance
both_have_read.wait()
balance = seen + amount
depositors = [threading.Thread(target=deposit, args=(50,)) for _ in range(2)]
for depositor in depositors:
depositor.start()
for depositor in depositors:
depositor.join()
print("balance:", balance)
balance: 150
The balance must be 200, but the program loses one deposit of 50. Without the barrier, the bug appears only on some runs, which makes it hard to find. A mutex, or lock, gives mutual exclusion. A thread locks the mutex before its critical section and unlocks it after. While one thread holds the lock, each other thread that tries to lock it waits. In Python, the with statement locks the lock at the start of the block and unlocks it at the end.7
import threading
balance = 100
balance_lock = threading.Lock()
def deposit(amount):
global balance
with balance_lock:
seen = balance
balance = seen + amount
depositors = [threading.Thread(target=deposit, args=(50,)) for _ in range(2)]
for depositor in depositors:
depositor.start()
for depositor in depositors:
depositor.join()
print("balance:", balance)
balance: 200
The lock does not fix the order of the two deposits. Either thread can go first. The lock makes sure that one critical section ends before the other starts, so the result is the same on each run.
How it works
The problem
Dijkstra stated the problem for processes that loop and enter a critical section from time to time. A solution must keep at most one process in its critical section. It must not assume anything about the relative speeds of the processes. A process that stops outside its critical section must not block the others. And the processes must not wait for each other forever when both want to enter.1 The last two conditions rule out a lock that is never released and two threads that each give way to the other without end.
Ordinary loads and stores can solve the problem, as the algorithms of Dekker, Dijkstra, Lamport and Peterson show (see History). These algorithms work, but on hardware that reorders memory accesses they need memory barriers to be correct.34 Library locks use special instructions instead.
Atomic read-modify-write
An atomic read-modify-write (RMW) instruction reads a memory word and writes it in one step that no other thread can split. Two forms are common:
- Test-and-set sets a flag to true and returns the value that it had before. In C++,
std::atomic_flag::test_and_setdoes this, and the operations ofatomic_flagare always lock-free.15 The thread that getsfalseback has taken the lock. - Compare-and-swap (CAS) writes a value only if the word still holds an expected value, and reports whether it did. A thread takes the lock when it changes the word from "unlocked" to "locked".
A spin lock is a loop around one of these instructions. This Rust spin lock uses CAS on an AtomicBool. The guard type unlocks in its destructor, which the next section explains.
use std::cell::UnsafeCell;
use std::hint;
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
struct SpinLock<T> {
locked: AtomicBool,
value: UnsafeCell<T>,
}
// SAFETY: the flag lets only one thread at a time reach the value.
unsafe impl<T: Send> Sync for SpinLock<T> {}
struct SpinGuard<'a, T> {
lock: &'a SpinLock<T>,
}
impl<T> SpinLock<T> {
fn new(value: T) -> Self {
SpinLock {
locked: AtomicBool::new(false),
value: UnsafeCell::new(value),
}
}
fn lock(&self) -> SpinGuard<'_, T> {
while self
.locked
.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)
.is_err()
{
hint::spin_loop();
}
SpinGuard { lock: self }
}
}
impl<T> Deref for SpinGuard<'_, T> {
type Target = T;
fn deref(&self) -> &T {
// SAFETY: this guard holds the lock.
unsafe { &*self.lock.value.get() }
}
}
impl<T> DerefMut for SpinGuard<'_, T> {
fn deref_mut(&mut self) -> &mut T {
// SAFETY: this guard holds the lock.
unsafe { &mut *self.lock.value.get() }
}
}
impl<T> Drop for SpinGuard<'_, T> {
fn drop(&mut self) {
self.lock.locked.store(false, Ordering::Release);
}
}
fn main() {
let counter = SpinLock::new(0u32);
thread::scope(|scope| {
for _ in 0..4 {
scope.spawn(|| {
for _ in 0..10_000 {
*counter.lock() += 1;
}
});
}
});
println!("total: {}", *counter.lock());
}
total: 40000
The orderings Acquire and Release are part of the lock. A lock must also make the writes of one critical section visible to the next. The C++ standard states this for every mutex: the earlier unlock operations on a mutex synchronize with each lock operation on it.8 Without this rule, a thread could take the lock and still read a stale value.
Spinning, then parking
A spin lock burns CPU time while it waits. If the thread that holds the lock is not running, the waiter can spin for its whole time slice. So a library mutex spins only for a short time. Then it asks the operating system to put the thread to sleep until the lock is free, which is called parking.
On Linux, the tool for this is the futex, a "fast user-space mutex". A futex is an aligned integer in user memory that the program changes only with atomic instructions. When there is no contention, the lock and the unlock stay entirely in user space. The kernel takes part only in the contended case, to put waiters to sleep and wake them.29
The Go sync.Mutex shows the three stages in its source. The fast path of Lock is one CAS that changes the state from 0 to locked. If the CAS fails, lockSlow spins a few times while runtime_canSpin allows it. Then it calls runtime_SemacquireMutex, which parks the goroutine.26
Ownership
Most mutexes have an owner, the thread that locked them. In C++, a thread must own a mutex to unlock it. A call of lock on a std::mutex that the thread already owns breaks a precondition.8 In Java, only one thread at a time holds the monitor of an object.19
Some locks have no owner. A Python Lock does not belong to a thread, and any thread may release it.5 A locked Go Mutex is also not tied to a goroutine, so one goroutine can lock it and another can unlock it.24 A Python RLock has an owner, and only that thread may release it.6
import threading
plain = threading.Lock()
owned = threading.RLock()
plain.acquire()
owned.acquire()
def release_both():
plain.release()
print("Lock: released by another thread")
try:
owned.release()
except RuntimeError as error:
print("RLock:", error)
helper = threading.Thread(target=release_both)
helper.start()
helper.join()
Lock: released by another thread
RLock: cannot release un-acquired lock
A lock without an owner can serve as a signal between threads. A lock with an owner can find more mistakes, because it knows which thread must unlock it.
Lock guards and scope
A pair of calls to lock and unlock is fragile. An early return, a break or an exception between them skips the unlock, and the lock stays held. Most languages tie the unlock to the end of a scope, so it runs on each path out of the critical section.
| Language | Scoped form | What unlocks the lock |
|---|---|---|
| C++ | std::lock_guard, std::scoped_lock, std::unique_lock |
the destructor of the guard11 |
| Rust | the MutexGuard that Mutex::lock returns |
the drop of the guard17 |
| Python | with lock: |
the end of the block, also on an exception7 |
| Java | a synchronized block or method; lock(), then try and finally with unlock() |
normal or abrupt completion19; the finally block20 |
| C# | the lock statement |
a try and finally that the compiler writes22 |
| Go | mu.Lock(), then defer mu.Unlock() |
the deferred call, at return or during a panic27 |
| Kotlin | lock.withLock { } |
the end of the lambda31 |
| C | none | an explicit pthread_mutex_unlock on each path |
The three C++ guards differ. A lock_guard holds one mutex for its whole life. A scoped_lock can take several mutexes, and then its constructor calls std::lock, which avoids a Deadlock between them.12 A unique_lock can move to another owner, start without the lock (defer_lock), or try once and keep the result (try_to_lock).13
Rust goes one step further. A Mutex<T> owns the data that it protects, and the program can reach the data only through the guard.17 Code that forgets to lock does not compile, because it has no path to the data. In C, C++, Java and Go, the mutex and the data are separate. Only a comment or a naming rule says which lock protects which field. Ownership and borrowing explains the borrow rules that make the Rust form work.
Reentrant locks
A reentrant lock, also called a recursive lock, lets its owner lock it again. It counts the levels, and the owner must unlock once for each level. The lock becomes free when the count goes back to zero. Java monitors work this way.19 So do ReentrantLock in Java20, the C# lock statement22, the Python RLock6, std::recursive_mutex in C++10, and a POSIX mutex of type PTHREAD_MUTEX_RECURSIVE.28
Other locks are not reentrant. A second lock by the owner then waits for itself. A std::mutex can deadlock in this case.9 For a Rust Mutex, the result is unspecified: the call can panic or deadlock, but it does not return.17 POSIX gives a choice: a PTHREAD_MUTEX_NORMAL mutex deadlocks, a PTHREAD_MUTEX_ERRORCHECK mutex returns an error, and for the default type the behaviour is undefined.28 This program uses a timeout, so the plain Lock gives up instead of waiting forever.5
import threading
plain = threading.Lock()
reentrant = threading.RLock()
plain.acquire()
print("Lock, second acquire:", plain.acquire(timeout=0.1))
reentrant.acquire()
print("RLock, second acquire:", reentrant.acquire(timeout=0.1))
Lock, second acquire: False
RLock, second acquire: True
A reentrant lock lets one locked method call another locked method of the same object. It also hides a risk. The inner call can run while the outer call has broken the invariant of the data for a moment.
Reader-writer locks
Many critical sections only read. Reads do not conflict with each other, so a reader-writer lock lets many readers in at the same time, or one writer alone.
| Language | Type | Read form | Write form |
|---|---|---|---|
| Rust | std::sync::RwLock18 |
read() |
write() |
| C++ | std::shared_mutex14 |
std::shared_lock |
std::unique_lock |
| Java, Kotlin | ReentrantReadWriteLock21 |
readLock(); Kotlin read { }31 |
writeLock(); Kotlin write { } |
| C# | ReaderWriterLockSlim23 |
EnterReadLock() |
EnterWriteLock() |
| Go | sync.RWMutex25 |
RLock() |
Lock() |
In this Rust program, two read guards exist at the same time. A writer cannot enter while they exist.
use std::sync::RwLock;
fn main() {
let settings = RwLock::new(String::from("mode=quiet"));
{
let first = settings.read().unwrap();
let second = settings.read().unwrap();
println!("two readers: {} and {}", *first, *second);
println!("writer can enter: {}", settings.try_write().is_ok());
}
settings.write().unwrap().push_str(",log=on");
println!("after the write: {}", settings.read().unwrap());
}
two readers: mode=quiet and mode=quiet
writer can enter: false
after the write: mode=quiet,log=on
The policy for a waiting writer differs. In Go, a blocked Lock call stops further readers from entering, so a stream of readers cannot starve the writer.25 ReaderWriterLockSlim also blocks further readers while a writer waits.23 The Rust RwLock takes its policy from the operating system.18 Because of these policies, a thread that takes a read lock twice can deadlock: a writer that waits between the two calls blocks the second one.1825
A read lock cannot become a write lock in Java. A thread that holds the read lock and asks for the write lock never succeeds. A writer can take the read lock and then release the write lock, which is a downgrade.21 C# offers an upgradeable mode instead. Only one thread at a time can be in it, so its upgrade cannot deadlock with another upgrade.23
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Standard library | |
| C++ | Standard library | |
| Java | Native | |
| C | Standard library | |
| C# | Native | |
| JavaScript | Idiom | |
| TypeScript | Idiom | |
| Go | Standard library | |
| Rust | Standard library | |
| Kotlin | Standard library | |
| SQL | Does not apply | SQL statements have no threads and no shared variables; the database system controls concurrent transactions. |
| Bash | Absent | Bash has no threads; background jobs are separate processes that share no variables. Alternative: The flock(1) command of util-linux, which locks a file between processes; it is not part of Bash. |
| PowerShell | Idiom | |
| HTML | Does not apply | Markup has no threads. |
| CSS | Does not apply | Style rules have no threads. |
| Regular expressions | Does not apply | A pattern has no threads. |
The example files show a counter that several threads increase under a lock, in each language. The table gives the verdict for each tier 1 language.
| Language | Verdict | Form |
|---|---|---|
| Python | stdlib | threading.Lock and RLock with with |
| JavaScript | idiom | a lock built from Atomics on a SharedArrayBuffer, between workers |
| TypeScript | idiom | as JavaScript; an async mutex for critical sections that contain await |
| Java | native | synchronized; ReentrantLock and ReentrantReadWriteLock |
| C | stdlib | POSIX pthread_mutex_t; the optional C11 mtx_t |
| C++ | stdlib | std::mutex with std::lock_guard or std::scoped_lock; std::shared_mutex |
| C# | native | the lock statement; ReaderWriterLockSlim |
| Go | stdlib | sync.Mutex and sync.RWMutex with defer |
| Rust | stdlib | std::sync::Mutex<T> and RwLock<T> with guards |
| Kotlin | stdlib | withLock, read and write over the JDK locks |
| PowerShell | idiom | [System.Threading.Monitor] from .NET in ForEach-Object -Parallel |
| Bash | absent | no threads; flock(1) locks a file between processes |
| SQL | n/a | the database system controls concurrent transactions |
| Regex | n/a | a pattern has no threads |
| HTML/CSS | n/a | markup and style rules have no threads |
The C examples use POSIX threads. The C standard library has mtx_t and mtx_lock in <threads.h>, but this header is optional. An implementation that defines __STDC_NO_THREADS__ need not provide it.33 The C library of macOS does not provide it.
JavaScript code on one thread needs no mutex. Only one piece of code runs at a time, and nothing else runs between two statements. Workers do run in parallel, and they can share a SharedArrayBuffer. The language gives no lock type, but Atomics.compareExchange, Atomics.wait and Atomics.notify are the parts of one.30 The JavaScript example builds a lock from them. A second case appears on one thread: a critical section that contains await lets other tasks run in the middle of it. The TypeScript example shows this case and an async mutex that fixes it.
Bash has no threads. A background job is a separate process, and processes share no variables. They can share files. The flock command manages flock(2) locks from shell scripts, but it is part of the util-linux package, not of Bash.35
SQL statements have no threads and no shared variables. The database system decides how concurrent transactions see each other's changes. Regex patterns, HTML and CSS have no threads.
import threading
counter = 0
counter_lock = threading.Lock()
def add_many(times):
global counter
for _ in range(times):
with counter_lock:
counter += 1
workers = [threading.Thread(target=add_many, args=(100_000,)) for _ in range(4)]
for worker in workers:
worker.start()
for worker in workers:
worker.join()
print("total:", counter)
total: 400000
- Verdict: stdlib. The module
threadinggivesLockandRLock. The statementwith counter_lock:acquires the lock and releases it at the end of the block, also when the block raises an exception. - A
Lockhas no owner, so any thread may release it. AnRLockhas an owner and a recursion level, and only the owner may release it. acquire(timeout=...)returnsFalsewhen the time runs out. Use it to stop a program that would otherwise wait forever.- The statement
counter += 1reads, adds and writes in separate steps, so threads can lose updates without the lock. The global interpreter lock does not make the statement atomic.
#include <mutex>
#include <print>
#include <shared_mutex>
#include <thread>
#include <vector>
class Account {
public:
explicit Account(int balance) : balance_(balance) {}
int balance() const {
std::shared_lock reader(mutex_);
return balance_;
}
friend void transfer(Account& from, Account& to, int amount) {
std::scoped_lock both(from.mutex_, to.mutex_);
from.balance_ -= amount;
to.balance_ += amount;
}
private:
mutable std::shared_mutex mutex_;
int balance_;
};
int main() {
Account checking(1000);
Account savings(1000);
{
std::vector<std::jthread> workers;
for (int i = 0; i < 4; i++) {
workers.emplace_back([&] {
for (int k = 0; k < 1000; k++) {
transfer(checking, savings, 1);
transfer(savings, checking, 1);
}
});
}
}
std::println("checking {}, savings {}", checking.balance(), savings.balance());
}
checking 1000, savings 1000
- Verdict: stdlib. The header
<mutex>givesstd::mutexand the guards.<shared_mutex>gives the reader-writer lockstd::shared_mutex. std::scoped_lockwith two mutexes locks both with a deadlock-avoidance algorithm. The two transfers lock the same pair in opposite orders, and the program still finishes.std::shared_locktakes shared ownership, so many readers ofbalance()can run at once. A write needs exclusive ownership. The mutex ismutableso that aconstmethod can lock it.- The
std::jthreadobjects join in their destructors at the end of the inner block, before the program prints. A plainstd::lock_guardis enough when a function takes one mutex.
import java.util.concurrent.locks.ReentrantLock;
public class Main {
static class Account {
private int balance;
synchronized void deposit(int amount) {
balance += amount;
}
synchronized void depositTwice(int amount) {
deposit(amount);
deposit(amount);
}
synchronized int balance() {
return balance;
}
}
public static void main(String[] args) throws InterruptedException {
Account account = new Account();
Thread[] workers = new Thread[4];
for (int i = 0; i < workers.length; i++) {
workers[i] = new Thread(() -> {
for (int k = 0; k < 10_000; k++) {
account.depositTwice(1);
}
});
workers[i].start();
}
for (Thread worker : workers) {
worker.join();
}
System.out.println("balance: " + account.balance());
ReentrantLock lock = new ReentrantLock();
lock.lock();
lock.lock();
System.out.println("hold count: " + lock.getHoldCount());
lock.unlock();
lock.unlock();
System.out.println("locked: " + lock.isLocked());
}
}
balance: 80000
hold count: 2
locked: false
- Verdict: native. Each object has a monitor. A
synchronizedmethod locks the monitor ofthis, and the lock is released when the method returns or throws. - Monitors are reentrant.
depositTwiceholds the monitor and callsdeposit, which locks the same monitor again. java.util.concurrent.locks.ReentrantLockaddstryLock, timeouts and an optional fair mode. Calllock(), thentry, andunlock()infinally. The owner must unlock once for each lock.ReentrantReadWriteLockgives a read lock and a write lock. A reader cannot upgrade to the write lock, but a writer can downgrade to the read lock.
A thread that calls unlock without the lock gets an exception.
This code raises IllegalMonitorStateException, on purpose.
import java.util.concurrent.locks.ReentrantLock;
public class Main {
public static void main(String[] args) {
ReentrantLock lock = new ReentrantLock();
lock.unlock();
}
}
#define _POSIX_C_SOURCE 200809L
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
static pthread_mutex_t counter_lock = PTHREAD_MUTEX_INITIALIZER;
static long counter = 0;
static void *add_many(void *arg) {
long times = *(long *)arg;
for (long i = 0; i < times; i++) {
pthread_mutex_lock(&counter_lock);
counter++;
pthread_mutex_unlock(&counter_lock);
}
return NULL;
}
int main(void) {
pthread_t workers[4];
long times = 100000;
for (int i = 0; i < 4; i++) pthread_create(&workers[i], NULL, add_many, ×);
for (int i = 0; i < 4; i++) pthread_join(workers[i], NULL);
printf("total: %ld\n", counter);
pthread_mutexattr_t attributes;
pthread_mutexattr_init(&attributes);
pthread_mutexattr_settype(&attributes, PTHREAD_MUTEX_ERRORCHECK);
pthread_mutex_t checked;
pthread_mutex_init(&checked, &attributes);
pthread_mutex_lock(&checked);
int again = pthread_mutex_lock(&checked);
printf("second lock: %s\n", again == EDEADLK ? "EDEADLK" : "no error");
pthread_mutex_unlock(&checked);
pthread_mutex_destroy(&checked);
pthread_mutexattr_destroy(&attributes);
return 0;
}
total: 400000
second lock: EDEADLK
- Verdict: stdlib. This example uses POSIX threads,
pthread_mutex_t. The C standard hasmtx_tin<threads.h>, but the header is optional, and the C library of macOS does not have it. - C has no guards. Each path out of the critical section needs its own
pthread_mutex_unlock. Agototo one cleanup label keeps the paths together. - The mutex type decides what a second lock by the owner does.
PTHREAD_MUTEX_ERRORCHECKreturnsEDEADLK,PTHREAD_MUTEX_RECURSIVEcounts the levels, and for the default type the result is undefined. pthread_rwlock_tis the POSIX reader-writer lock, withpthread_rwlock_rdlockfor readers andpthread_rwlock_wrlockfor the writer. Check the return value of each call in real code.
var counterLock = new Lock();
int counter = 0;
var workers = new Task[4];
for (int i = 0; i < workers.Length; i++)
{
workers[i] = Task.Run(() =>
{
for (int k = 0; k < 10_000; k++)
{
lock (counterLock)
{
counter++;
}
}
});
}
Task.WaitAll(workers);
Console.WriteLine($"total: {counter}");
var settings = new ReaderWriterLockSlim();
settings.EnterReadLock();
Console.WriteLine($"readers: {settings.CurrentReadCount}");
settings.ExitReadLock();
total: 40000
readers: 1
- Verdict: native. The
lockstatement takes a lock, runs the block and releases the lock in afinally. With aSystem.Threading.Lock, it callsEnterScope. With any other object, it usesMonitor.EnterandMonitor.Exit. - The thread that holds a lock can take it again, so
lockis reentrant. - Lock a private object that only this code can see. Do not lock
this, aTypeor a string, because other code can lock the same object. - The body of a
lockstatement cannot containawait.ReaderWriterLockSlimis the reader-writer lock. It does not allow recursion by default, and it has an upgradeable read mode.
import { Worker } from "node:worker_threads";
const source = `
const { workerData } = require("node:worker_threads");
const cells = new Int32Array(workerData.shared);
const LOCK = 0;
const COUNT = 1;
function lock() {
while (Atomics.compareExchange(cells, LOCK, 0, 1) !== 0) {
Atomics.wait(cells, LOCK, 1);
}
}
function unlock() {
Atomics.store(cells, LOCK, 0);
Atomics.notify(cells, LOCK, 1);
}
for (let i = 0; i < workerData.times; i++) {
lock();
cells[COUNT] = cells[COUNT] + 1;
unlock();
}
`;
const shared = new SharedArrayBuffer(2 * Int32Array.BYTES_PER_ELEMENT);
function runWorker(times) {
return new Promise((resolve, reject) => {
const worker = new Worker(source, { eval: true, workerData: { shared, times } });
worker.once("exit", resolve);
worker.once("error", reject);
});
}
await Promise.all([1, 2, 3, 4].map(() => runWorker(10_000)));
console.log("total:", new Int32Array(shared)[1]);
total: 40000
- Verdict: idiom. Code on one thread needs no lock, because nothing else runs between two statements. Workers run in parallel, and a
SharedArrayBuffergives them shared memory. - The language has no mutex type.
Atomics.compareExchangetakes the lock,Atomics.waitparks the worker while the cell holds 1, andAtomics.notifywakes one waiter after the unlock. The plain read and write ofcells[COUNT]are safe, because they happen between the atomic operations of the lock and the unlock. - The main thread of a browser page may not call
Atomics.wait. Node.js allows it. For critical sections that containawaiton one thread, see the TypeScript example.
On one thread, a critical section that contains await lets other tasks run in the middle of it. Both deposits here read the balance before either one writes.
This code runs but gives a wrong answer on purpose.
let balance = 100;
async function deposit(amount: number): Promise<void> {
const seen = balance;
await new Promise((resolve) => setTimeout(resolve, 10));
balance = seen + amount;
}
await Promise.all([deposit(50), deposit(50)]);
console.log("balance:", balance);
balance: 150
An async mutex makes each task wait for the one before it. It suspends the task, not the thread.
class AsyncMutex {
private tail: Promise<void> = Promise.resolve();
lock(): Promise<() => void> {
let release: () => void = () => {};
const done = new Promise<void>((resolve) => {
release = resolve;
});
const ready = this.tail.then(() => release);
this.tail = done;
return ready;
}
}
let balance = 100;
const balanceMutex = new AsyncMutex();
async function deposit(amount: number): Promise<void> {
const unlock = await balanceMutex.lock();
try {
const seen = balance;
await new Promise((resolve) => setTimeout(resolve, 10));
balance = seen + amount;
} finally {
unlock();
}
}
await Promise.all([deposit(50), deposit(50)]);
console.log("balance:", balance);
balance: 200
- Verdict: idiom. TypeScript adds no lock type. Between workers, use
Atomicsas in the JavaScript example. - The mutex keeps a chain of promises. Each
lockcall waits for the promise of the call before it, andunlockresolves its own promise. finallyreleases the mutex when the critical section throws.
package main
import (
"fmt"
"sync"
)
type HitCounter struct {
mu sync.RWMutex
hits map[string]int
}
func (c *HitCounter) Add(page string) {
c.mu.Lock()
defer c.mu.Unlock()
c.hits[page]++
}
func (c *HitCounter) Get(page string) int {
c.mu.RLock()
defer c.mu.RUnlock()
return c.hits[page]
}
func main() {
counter := &HitCounter{hits: map[string]int{}}
var wg sync.WaitGroup
for range 4 {
wg.Add(1)
go func() {
defer wg.Done()
for range 10_000 {
counter.Add("/home")
}
}()
}
wg.Wait()
fmt.Println("hits:", counter.Get("/home"))
}
hits: 40000
- Verdict: stdlib. The package
syncgivesMutexandRWMutex. The zero value of each is an unlocked lock, so the struct needs no constructor for it. defer c.mu.Unlock()releases the lock when the method returns, also during a panic. Put it on the line afterLock.- A mutex must not be copied after its first use. Give methods a pointer receiver, as
*HitCounterhere. The commandgo vetreports copies of locks. - A Go map is not safe for concurrent writes, so the map needs the lock.
RWMutexlets manyGetcalls run at once, and a waiting writer blocks further readers.
use std::sync::Mutex;
use std::thread;
fn main() {
let counter = Mutex::new(0u32);
thread::scope(|scope| {
for _ in 0..4 {
scope.spawn(|| {
for _ in 0..10_000 {
*counter.lock().unwrap() += 1;
}
});
}
});
println!("total: {}", counter.into_inner().unwrap());
}
total: 40000
- Verdict: stdlib.
Mutex<T>owns the value that it protects.lockreturns aMutexGuard, the only way to reach the value, and the drop of the guard unlocks. thread::scopelets the threads borrowcounterand joins them before it returns.into_innerthen takes the value out with no lock, because no other reference exists.lockreturns aResult, because a panic in a thread that holds the guard poisons the mutex.
This program recovers from a poisoned mutex. The error holds the guard, and into_inner gives it back, so the program can check the data and go on.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let balance = Arc::new(Mutex::new(100));
let worker_balance = Arc::clone(&balance);
let outcome = thread::spawn(move || {
let mut guard = worker_balance.lock().unwrap();
*guard -= 30;
panic!("the transfer stopped halfway");
})
.join();
println!("worker failed: {}", outcome.is_err());
println!("poisoned: {}", balance.is_poisoned());
let guard = match balance.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
println!("balance after the failed transfer: {}", *guard);
}
worker failed: true
poisoned: true
balance after the failed transfer: 70
import java.util.concurrent.locks.ReentrantLock
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read
import kotlin.concurrent.thread
import kotlin.concurrent.withLock
import kotlin.concurrent.write
class Scoreboard {
private val lock = ReentrantReadWriteLock()
private val scores = mutableMapOf<String, Int>()
fun add(player: String, points: Int) = lock.write {
scores[player] = (scores[player] ?: 0) + points
}
fun total(): Int = lock.read { scores.values.sum() }
}
fun main() {
val counterLock = ReentrantLock()
var counter = 0
val workers = List(4) {
thread {
repeat(10_000) {
counterLock.withLock { counter++ }
}
}
}
workers.forEach { it.join() }
println("total: $counter")
val board = Scoreboard()
val players = listOf("ada", "grace", "alan").map { name ->
thread { repeat(100) { board.add(name, 2) } }
}
players.forEach { it.join() }
println("points: ${board.total()}")
}
total: 40000
points: 600
- Verdict: stdlib. Kotlin on the JVM uses the locks of
java.util.concurrent.locks. The packagekotlin.concurrentaddswithLock,read,writeandthread. The functionthreadstarts a thread at once and returns it, sojoincan wait for it. withLockis an inline function. It locks, runs the lambda and unlocks, also when the lambda throws.readandwritedo the same for the two halves of aReentrantReadWriteLock. Manytotalcalls can run at once, butaddruns alone.- The lambda changes the local
counter. The compiler puts the variable in a shared object, so the lock must protect it. The Javasynchronizedmodifier has the Kotlin form@Synchronized.
$gate = [object]::new()
$total = [int[]]::new(1)
1..4 | ForEach-Object -Parallel {
$gate = $using:gate
$total = $using:total
foreach ($i in 1..1000) {
[System.Threading.Monitor]::Enter($gate)
try {
$total[0]++
}
finally {
[System.Threading.Monitor]::Exit($gate)
}
}
}
"total: $($total[0])"
total: 4000
- Verdict: idiom. PowerShell has no lock statement.
ForEach-Object -Parallelruns each script block on its own thread, and the .NET classSystem.Threading.Monitorgives the lock. $using:passes a reference to a .NET object, so all blocks share$gateand the array$total. Shared objects that the blocks change must be thread-safe, or a lock must protect them.tryandfinallymake sure thatMonitor.Exitruns, as the C#lockstatement does.- For collections, the documentation uses thread-safe types such as
ConcurrentDictionaryinstead of a lock. By default, at most 5 blocks run at a time, and-ThrottleLimitchanges this number.
Variations and related ideas
- Semaphores. Dijkstra's semaphore is a counter with the operations P (wait until the count is positive, then decrease it) and V (increase it). A semaphore that starts at one gives mutual exclusion.1 A larger start value lets that many threads in at once.
- Try-lock and timed lock.
tryLockin Java20,acquire(timeout=...)in Python5 andTryLockin Go return at once or after a time limit. They let a thread do other work instead of waiting. The Go documentation warns that the use ofTryLockis often a sign of a deeper problem.24 - Fair locks. A fair lock grants the lock in the order of the requests. Java
ReentrantLocktakes an optional fairness setting. The documentation says that many threads on a fair lock can show lower overall throughput.20 - Monitors. In Java, each object has a monitor, which is the lock that
synchronizeduses.19 Condition variables, which let a thread wait for a state of the data, are a separate topic. - Locks across
await. A thread lock held across anawaitstays held for the whole wait. The code after theawaitcan also resume on a thread that does not own the lock. C# forbidsawaitinside alockstatement (see Pitfalls). Async/await explains the model. An async mutex suspends the task instead of the thread. - No shared mutable state. Data that never changes needs no lock, see Immutability. Threads that send messages instead of sharing memory need no lock around the data, see Channel.
- Lock ordering. Code that takes two locks can deadlock when two threads take them in different orders. Deadlock covers lock ordering and the other remedies.
Pitfalls
A lock around each access is not enough
The read and the write of a read-modify-write must be in one critical section. Here each access has its own lock, and the barrier makes both threads read before either writes.
This code runs but gives a wrong answer on purpose.
import threading
balance = 100
balance_lock = threading.Lock()
both_have_read = threading.Barrier(2)
def deposit(amount):
global balance
with balance_lock:
seen = balance
both_have_read.wait()
with balance_lock:
balance = seen + amount
depositors = [threading.Thread(target=deposit, args=(50,)) for _ in range(2)]
for depositor in depositors:
depositor.start()
for depositor in depositors:
depositor.join()
print("balance:", balance)
balance: 150
No access is unprotected, but the update is still lost. The fix is one critical section around the read, the computation and the write, as in Idea. The same rule holds for check-then-act code, such as "if the key is absent, insert it".
An exception skips the unlock
When a lock and its unlock are separate calls, an exception between them leaves the lock held. Here withdraw throws before it reaches unlock, and another thread then waits 100 milliseconds for the lock and gives up.20
This code runs but gives a wrong answer on purpose.
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
private static final ReentrantLock balanceLock = new ReentrantLock();
private static int balance = 100;
static void withdraw(int amount) {
balanceLock.lock();
if (amount > balance) {
throw new IllegalArgumentException("not enough money");
}
balance -= amount;
balanceLock.unlock();
}
public static void main(String[] args) throws InterruptedException {
try {
withdraw(500);
} catch (IllegalArgumentException error) {
System.out.println("withdraw failed: " + error.getMessage());
}
Thread auditor = new Thread(() -> {
try {
boolean acquired = balanceLock.tryLock(100, TimeUnit.MILLISECONDS);
System.out.println("auditor got the lock: " + acquired);
if (acquired) {
balanceLock.unlock();
}
} catch (InterruptedException error) {
Thread.currentThread().interrupt();
}
});
auditor.start();
auditor.join();
}
}
withdraw failed: not enough money
auditor got the lock: false
The fix is the form that the Java documentation recommends: lock(), then a try block, with unlock() in finally.20 The scoped forms in How it works do the same in the other languages.
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
private static final ReentrantLock balanceLock = new ReentrantLock();
private static int balance = 100;
static void withdraw(int amount) {
balanceLock.lock();
try {
if (amount > balance) {
throw new IllegalArgumentException("not enough money");
}
balance -= amount;
} finally {
balanceLock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
try {
withdraw(500);
} catch (IllegalArgumentException error) {
System.out.println("withdraw failed: " + error.getMessage());
}
Thread auditor = new Thread(() -> {
try {
boolean acquired = balanceLock.tryLock(100, TimeUnit.MILLISECONDS);
System.out.println("auditor got the lock: " + acquired);
if (acquired) {
balanceLock.unlock();
}
} catch (InterruptedException error) {
Thread.currentThread().interrupt();
}
});
auditor.start();
auditor.join();
}
}
withdraw failed: not enough money
auditor got the lock: true
Exception explains finally and the other cleanup forms.
An unlock of a lock that is not held
An unlock must match a lock. A second unlock is a bug, and most libraries stop the program. This Go method mixes defer with an explicit unlock, so the early return unlocks twice.
This code fails on purpose. The output below is the error.
package main
import (
"fmt"
"sync"
)
type Account struct {
mu sync.Mutex
balance int
}
func (a *Account) Withdraw(amount int) bool {
a.mu.Lock()
defer a.mu.Unlock()
if amount > a.balance {
a.mu.Unlock()
return false
}
a.balance -= amount
return true
}
func main() {
account := &Account{balance: 100}
fmt.Println(account.Withdraw(500))
}
The Go runtime stops with fatal error: sync: unlock of unlocked mutex. The documentation calls this a run-time error.24 The fix is to remove the explicit Unlock and let defer do the one unlock. In Python, the release of an unlocked Lock raises RuntimeError.5
This code raises RuntimeError, on purpose.
import threading
balance_lock = threading.Lock()
balance_lock.release()
A panic poisons a Rust mutex
When a thread panics while it holds a Rust Mutex, the mutex becomes poisoned. Each later lock returns an error, because the data may be in a half-changed state.17 Code that calls unwrap on the result then panics too.
This code panics, on purpose.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let balance = Arc::new(Mutex::new(100));
let worker_balance = Arc::clone(&balance);
let outcome = thread::spawn(move || {
let mut guard = worker_balance.lock().unwrap();
*guard -= 30;
panic!("the transfer stopped halfway");
})
.join();
println!("worker failed: {}", outcome.is_err());
let guard = balance.lock().unwrap();
println!("balance: {}", *guard);
}
The second unwrap panics with a PoisonError. Poisoning is advisory. The program can take the guard from the error with PoisonError::into_inner, check the data, and go on, as in the Rust example.17 An RwLock is poisoned only by a panic in write mode.18
A lock held across an await
A critical section that waits for I/O holds the lock for the whole wait. With a thread lock and await, the code after the await can also resume on another thread. C# rejects an await in the body of a lock statement.22
This code does not compile, on purpose.
var balanceLock = new Lock();
int balance = 100;
lock (balanceLock)
{
await Task.Delay(10);
balance += 50;
}
Console.WriteLine(balance);
The compiler stops with error CS1996, "Cannot await in the body of a lock statement". The fix is to do the slow work outside the lock and keep only the update inside. When the critical section must contain an await, use a lock that suspends the task, not the thread. The TypeScript example has one.
Data outside the lock
In C and C++, nothing ties a mutex to the data that it protects. One function that forgets the lock is enough for a data race, which is undefined behaviour. ThreadSanitizer finds the race in this program, where reset writes the field without the lock.
This code has a memory error, on purpose, and the sanitizer reports it.
#include <mutex>
#include <print>
#include <thread>
class Counter {
std::mutex mutex_;
int value_ = 0;
public:
void add() {
std::lock_guard guard(mutex_);
++value_;
}
void reset() { value_ = 0; }
int get() {
std::lock_guard guard(mutex_);
return value_;
}
};
int main() {
Counter counter;
std::thread adder([&] {
for (int i = 0; i < 1000; i++) counter.add();
});
std::thread resetter([&] { counter.reset(); });
adder.join();
resetter.join();
std::println("{}", counter.get() >= 0);
}
The fix is a lock_guard in reset too. A Rust Mutex<T> prevents this mistake, because the field is inside the mutex.
Cost
- The uncontended case. A lock that nobody else holds costs one atomic RMW to lock and one atomic store or RMW to unlock. No system call happens. The Go fast path is one CAS, and a futex stays in user space when there is no contention.2629 This cost is small, but it is larger than a plain load and store.
- The contended case. A thread that finds the lock taken spins for a while, then parks. Each park and each wake is a system call and a context switch. So the time per critical section can grow many times over when many threads want the same lock.
- Convoys. When the holder of a lock is slow or not scheduled, the other threads queue behind it. After the release, they wake one at a time, and each pays the cost of a wake. A lock that is held for a long time turns parallel threads into a queue. The C# guidelines say to hold a lock for as short a time as possible.22
- Fairness against throughput. A fair lock hands the lock to the oldest waiter, which may still be asleep. An unfair lock lets a running thread take it again at once, which gives more throughput but can starve a waiter. In its normal mode, a Go mutex lets a running goroutine compete with a woken waiter. A waiter that fails to get the mutex for more than 1 millisecond switches it to starvation mode. Then the unlock hands the mutex directly to the first waiter.26 The Java documentation says that a fair lock can show lower throughput.20
- False sharing. A processor moves memory between cores in cache lines. Two variables on one cache line contend even when each thread uses only its own variable, and even when no lock protects them. A lock word next to hot data has the same effect. C++ gives
std::hardware_destructive_interference_size, the minimum offset between two objects that avoids this contention.16 Padding oralignaswith this value puts each counter or lock on its own line. - Reader-writer locks. A reader still writes to the shared lock word to record its entry. So readers on many cores contend on that word, and a reader-writer lock can be slower than a plain mutex for short reads. It helps when reads are long or writes are rare.
- Lock granularity. One lock for a whole structure keeps the rules clear, but all threads wait for it. Many small locks allow more parallel work, but they cost more memory and make Deadlock more likely.
History
- 1965. Dijkstra published "Solution of a problem in concurrent programming control" in Communications of the ACM.2 The requirement of mutual exclusion was first stated and solved in this paper.36 In his manuscript EWD 123, Cooperating Sequential Processes, Dijkstra used the term critical section and credited Th. J. Dekker with the first correct solution for two processes. The same text introduced the semaphore operations P and V.1
- 1974. Leslie Lamport published the bakery algorithm in "A New Solution of Dijkstra's Concurrent Programming Problem". It gives mutual exclusion without any lower-level mutual exclusion, even when a read overlaps a write to the same memory.4
- 1981. Gary L. Peterson published "Myths about the mutual exclusion problem" in Information Processing Letters.3 It contains a short algorithm for two processes, which is called Peterson's algorithm.34
References
- Edsger W. Dijkstra, Cooperating sequential processes, EWD 123, 2.1 A Simple Example (the critical section and the conditions on a solution); 3.2 and 3.3 (the operations P and V, and a semaphore for mutual exclusion)
- E. W. Dijkstra, Solution of a problem in concurrent programming control, Communications of the ACM 8(9), 1965, p. 569
- G. L. Peterson, Myths about the mutual exclusion problem, Information Processing Letters 12(3), 1981, pp. 115-116
- Leslie Lamport, The Writings of Leslie Lamport, the entry for A New Solution of Dijkstra's Concurrent Programming Problem, Communications of the ACM 17(8), 1974, pp. 453-455
- The Python Standard Library, threading, Python 3.14, Lock objects; Lock.acquire and Lock.release
- The Python Standard Library, threading, Python 3.14, RLock objects
- The Python Standard Library, threading, Python 3.14, Using locks, conditions, and semaphores in the with statement
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [thread.mutex.requirements.mutex.general], paragraphs 4 to 8 (lock) and 20 to 21 (unlock)
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [thread.mutex.class], paragraph 4, note 1
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [thread.mutex.recursive], paragraph 3
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [thread.lock.guard], paragraph 6
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [thread.lock.scoped], paragraph 2
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [thread.lock.unique], the constructors with defer_lock and try_to_lock
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [thread.sharedmutex.requirements.general], paragraph 2
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [atomics.flag], paragraphs 2, 9 and 10
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [hardware.interference], paragraph 1
- The Rust Standard Library, std::sync::Mutex, the type description, Poisoning, and the methods lock, get_mut and into_inner
- The Rust Standard Library, std::sync::RwLock, the type description, Poisoning, and the method read (Panics and Errors)
- The Java Language Specification, Java SE 25 Edition, 17.1 Synchronization
- Java SE 25 API, java.util.concurrent.locks.ReentrantLock, the class description (fairness and the recommended try and finally form) and tryLock(long, TimeUnit)
- Java SE 25 API, java.util.concurrent.locks.ReentrantReadWriteLock, the class description, Reentrancy and Lock downgrading
- C# language reference, The lock statement, the lock statement, and Guidelines
- .NET API, System.Threading.ReaderWriterLockSlim, Remarks, Upgrade and downgrade locks
- Go standard library, package sync, type Mutex, Mutex.Lock, Mutex.TryLock and Mutex.Unlock
- Go standard library, package sync, type RWMutex
- Go source, src/internal/sync/mutex.go at go1.27.3, lines 31 to 63 (Mutex fairness and the fast path of Lock) and lines 95 to 149 (lockSlow)
- The Go Programming Language Specification, Defer statements
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), pthread_mutex_lock, DESCRIPTION, the table of mutex types
- Linux manual page, futex(7), DESCRIPTION
- ECMA-262, ECMAScript 2026 Language Specification, 25.4.6 Atomics.compareExchange, 25.4.13 Atomics.wait and 25.4.15 Atomics.notify
- Kotlin standard library, package kotlin.concurrent, withLock, read and write
- PowerShell reference, ForEach-Object, the Parallel parameter, and Notes
- ISO/IEC 9899 working draft N3220 (C23 with editorial changes), 6.10.10.4 Conditional feature macros (__STDC_NO_THREADS__); 7.28.1 Introduction, paragraph 2; 7.28.4.3 The mtx_lock function
- Wikipedia, Peterson's algorithm, the introduction, and Note about hardware
- Linux manual page, flock(1), DESCRIPTION and AVAILABILITY
- Wikipedia, Mutual exclusion, the introduction, and Problem description
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag F9MBDM Edit this page History Report an error Markdown