arthrop0d

Brief articles on varied topics.

Linux Futexes and User-Space Synchronization

linuxoperating systemsconcurrency

A futex (fast userspace mutex) is a Linux synchronization mechanism built around a shared 32-bit integer: threads inspect and change that integer in user space, entering the kernel only when they must wait or wake another thread. This lets an uncontended mutex or condition variable avoid a system call entirely.

The problem futexes solve

A mutex protects shared data by allowing only one thread into a critical section at a time. Most lock operations are uncontended: the lock is free when a thread tries to acquire it, or becomes free before anyone needs to sleep. Paying for a kernel transition on every lock and unlock would make this common path unnecessarily expensive.

Before futexes, a synchronization library generally had to involve the kernel more directly whenever it managed a lock. The kernel is good at scheduling threads, but entering it, validating state, and switching between runnable and sleeping threads costs more than a few atomic instructions in user space.

Futexes divide the job:

The futex itself is not normally a complete mutex object. It is a kernel service associated with an aligned 32-bit value in memory. A library such as pthread_mutex or pthread_cond uses that value as a compact coordination point.

The uncontended mutex path

Imagine a mutex whose futex word contains 0 for unlocked and 1 for locked. A thread acquiring it attempts an atomic compare-and-exchange: change 0 to 1, but only if the value is still 0.

If the operation succeeds, the thread owns the mutex. No system call occurred. The CPU's atomic instruction both checks and updates the word so that two threads cannot both observe the lock as free and claim it.

Unlocking can also be a user-space operation. The owner atomically changes the word back to an unlocked state. If the implementation knows that no thread is waiting, it does not need to notify the kernel at all.

Real implementations use more states and optimizations than this simplified example. For instance, a state may record that there are possible waiters, allowing unlock to decide whether a wake operation is needed. The principle remains the same: an atomic read-modify-write handles the fast path; the kernel is reserved for waiting.

Contention moves waiting into the kernel

Suppose a second thread tries to acquire the locked mutex. Its atomic attempt fails. It must not simply keep retrying forever: repeatedly checking the word is spinning, and can waste a CPU while the owner is descheduled or performs slow work.

The thread can instead use the futex wait operation. It supplies:

  1. the address of the futex word,
  2. the value it expects to see, and
  3. optionally, a timeout.

The kernel checks the word again and sleeps the thread only if the value still matches the expected value. That check is part of the wait operation, not a separate user-space check followed by a sleep.

That detail prevents a lost wakeup: a notification that happens before a waiter has actually gone to sleep. Without the atomic check-and-sleep behavior, the owner could unlock and wake waiters in the small gap after the second thread checked the lock but before it entered the kernel. The second thread would then sleep despite the lock already being available.

Conceptually, the slow path looks like this:

if (atomic_compare_exchange(&mutex_word, 0, 1)) {
    // Acquired without entering the kernel.
} else {
    // Retry the state check as needed, then ask the kernel to wait
    // while mutex_word still has the locked value.
    futex_wait(&mutex_word, locked_value);
}

The actual futex system call is exposed as the futex operation with commands such as FUTEX_WAIT and FUTEX_WAKE; threading libraries wrap these details and add the required retry and memory-ordering logic.

When the owner unlocks, it updates the word with release semantics. Memory ordering is the rule that controls when one thread's reads and writes become visible relative to its synchronization operations. The release operation ensures that writes inside the critical section become visible before another thread successfully acquires the mutex.

If waiters may exist, the owner issues a futex wake operation. FUTEX_WAKE asks the kernel to make one or more threads waiting on that futex runnable. It does not transfer ownership directly and does not guarantee which particular waiter runs next. A woken thread returns to user space, retries the atomic acquisition, and proceeds only if it actually obtains the lock.

A wakeup means “the condition may have changed,” not “you now own the mutex.”

The kernel maintains the wait queue: a data structure containing sleeping threads associated with a wait condition. It handles putting a thread to sleep, removing it when woken or timed out, and making it eligible to run again. The lock's normal ownership state still lives in user memory.

Condition variables use the same split

A condition variable lets a thread sleep until some application-defined condition becomes true, such as “the queue is no longer empty.” The condition itself is ordinary shared state; the condition variable supplies an efficient way to wait for changes to it.

The waiting thread must hold a mutex while checking the predicate, then perform a coordinated operation that releases the mutex and begins waiting. This coordination matters: another thread can update the predicate and signal immediately after the mutex is released. The condition-variable implementation uses a futex state and kernel wait queue so that this transition does not lose the signal.

A typical pattern is:

lock(&mutex);
while (queue_is_empty()) {
    condition_wait(&not_empty, &mutex);
}
item = remove_item();
unlock(&mutex);

The while loop is required. A waiter can wake because another thread signaled, because several waiters competed for the mutex, because of a timeout or interruption, or because the implementation permits a spurious wakeup—a return from waiting without the predicate being true. After waking, it reacquires the mutex and checks the actual predicate again.

A signaling thread changes the shared state while holding the mutex, then signals one waiter or broadcasts to all relevant waiters. The library may use futex wake operations directly, often with sequence counters or other state encodings to distinguish new notifications from old ones.

Where the term appears in practice

A thread dump showing futex_wait, futex_wait_queue_me, or a stack frame inside pthread_mutex_lock often means the thread is blocked on synchronization rather than actively using the CPU. That is not automatically a bug: sleeping is the intended behavior under contention. The engineering question is whether the wait is brief and expected, or whether lock ownership, scheduling, I/O, or a missed application-level condition is keeping other threads blocked.

Futexes are therefore best understood as a boundary: atomic user-space state for the fast path, and a kernel-managed wait queue for the slow path. That boundary gives common mutex and condition-variable operations low overhead without requiring the kernel to understand every application-specific lock or predicate.

← All articles