The Complete Guide to Mutexes, Condition Variables and Locks
One guide to locking in C, C++ and Rust: mutexes, deadlock, condition variables, semaphores, barriers, rwlocks, spinlocks, futexes and debugging.

A mutex makes threads take turns, a condition variable lets a thread sleep until another one changes something, and almost every other lock in this guide is a variation on one of those two ideas. The hard part is not learning the function names. It is knowing what a lock protects, what it does not, how it fails, and how to arrange a program so those failures cannot happen. This guide covers all of it in one place: the race condition that locks exist to prevent, mutexes in C with POSIX threads, in C++ with the standard library and in Rust, deadlock and the rules that avoid it, condition variables and their predicate loop, semaphores and barriers, read-write locks, spinlocks, how the Linux futex sits underneath all of them, priority inversion, the tools that find bugs, and a set of design rules. Code throughout is written for Linux with glibc 2.41, GCC 14 in C17 and C++20 mode, and Rust 1.85, against the POSIX.1-2024 specification. Each section links in spirit to a deeper post in this cluster, and the guide stands alone for a reader who has never locked anything.
What a lock is for
Two threads share a variable. Each adds one to it a million times. The result should be two million, and it is not, because counter++ is three machine steps: load, add, store. When both threads load the same value before either stores, one increment is lost. The language standards call this a data race: two threads access the same memory location, at least one writes, and nothing orders them. In C11 and C++11 and later, a data race is undefined behavior, so the compiler is allowed to assume it never happens, and the program may misbehave in ways that no single interleaving explains.
A lock fixes two separate problems at once, and it is worth keeping them apart.
Atomicity. The region of code between lock and unlock, the critical section, runs without another thread running a critical section guarded by the same lock. The three steps of the increment happen as a unit.
Visibility. Unlocking a mutex and then locking it again from another thread makes the first thread's writes visible to the second. Without that, the compiler may keep a value in a register and the processor may delay a store, and the second thread reads something old. POSIX lists the mutex functions among those that synchronize memory with respect to other threads. C++ states the same through the happens-before relation: an unlock synchronizes with the next lock of the same mutex.
Here is the bug in the smallest complete program:
#include <pthread.h>
#include <stdio.h>
#define N 1000000
static long counter = 0;
static void *work(void *arg) {
(void)arg;
for (int i = 0; i < N; i++)
counter++;
return NULL;
}
int main(void) {
pthread_t a, b;
pthread_create(&a, NULL, work, NULL);
pthread_create(&b, NULL, work, NULL);
pthread_join(a, NULL);
pthread_join(b, NULL);
printf("counter = %ld (expected %d)\n", counter, 2 * N);
return 0;
}counter = 1184302 (expected 2000000)The digits differ on every run and every machine, and the number is below two million. That variability is the signature of a race. A run that happens to print 2000000 is not a pass. It is the same bug, waiting for more cores or a different compiler. Build threaded code with -fsanitize=thread in GCC or Clang during testing, and the sanitizer reports the race even on a run that gets the right answer.
Mutexes in C with POSIX threads
A POSIX mutex is a pthread_mutex_t, declared in <pthread.h>. A mutex with static storage can be initialized with the constant PTHREAD_MUTEX_INITIALIZER. One inside a heap object or on a stack is initialized with pthread_mutex_init and released with pthread_mutex_destroy. The two operations that matter are pthread_mutex_lock, which blocks until the mutex is free and then takes it, and pthread_mutex_unlock. All the pthread_* functions return zero on success and an error number on failure, and they do not set errno, which is the convention of the POSIX threads API.
#include <pthread.h>
#include <stdio.h>
#define N 1000000
static long counter = 0;
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static void *work(void *arg) {
(void)arg;
for (int i = 0; i < N; i++) {
pthread_mutex_lock(&lock);
counter++;
pthread_mutex_unlock(&lock);
}
return NULL;
}
int main(void) {
pthread_t a, b;
pthread_create(&a, NULL, work, NULL);
pthread_create(&b, NULL, work, NULL);
pthread_join(a, NULL);
pthread_join(b, NULL);
printf("counter = %ld (expected %d)\n", counter, 2 * N);
return 0;
}counter = 2000000 (expected 2000000)The result is now deterministic. It is also slower than the broken program, because every increment pays for a lock and an unlock, and when two threads collide on the mutex one of them sleeps. The first lesson about cost is that the lock is cheap when nobody competes for it and expensive when somebody does, and the way to make a locked program fast is to lock less often. If each thread counts privately and adds its total to the shared counter once at the end, the whole run has two lock acquisitions:
static void *work(void *arg) {
(void)arg;
long local = 0;
for (int i = 0; i < N; i++)
local++;
pthread_mutex_lock(&lock);
counter += local;
pthread_mutex_unlock(&lock);
return NULL;
}Put the mutex next to the data
The most useful habit in C is to declare the mutex in the same struct as the data it guards, so the pairing is visible and a function that takes a pointer to the struct has what it needs to lock. A small thread-safe stack shows the shape.
#include <pthread.h>
#include <stdlib.h>
struct node { int value; struct node *next; };
struct stack {
pthread_mutex_t lock; /* guards top and size */
struct node *top;
size_t size;
};
int stack_init(struct stack *s) {
s->top = NULL;
s->size = 0;
return pthread_mutex_init(&s->lock, NULL);
}
int stack_push(struct stack *s, int value) {
struct node *n = malloc(sizeof *n);
if (!n)
return -1;
n->value = value;
pthread_mutex_lock(&s->lock);
n->next = s->top;
s->top = n;
s->size++;
pthread_mutex_unlock(&s->lock);
return 0;
}
int stack_pop(struct stack *s, int *out) {
pthread_mutex_lock(&s->lock);
struct node *n = s->top;
if (!n) {
pthread_mutex_unlock(&s->lock); /* every return path unlocks */
return -1;
}
s->top = n->next;
s->size--;
pthread_mutex_unlock(&s->lock);
*out = n->value;
free(n);
return 0;
}Four details carry the discipline. The malloc happens before the lock, because allocation can be slow and needs no exclusion. Reads need the lock too: a function that returns s->size without locking races with a writer. The early return in stack_pop unlocks before it leaves, and forgetting that unlock is the classic mutex bug, because the next caller hangs forever and the program does not crash, it just stops. And once the node is unlinked, only the caller can reach it, so reading its value and freeing it happen outside the lock, which shortens the critical section.
You may destroy a mutex only when no thread holds it and none can still reach it. Join every worker before you call pthread_mutex_destroy, as POSIX makes destroying a locked mutex undefined.
Mutex types
POSIX defines four mutex types, chosen with pthread_mutexattr_settype before pthread_mutex_init. The default type on glibc behaves like PTHREAD_MUTEX_NORMAL: locking it twice from one thread deadlocks, and unlocking a mutex you do not hold is undefined. The error-checking type turns both into return codes.
| Type | Relock by owner | Unlock by non-owner |
|---|---|---|
PTHREAD_MUTEX_NORMAL | Deadlock | Undefined |
PTHREAD_MUTEX_ERRORCHECK | Returns EDEADLK | Returns EPERM |
PTHREAD_MUTEX_RECURSIVE | Succeeds and counts | Returns EPERM |
Use error-checking mutexes in debug builds, because a hang becomes an error code you can assert on. Treat recursive mutexes as a last resort. A function that locks a mutex does so to protect an invariant that is temporarily broken inside the critical section, and a recursive lock lets code that runs in that broken state call another function that also locks, which then proceeds as if the invariant held. A non-recursive mutex would deadlock and show you the design flaw. The better structure is a public function that locks and a private helper, named with a suffix such as _locked, that assumes the lock is held. One more reason to avoid recursion: pthread_cond_wait on a recursive mutex locked more than once is undefined, because the wait releases only one level.
A fourth attribute, robust mutexes, handles a thread that dies while holding the lock. The next locker gets the return value EOWNERDEAD, repairs the data, and calls pthread_mutex_consistent. It matters mainly for mutexes in shared memory between processes.
Mutexes in C++
C++ makes forgetting to unlock impossible by tying the unlock to scope. std::mutex provides lock and unlock, and you should almost never call them directly. Instead, std::lock_guard locks in its constructor and unlocks in its destructor, which runs on a normal return, an early return and an exception.
#include <iostream>
#include <mutex>
#include <stdexcept>
#include <thread>
#include <vector>
std::mutex m;
std::vector<int> data;
void add_checked(int v) {
std::lock_guard<std::mutex> g(m);
if (v < 0)
throw std::invalid_argument("negative");
data.push_back(v);
}
int main() {
std::thread t1([] { for (int i = 0; i < 1000; i++) add_checked(i); });
std::thread t2([] { for (int i = 0; i < 1000; i++) add_checked(i); });
t1.join();
t2.join();
try {
add_checked(-1);
} catch (const std::invalid_argument &e) {
std::cout << "caught: " << e.what() << "\n";
}
add_checked(7);
std::cout << "size = " << data.size() << "\n";
}caught: negative
size = 2001With manual m.lock() and m.unlock(), the throw would leave the mutex locked and the last call would hang. Two traps are worth knowing. Always name the guard: std::lock_guard<std::mutex>(m); without a name declares a variable called m and locks nothing useful. And limit the guard's scope with a block when the critical section is shorter than the function, since the guard unlocks only at the closing brace.
A thread-safe class
Keep the mutex as a private member next to the data, take a guard in each public method, and make every check-and-update a single critical section.
#include <iostream>
#include <mutex>
#include <thread>
class Account {
public:
void deposit(long cents) {
std::lock_guard<std::mutex> g(m_);
balance_ += cents;
}
bool withdraw(long cents) {
std::lock_guard<std::mutex> g(m_);
if (balance_ < cents)
return false;
balance_ -= cents;
return true;
}
long balance() const {
std::lock_guard<std::mutex> g(m_);
return balance_;
}
private:
mutable std::mutex m_;
long balance_ = 0;
};
int main() {
Account acct;
auto work = [&acct] { for (int i = 0; i < 100000; i++) acct.deposit(1); };
std::thread a(work), b(work);
a.join();
b.join();
std::cout << "balance = " << acct.balance() << "\n";
}balance = 200000Notice that withdraw checks and subtracts under one lock. Splitting that into a public balance() call followed by a separate subtract would let another thread change the balance between the two. The design rule that falls out is that a thread-safe class exposes operations, not getters and setters that callers combine. mutable on the mutex lets a const method lock, since locking changes the mutex and not the object's logical value.
std::unique_lock is the more flexible guard. It can unlock early, be constructed without locking, and it is the type std::condition_variable requires. Use lock_guard by default and unique_lock when you need one of those capabilities. std::mutex is not recursive, and locking it twice in one thread is undefined behavior.
Mutexes in Rust
Rust takes a different approach: the mutex owns the data. std::sync::Mutex<T> holds a T, and the only way to reach the value is through the guard that lock() returns, so you cannot touch the data without holding the lock. To share a mutex among threads, wrap it in Arc, the atomic reference-counted pointer.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0u32));
let mut handles = Vec::new();
for _ in 0..4 {
let counter = Arc::clone(&counter);
handles.push(thread::spawn(move || {
for _ in 0..1000 {
let mut n = counter.lock().unwrap();
*n += 1;
}
}));
}
for h in handles {
h.join().unwrap();
}
println!("total = {}", *counter.lock().unwrap());
}total = 4000The compiler enforces the discipline. A plain Rc is rejected because it is not Send, a bare reference is rejected because a spawned thread needs a 'static closure, and mutating through an Arc without a Mutex is rejected because shared access is read-only. The data race becomes a compile error. lock() returns a Result because of poisoning: if a thread panics while holding the guard, the mutex is marked poisoned so that later lockers know the data may be half-updated. unwrap() turns that into a panic in the second thread, a fail-fast policy that is often right, and PoisonError::into_inner returns the guard if you decide to recover. Keep code that can panic outside the critical section and poisoning rarely matters. For a single shared integer an AtomicU32 avoids the lock entirely.
Deadlock
A deadlock is a set of threads each waiting for something another holds. Four conditions must all hold for one to occur, listed by Coffman and colleagues in 1971: mutual exclusion, hold and wait, no preemption, and circular wait. Removing any one prevents the deadlock, and in practice the one you can remove is circular wait.
The textbook case is a transfer between two accounts, each with its own mutex.
#include <mutex>
#include <thread>
struct Account {
std::mutex m;
long balance = 1000;
};
void transfer(Account &from, Account &to, long amount) {
std::lock_guard<std::mutex> a(from.m);
std::lock_guard<std::mutex> b(to.m);
from.balance -= amount;
to.balance += amount;
}
int main() {
Account x, y;
std::thread t1([&] { for (int i = 0; i < 100000; i++) transfer(x, y, 1); });
std::thread t2([&] { for (int i = 0; i < 100000; i++) transfer(y, x, 1); });
t1.join();
t2.join();
}Thread one locks x then y, thread two locks y then x. When each has taken its first lock before either takes its second, both wait forever. On many runs the program finishes. On others it hangs. A hang that appears only under load is characteristic of lock-order bugs.
There are three standard cures, in increasing order of convenience.
A global lock order. Always lock the account with the lower address, or lower id, first. It works and it must be applied everywhere, which is why it fails in large codebases.
std::lock and std::scoped_lock. C++17 added std::scoped_lock, which locks several mutexes with a deadlock-avoidance algorithm and unlocks them all in its destructor.
void transfer(Account &from, Account &to, long amount) {
if (&from == &to)
return; // locking one mutex twice is undefined
std::scoped_lock lk(from.m, to.m);
from.balance -= amount;
to.balance += amount;
}The argument order no longer matters. Note the self-transfer guard: passing the same non-recursive mutex twice is undefined behavior, and the call looks harmless in review.
Try-lock with backoff. When you cannot take all locks up front, lock the first, try_lock the second, and if that fails release the first and start over after a short delay. It is livelock-prone without randomized backoff, and it is what std::lock does internally in a controlled way.
Two further rules prevent the rest. Never call unknown code while holding a lock: a callback, a virtual method or a logging call may take another lock in the opposite order. And keep a documented hierarchy when locks nest, so every thread takes them from top to bottom.
To diagnose a hang, attach a debugger with gdb -p <pid> and run thread apply all bt. Two threads whose top frames are inside pthread_mutex_lock, each called from a function that holds a different mutex, show the cycle. ThreadSanitizer includes a lock-order-inversion detector that reports a potential deadlock when it sees locks taken in opposite orders in different places, even if the run never hung.
Condition variables
A mutex answers who may touch the data. It does not answer when there is something worth touching. A thread that wants a job from a shared queue has two bad options: poll in a loop that burns a core, or sleep for a guessed interval and add latency. A condition variable lets the thread sleep until another thread says the state changed.
A condition variable stores no value. It is a queue of sleeping threads, with three operations: wait, which atomically releases the mutex and sleeps and then relocks the mutex before returning, signal, which wakes at least one waiter, and broadcast, which wakes all. The word atomically matters: if the unlock and the sleep were separate steps, a signal could arrive between them and be lost. And because a signal is not remembered, the real condition must live in a variable you own, protected by the mutex.
The shape of every correct wait is a loop:
pthread_mutex_lock(&m);
while (!condition_is_true)
pthread_cond_wait(&cond, &m);
/* condition is true and m is held */
pthread_mutex_unlock(&m);Three rules sit in those four lines. Hold the mutex when you wait. Test the predicate under the same mutex the signaling thread uses when it changes the state. And wait in a while loop, never an if.
Why the loop
The loop covers two different situations. A spurious wakeup is when the wait returns although no one signaled, which POSIX and C++ both allow, and which implementations can produce through interrupted system calls. More important in practice is the stolen wakeup. The condition becomes true and a waiter is woken, but it must reacquire the mutex before returning, and another thread that was not waiting can take the mutex first, consume the state and leave. The woken thread finally gets the mutex and finds the condition false again. With an if it proceeds anyway and pops from an empty queue. With a while it rechecks and sleeps again. No spurious wakeup is involved, and the bug is still real on every platform.
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cv = PTHREAD_COND_INITIALIZER;
static int items = 0;
static void *consumer(void *arg) {
int id = *(int *)arg;
pthread_mutex_lock(&lock);
if (items == 0) /* BUG: should be while */
pthread_cond_wait(&cv, &lock);
items--;
printf("consumer %d took an item, items = %d\n", id, items);
pthread_mutex_unlock(&lock);
return NULL;
}
int main(void) {
pthread_t c[2];
int ids[2] = {1, 2};
pthread_create(&c[0], NULL, consumer, &ids[0]);
pthread_create(&c[1], NULL, consumer, &ids[1]);
sleep(1); /* both are waiting */
pthread_mutex_lock(&lock);
items = 1;
pthread_cond_broadcast(&cv); /* wakes both, only one item */
pthread_mutex_unlock(&lock);
pthread_join(c[0], NULL);
pthread_join(c[1], NULL);
return 0;
}consumer 1 took an item, items = 0
consumer 2 took an item, items = -1The broadcast wakes both consumers for one item, and the second decrements items to minus one. The order of the two lines can vary, and the bug does not. Change the if to while and the second consumer rechecks and waits again.
In C++ the predicate overload runs the loop for you. The standard defines cv.wait(lock, pred) as equivalent to while (!pred()) cv.wait(lock);, so prefer it.
A complete bounded queue
A producer-consumer queue with a fixed capacity needs two predicates, so it uses two condition variables: consumers wait while the queue is empty, producers wait while it is full. Giving each its own condition variable means a signal reaches a thread that can use it.
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>
class BoundedQueue {
public:
explicit BoundedQueue(std::size_t cap) : cap_(cap) {}
bool put(int v) {
std::unique_lock<std::mutex> lk(m_);
not_full_.wait(lk, [this] { return q_.size() < cap_ || closed_; });
if (closed_)
return false;
q_.push(v);
not_empty_.notify_one();
return true;
}
bool get(int &out) {
std::unique_lock<std::mutex> lk(m_);
not_empty_.wait(lk, [this] { return !q_.empty() || closed_; });
if (q_.empty())
return false; // closed and drained
out = q_.front();
q_.pop();
not_full_.notify_one();
return true;
}
void close() {
{
std::lock_guard<std::mutex> g(m_);
closed_ = true;
}
not_empty_.notify_all();
not_full_.notify_all();
}
private:
std::mutex m_;
std::condition_variable not_empty_, not_full_;
std::queue<int> q_;
std::size_t cap_;
bool closed_ = false;
};
int main() {
BoundedQueue q(8);
long sum[2] = {0, 0};
std::vector<std::thread> consumers, producers;
for (int c = 0; c < 2; c++)
consumers.emplace_back([&, c] {
int v;
while (q.get(v))
sum[c] += v;
});
for (int p = 0; p < 3; p++)
producers.emplace_back([&q, p] {
for (int i = 1; i <= 1000; i++)
q.put(p * 10000 + i);
});
for (auto &t : producers)
t.join();
q.close();
for (auto &t : consumers)
t.join();
std::cout << "consumed sum = " << sum[0] + sum[1] << "\n";
}consumed sum = 31501500Three producers send p * 10000 + i for i from 1 to 1000. Each producer's sum is 1000 * (p * 10000) + 500500, and over p of 0, 1 and 2 that is 500,500 plus 10,500,500 plus 20,500,500, which is 31,501,500. The total is the same on every run, whichever consumer takes which item. Shutdown deserves a note: close sets the flag under the mutex and broadcasts, consumers drain remaining items and return false only when the queue is closed and empty, and the main thread joins the producers before closing so that every item is delivered.
Timed waits exist for the case where waiting forever is wrong. pthread_cond_timedwait takes an absolute deadline as a struct timespec and returns ETIMEDOUT when it passes, and C++ has wait_for and wait_until. The default POSIX clock is CLOCK_REALTIME, which can jump when someone adjusts the system time, so set CLOCK_MONOTONIC with pthread_condattr_setclock when you need a deadline that is immune to that.
A signal may be sent inside or outside the lock, and both are correct. The change to the shared state must happen under the lock either way, and that holds even if the state is a std::atomic, because the waiter's predicate check and its sleep have to be ordered with respect to the change.
Semaphores
A counting semaphore holds a non-negative integer with two operations: wait decrements it, blocking at zero, and post increments it and wakes a waiter. Unlike a mutex, it has no owner, so the thread that posts need not be the thread that waited. Unlike a condition variable, it remembers: a post before a wait leaves the count at one, so no wake-up is lost and no separate predicate variable is needed. POSIX provides sem_init, sem_wait, sem_post, sem_trywait and sem_timedwait in <semaphore.h>. These return minus one and set errno, unlike the pthread_* functions, and sem_wait can fail with EINTR when a signal handler interrupts it, so loop on it.
The classic use is limiting concurrent access to a resource, such as at most three database connections at once.
#include <errno.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <unistd.h>
#define WORKERS 6
#define MAX_CONN 3
static sem_t conn_slots;
static pthread_mutex_t out = PTHREAD_MUTEX_INITIALIZER;
static int active = 0, peak = 0;
static void *worker(void *arg) {
(void)arg;
while (sem_wait(&conn_slots) == -1 && errno == EINTR)
;
pthread_mutex_lock(&out);
active++;
if (active > peak)
peak = active;
pthread_mutex_unlock(&out);
usleep(100000); /* use the connection */
pthread_mutex_lock(&out);
active--;
pthread_mutex_unlock(&out);
sem_post(&conn_slots);
return NULL;
}
int main(void) {
pthread_t t[WORKERS];
sem_init(&conn_slots, 0, MAX_CONN);
for (int i = 0; i < WORKERS; i++)
pthread_create(&t[i], NULL, worker, NULL);
for (int i = 0; i < WORKERS; i++)
pthread_join(t[i], NULL);
printf("peak concurrent connections = %d\n", peak);
sem_destroy(&conn_slots);
return 0;
}peak concurrent connections = 3A semaphore does not protect data, it counts permits. A binary semaphore used as a mutex has no ownership check and no priority inheritance, and a stray extra post turns it into a count of two, so use a mutex for mutual exclusion. A pair of semaphores can hand items between two threads, and sem_post is on the list of async-signal-safe functions, which makes it the standard way to wake a thread from a signal handler. C++20 added std::counting_semaphore and std::binary_semaphore in <semaphore> with the same ideas.
Barriers and latches
Parallel algorithms often run in phases: every thread computes its slice, and no thread may start the next phase until all have finished this one. A barrier is the rendezvous. POSIX provides pthread_barrier_init, pthread_barrier_wait and pthread_barrier_destroy. pthread_barrier_wait returns PTHREAD_BARRIER_SERIAL_THREAD to exactly one released thread and zero to the others, which is handy for once-per-phase work. Writes made before the call are visible to every thread after it, and the barrier resets for the next round, so one object serves a loop.
#include <pthread.h>
#include <stdio.h>
#define THREADS 4
#define N 1000
static int data[N];
static long partial[THREADS];
static long total;
static pthread_barrier_t barrier;
static void *worker(void *arg) {
int id = (int)(long)arg;
int lo = id * (N / THREADS), hi = lo + (N / THREADS);
long s = 0;
for (int i = lo; i < hi; i++)
s += data[i];
partial[id] = s; /* phase one */
if (pthread_barrier_wait(&barrier) == PTHREAD_BARRIER_SERIAL_THREAD) {
for (int i = 0; i < THREADS; i++) /* phase two, once */
total += partial[i];
}
return NULL;
}
int main(void) {
for (int i = 0; i < N; i++)
data[i] = i + 1;
pthread_barrier_init(&barrier, NULL, THREADS);
pthread_t t[THREADS];
for (long i = 0; i < THREADS; i++)
pthread_create(&t[i], NULL, worker, (void *)i);
for (int i = 0; i < THREADS; i++)
pthread_join(t[i], NULL);
pthread_barrier_destroy(&barrier);
printf("total = %ld\n", total);
return 0;
}total = 500500The barrier's count must equal the number of threads that will call it. If a thread exits early on an error before reaching the barrier, the others block forever, so error paths must still arrive, typically by setting a shared failure flag that every thread checks after the barrier. Barriers are optional in POSIX and missing on some platforms such as macOS. C++20 provides std::barrier, which takes a completion function that runs once per phase, and std::latch, a single-use countdown for the "wait until N things are done" case.
Read-write locks
A mutex treats readers like writers. For data that is read constantly and changed rarely, that wastes parallelism, because two threads that only read cannot interfere. A read-write lock allows any number of readers at once or exactly one writer. POSIX has pthread_rwlock_t with pthread_rwlock_rdlock, pthread_rwlock_wrlock and a single pthread_rwlock_unlock, and C++17 has std::shared_mutex with std::shared_lock for readers and std::unique_lock for writers.
#include <iostream>
#include <map>
#include <mutex>
#include <shared_mutex>
#include <string>
#include <thread>
#include <vector>
class Registry {
public:
int get(const std::string &k) const {
std::shared_lock<std::shared_mutex> lk(m_); // many readers at once
auto it = map_.find(k);
return it == map_.end() ? -1 : it->second;
}
void set(const std::string &k, int v) {
std::unique_lock<std::shared_mutex> lk(m_); // exclusive
map_[k] = v;
}
private:
mutable std::shared_mutex m_;
std::map<std::string, int> map_;
};
int main() {
Registry r;
r.set("limit", 10);
std::vector<std::thread> readers;
std::vector<long> hits(3, 0);
for (int i = 0; i < 3; i++)
readers.emplace_back([&r, &hits, i] {
for (int n = 0; n < 100000; n++)
hits[i] += r.get("limit");
});
std::thread writer([&r] { for (int n = 0; n < 100; n++) r.set("limit", 10); });
for (auto &t : readers)
t.join();
writer.join();
std::cout << "total = " << hits[0] + hits[1] + hits[2] << "\n";
}total = 3000000Three rules keep read-write locks correct. Code under a read lock must not modify the data, including a statistics counter, or two readers race on it. There is no upgrade from read to write: taking the write lock while holding the read lock deadlocks, so release, take the write lock and recheck the condition. And the lock's preference policy matters. glibc's default prefers readers, so a steady stream of overlapping readers can starve a writer, and PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP changes that. A read-write lock does more bookkeeping per acquisition than a mutex, so it wins only when the read-side work is long enough for parallelism to matter and writes are rare. Measure before switching.
Spinlocks and what is underneath
A mutex sleeps while it waits. A spinlock keeps the thread on the CPU in a loop until the lock is free. Spinning costs cycles and avoids the system call and context switch, so it wins only when the critical section is a few instructions and the holder is certainly running. In user space the holder can be preempted at any point, and then every spinner burns a time slice for nothing, so a user-space spinlock is rarely the right choice outside pinned, one-thread-per-core designs. Inside the Linux kernel, spinlocks disable preemption while held, which is what makes them safe there and why code under one must not sleep.
A glibc mutex is built on the futex system call. The lock is a 32-bit integer in user memory. An uncontended lock is one atomic compare-and-swap with no kernel entry. Only when a thread finds the mutex held does it call futex(FUTEX_WAIT), which sleeps it on that address if the value is still what it expected, and unlock calls FUTEX_WAKE only if there are waiters. A minimal three-state version, zero for unlocked, one for locked and two for locked with waiters, fits in a few lines.
#define _GNU_SOURCE
#include <linux/futex.h>
#include <stdatomic.h>
#include <sys/syscall.h>
#include <unistd.h>
typedef struct { atomic_int state; } fmutex_t;
static long futex_wait(atomic_int *a, int expected) {
return syscall(SYS_futex, a, FUTEX_WAIT_PRIVATE, expected, NULL, NULL, 0);
}
static long futex_wake(atomic_int *a, int n) {
return syscall(SYS_futex, a, FUTEX_WAKE_PRIVATE, n, NULL, NULL, 0);
}
static void fmutex_lock(fmutex_t *m) {
int c = 0;
if (atomic_compare_exchange_strong_explicit(&m->state, &c, 1,
memory_order_acquire, memory_order_relaxed))
return; /* fast path: no kernel */
if (c != 2)
c = atomic_exchange_explicit(&m->state, 2, memory_order_acquire);
while (c != 0) {
futex_wait(&m->state, 2);
c = atomic_exchange_explicit(&m->state, 2, memory_order_acquire);
}
}
static void fmutex_unlock(fmutex_t *m) {
if (atomic_exchange_explicit(&m->state, 0, memory_order_release) == 2)
futex_wake(&m->state, 1);
}This is for understanding, not for production: it has no owner, no recursion, no robustness and no priority inheritance. Run a program that uses it under strace -f -e trace=futex and you see futex calls only when threads collide, and none at all with a single thread, which is the whole point of the design. The kernel side hashes the futex key to a bucket of waiters and rechecks the user word under the bucket lock before sleeping, so a wake cannot be lost.
Priority inversion
On a real-time system a high-priority thread H can wait for a mutex held by a low-priority thread L while a medium-priority thread M, which needs no lock, preempts L. H is then effectively running at the lowest priority for as long as M wants the CPU. This is priority inversion, and it famously reset the Mars Pathfinder lander in 1997 until the mutex was configured to avoid it.
The fix is priority inheritance: while L holds the mutex, it runs at the highest priority of any thread blocked on it. In POSIX you ask for it with pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT) before initializing the mutex, which on Linux uses priority-inheritance futexes backed by the kernel's rt_mutex. It matters only under a real-time scheduling policy such as SCHED_FIFO, where fixed priorities exist. A priority ceiling, PTHREAD_PRIO_PROTECT, is the alternative: the holder runs at a fixed ceiling priority while it holds the lock. Neither shortens a long critical section, so keep them short.
How a lock orders memory
It helps to know why a lock gives visibility, because the same reasoning explains every other primitive in this guide. Modern compilers and processors reorder memory accesses and delay stores for speed, and each core has its own caches. Two threads that touch the same variable with no synchronization have no agreed order of events, which is what makes a data race undefined.
A mutex establishes an order through a pair of one-way barriers. Locking is an acquire operation: no read or write inside the critical section may move to before it. Unlocking is a release operation: no read or write inside the critical section may move to after it. When thread B locks a mutex that thread A just unlocked, A's release synchronizes with B's acquire, and everything A wrote before unlocking happens before everything B does after locking. That sentence is the whole contract. It is why you can write a plain, non-atomic long inside a critical section and read it in another thread's critical section with no further care, and it is why reading the same long outside any lock is a race even if you only look at it.
The same pair explains the other tools. A condition variable wait releases the mutex and reacquires it, so the waiter sees the state that the signaler wrote under the lock. A semaphore post is a release and a successful wait is an acquire. A barrier makes every thread's earlier writes visible to every thread after the rendezvous. A thread join makes everything the joined thread did visible to the joiner, and a thread creation makes everything before pthread_create visible to the new thread. If you are ever unsure whether two accesses are ordered, look for one of these pairs between them. If you cannot find one, there is a race.
One consequence surprises people: a lock protects data by convention, not by enforcement. Nothing in C or C++ stops a thread from touching the shared variable without taking the mutex. The protection exists only because every access follows the rule, which is why the earlier advice to keep the mutex next to the data and expose operations, not raw fields, matters. Rust is the exception, since the mutex owns the value and the type system refuses unlocked access.
Granularity: coarse locks, fine locks and no locks
How much data one lock covers is the main design decision after "do I need a lock at all". A coarse lock covers a whole structure: one mutex for the whole table. It is simple, easy to reason about and hard to get wrong, and it serializes every operation, so throughput stops growing as threads are added. A fine-grained design uses many locks over parts of the structure: one per bucket, one per node, one per account. It allows more parallelism and brings more ways to fail, since several locks mean lock ordering, and deadlock becomes possible.
The sound path is to start coarse and measure. Write the structure with one lock, make it correct, put it under a realistic load, and look at whether threads actually wait. The tools in the debugging section tell you which lock is hot and how much of the run is spent waiting for it. If the wait share is small, you are done, and a simpler design is worth more than a faster one nobody needs. If it is large, there are four moves, in rough order of risk.
Shorten the critical section. Move allocation, I/O and computation outside, and copy data out under the lock if the work on it is slow. This is almost always the first and best fix.
Shard the data. Split a hash table into N independent tables, each with its own mutex, and pick the shard from the key's hash. Two threads collide only when they touch the same shard. Sharding keeps each lock simple and avoids nested locking, which is why it beats fine-grained per-node locking in most programs. The number of shards should be a few times the number of threads, and each shard's mutex should sit on its own cache line, since false sharing between adjacent mutexes defeats the point.
Switch the lock type. A read-write lock for read-mostly data, or an atomic for a single word, as the earlier sections describe.
Move to a lock-free structure. Only for the case where a lock is provably the bottleneck or where blocking is forbidden, such as a signal handler.
#include <array>
#include <functional>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
class ShardedMap {
public:
void add(const std::string &k, long delta) {
Shard &s = shard_for(k);
std::lock_guard<std::mutex> g(s.m);
s.map[k] += delta;
}
long get(const std::string &k) {
Shard &s = shard_for(k);
std::lock_guard<std::mutex> g(s.m);
auto it = s.map.find(k);
return it == s.map.end() ? 0 : it->second;
}
private:
struct alignas(64) Shard {
std::mutex m;
std::unordered_map<std::string, long> map;
};
Shard &shard_for(const std::string &k) {
return shards_[std::hash<std::string>{}(k) % shards_.size()];
}
std::array<Shard, 16> shards_;
};
int main() {
ShardedMap sm;
std::vector<std::thread> ts;
for (int t = 0; t < 4; t++)
ts.emplace_back([&sm] {
for (int i = 0; i < 10000; i++)
sm.add("key" + std::to_string(i % 100), 1);
});
for (auto &t : ts)
t.join();
std::cout << "key7 = " << sm.get("key7") << "\n";
}key7 = 400Each of the four threads adds one to key7 a hundred times, so the total is 400, whichever shard thread timing visits first. Sixteen shards means threads working on different keys usually take different mutexes. The alignas(64) keeps each shard on its own cache line, and the total memory cost is small.
Testing locked code
Concurrent code is tested differently from sequential code, because a passing test proves little. Three practices give most of the value.
Test an invariant, not an output. Run many operations from many threads and check a property that must hold at the end: the count of items out equals the count in, the sum matches, every key is present exactly once. Write the property down before writing the code, since it is the specification.
Create adversarial schedules. Use more threads than cores so the scheduler preempts threads in the middle of critical sections, run long enough for rare interleavings to occur, and add short sched_yield or std::this_thread::yield calls inside critical sections in a test build to widen the windows in which races happen. A race that appears once in a billion operations on your laptop may appear once a minute on a production machine with different timing.
Run under the sanitizers on every build. ThreadSanitizer runs about an order of magnitude slower than normal execution and uses several times the memory, which is acceptable for a test job. Keep it on in continuous integration. When it reports a race, treat it as real: the cost of ignoring a sanitizer warning is a production failure that is hard to reproduce.
Finding bugs
Tools find lock bugs that tests do not.
| Tool | Finds | How |
|---|---|---|
ThreadSanitizer, -fsanitize=thread | Data races, lock-order inversions | Instruments memory accesses and lock calls at compile time |
Helgrind, valgrind --tool=helgrind | Data races, lock misuse, ordering | Runs the unmodified binary under emulation, much slower |
gdb -p, thread apply all bt | Where a hung process is stuck | Shows every thread's stack |
| Error-checking mutexes | Relock and bad unlock | Return EDEADLK and EPERM instead of hanging |
| Kernel lockdep | Lock-order and context errors in the kernel | Tracks lock classes at run time |
mutrace, perf lock contention | Which lock is hot | Counts and times contention |
A clean sanitizer run is evidence, not proof, since it sees only the interleavings that occurred. Write stress tests with more threads than cores, so the scheduler preempts threads mid-operation, and with an invariant to check at the end, such as the sum of all items.
Design rules that prevent most problems
A short list covers most of what goes wrong.
Name what each lock protects, in a comment next to its declaration, and keep it next to the data. If two readers of the code would disagree about which variables a mutex guards, the design is already in trouble.
Keep critical sections short. Do the allocation, the I/O, the logging and the computation outside, and hold the lock only for the memory updates that need exclusion. Never hold a lock across a call you do not control.
Take locks in one fixed order, or take them all at once with std::scoped_lock. Never acquire a second lock while holding a first one in code that other paths call in the opposite order.
Make check-and-update a single operation. Expose methods like withdraw that test and change under one lock, not separate getters and setters that callers combine.
Wait in a loop on a predicate. Change the state under the same mutex the waiter uses, then signal.
Prefer scope-based locking, such as std::lock_guard or the Rust guard, and in C use a single exit path with one unlock, or a goto out idiom.
Share less. The cheapest lock is the one you do not take: give each thread its own data and merge at the end, or hand work between threads through a queue so that only the queue is shared.
Choosing the tool
| Need | Use |
|---|---|
| One thread at a time touches this data | Mutex |
| Wait until a condition on shared state holds | Condition variable with a mutex and a predicate loop |
| At most N threads use a resource, or count events | Counting semaphore |
| All threads finish a phase before any continues | Barrier |
| Many readers, rare writers, long read sections | Read-write lock |
| A critical section of a few instructions, pinned threads | Spinlock |
| A single shared integer or flag | Atomic variable |
| Real-time threads sharing a lock | Mutex with priority inheritance |
| Threads need not share state at all | Message passing or a queue |
Where locks stop
Locks have costs that no tuning removes. Every lock is a point where a stalled thread can stall everyone, so a thread descheduled while holding one, or killed, blocks the rest. Locks do not compose: two correct thread-safe objects used together can still deadlock or violate an invariant that spans both. Contended locks serialize work, and Amdahl's law says the serial part limits speedup no matter how many cores you add.
When those costs dominate, the alternatives are atomics for a single word, ownership transfer through queues so that a thread has exclusive access without a lock, and lock-free data structures, which guarantee that some thread always makes progress. Lock-free structures are much harder to write and verify, require a memory reclamation scheme, and often are not faster, so reach for them only after a measurement shows the lock is the bottleneck. The cornerstone guide on lock-free data structures in this cluster covers that territory. A good program keeps its locks simple, short and few, and treats each one as a design decision.


