arthrop0d

Brief articles on varied topics.

Linux Futexes and the Contended Lock Path

linuxconcurrencyoperating systems

A futex—short for “fast userspace mutex”—is a Linux mechanism that lets a lock be managed in user space when uncontended, then lets the kernel put waiting threads to sleep when contention requires it. The common path is an atomic memory operation; a system call is needed only when a thread cannot make progress immediately.

The problem futexes solve

A lock protects shared state so that only one thread changes it at a time. The usual fast case is simple: the lock is free, and the arriving thread takes it. If taking a lock always required entering the kernel, even this uncontended case would pay for a system-call transition, argument handling, and kernel bookkeeping.

Before futex-style designs, a user-space lock could spin—repeatedly checking until the owner released it—or rely on a kernel-backed object for every operation. Spinning wastes CPU when the owner will take a while. Kernel entry avoids that waste but adds overhead to every acquisition.

A futex separates these cases:

The shared word is normally a naturally aligned 32-bit integer in memory visible to all participating threads. The futex system call does not itself contain the lock state. It uses the address of that word to coordinate sleeping and waking.

The fast path is ordinary shared memory

A lock implementation can represent 0 as unlocked and 1 as locked. To acquire it, a thread performs an atomic compare-and-exchange: change 0 to 1, but only if the value is still 0.

if (atomic_compare_exchange_strong(&lock_word, &expected, 1)) {
    /* Acquired: no system call was needed. */
    use_shared_data();
    atomic_store(&lock_word, 0);
} else {
    /* Another thread owns it; enter the slow path. */
}

The real implementation must also arrange the correct memory ordering: operations inside the critical section must become visible to a later owner, and the lock acquisition must not be reordered ahead of them. C11 atomics provide the vocabulary for this; production mutex implementations have more states and rules than this small illustration.

The important point is that the kernel is not consulted merely to change an uncontended lock. The atomic instruction operates directly on the shared memory location.

The slow path: sleep only if the value is still busy

Suppose a second thread observes that the word is 1. It must not blindly sleep. The owner could release the lock immediately after the observation. Instead, the waiter asks Linux to wait only while the word still equals the value it observed.

Conceptually, the call is the futex system call with the operation FUTEX_WAIT (or FUTEX_WAIT_PRIVATE when the word is shared only between threads in one process), the address of the word, and the expected value. Linux atomically checks the word as part of registering the wait. If it no longer equals the expected value, the call returns without sleeping.

That check closes a crucial race:

  1. The waiter sees the lock as busy.
  2. The owner releases it and issues a wakeup.
  3. The waiter tries to wait.

If the kernel did not recheck the value while adding the waiter, the wakeup in step 2 could be lost and the waiter could sleep indefinitely. The futex wait operation makes “check the value and enqueue me if it matches” one coordinated operation from the kernel’s point of view.

A waiter must still use a loop. It can wake because the lock was released, because a signal interrupted the wait, because the implementation permits a spurious wakeup, or because another waiter got the lock first.

for (;;) {
    int expected = 1;

    if (atomic_compare_exchange_weak(&lock_word, &expected, 1))
        break;                         /* Acquired */

    futex_wait_private(&lock_word, 1);  /* Conceptual wrapper */
}

futex_wait_private above is a descriptive wrapper, not a C library function with that exact portable interface. Low-level code issues the Linux futex system call, commonly through syscall; libraries such as the GNU C Library hide those details behind pthread_mutex_lock and related APIs.

Kernel wait queues and targeted wakeups

When the wait operation really blocks, Linux places the thread on a wait queue associated with the futex address. A wait queue is kernel bookkeeping for threads that cannot proceed until some condition changes. The thread is marked unable to run and the scheduler can give the CPU to useful work instead of making it spin.

The kernel does not need to maintain a heavyweight kernel lock object for every futex word. It can derive a key from the address (and, for process-shared futexes, the relevant shared-memory identity), then use internal hash buckets to find waiters for that key. The details are kernel implementation details, but the effect is that a wake operation targets waiters associated with this particular futex rather than waking every sleeping thread on the machine.

When the owner unlocks, it first changes the shared word to indicate that the lock is available. If it knows there may be waiters, it invokes the futex operation FUTEX_WAKE or FUTEX_WAKE_PRIVATE, usually asking to wake one waiter for a mutex. The kernel marks an appropriate sleeping thread runnable. That thread returns from its wait, loops, and races with other contenders to acquire the word using the same atomic operation.

The unlocker does not hand ownership directly to a specific thread. A wakeup merely makes a waiter eligible to run; scheduling and the atomic acquisition decide who gets the lock. This is why the waiter must retry rather than assume that returning from the kernel means it owns anything.

What you may have already seen

Most application code does not call futexes directly. A pthread_mutex_t, condition variable, semaphore, or language runtime lock may use them internally. A thread dump showing many threads in futex_wait, an incident report mentioning FUTEX_WAIT_PRIVATE, or a profiler attributing time to do_futex is usually showing the contended path: user-space attempts failed, so threads were sleeping in the kernel rather than burning CPU.

Futexes do not make a critical section fast by themselves, and they do not prevent deadlocks. They provide an efficient boundary between two strategies: atomic user-space operations when the lock is available, and kernel-managed sleeping plus narrowly directed wakeups when it is not.

← All articles