futex(2) - SerenityOS man pages

#Name

futex - low-level synchronization primitive

#Synopsis

#include <serenity.h>

// Raw syscall.
int futex(uint32_t* userspace_address, int futex_op, uint32_t value, const struct timespec* timeout, uint32_t* userspace_address2, uint32_t value3);

// More convenient wrappers.
int futex_wait(uint32_t* userspace_address, uint32_t value, const struct timespec* abstime, int clockid, int process_shared);
int futex_wake(uint32_t* userspace_address, uint32_t count, int process_shared);

#Description

The futex() system call provides a low-level synchronization primitive, essentially exposing the kernel's internal thread synchronization primitives to userspace.

While the futex() API is powerful and generic, it is complex and cumbersome to use, and notoriously tricky to use correctly. For this reason, it is not intended to be used by application code directly, but rather to serve as a building block for more specialized and easier to use synchronization primitives implemented in user space, such as mutexes and semaphores. Specifically, the futex() API is designed to enable userspace synchronization primitives to have a fast path that does not involve calling into the kernel at all in the common uncontended case, avoiding the cost of making a syscall completely.

A futex is a single 32-bit integer cell located anywhere in the address space of a process (identified by its address), as well as an associated kernel-side queue of waiting threads. The kernel-side resources associated with a futex are created and destroyed implicitly when a futex is used; in other words, any 32-bit integer can be used as a futex without any specific setup, and a futex on which no threads are waiting is no different to any other integer. The kernel does not assign any meaning to the value of the futex integer; it is up to userspace to make use of the value for its own logic.

The futex() API provides a number of operations, the most basic ones being waiting and waking:

Additionally, the FUTEX_PRIVATE_FLAG flag can be or'ed in with one of the operation values listed above. This flag restricts the call to only work on other threads of the same process (as opposed to any threads in the system that may have the same memory page mapped into their address space, possibly at a different address), which enables additional optimizations in the syscall implementation. The inverse of this flag is exposed as the process_shared argument in futex_wait() and futex_wake() wrapper functions.

#Return value

#Errors

#Examples

The following program demonstrates how futexes can be used to implement a simple "event" synchronization primitive. An event has a boolean state: it can be set or unset; the initial state being unset. The two operations on an event are waiting until it is set, and setting it (which wakes up any threads that were waiting for the event to get set).

Such a synchronization primitive could be used, for example, to notify threads that are waiting for another thread to perform some sort of complex initialization.

The implementation features two fast paths: both setting an event that no thread is waiting on, and trying to wait on an event that has already been set, are performed entirely in userspace without calling into the kernel. For this to work, the value of the futex integer is used to track both the state of the event (whether it has been set) and whether any threads are waiting on it.

#include <AK/Atomic.h>
#include <serenity.h>

class Event {
private:
    enum State : u32 {
        UnsetNoWaiters,
        UnsetWithWaiters,
        Set,
    };

    AK::Atomic<State> m_state { UnsetNoWaiters };

    u32* state_futex_ptr() { return reinterpret_cast<u32*>(const_cast<State*>(m_state.ptr())); }

public:
    void set()
    {
        State previous_state = m_state.exchange(Set, AK::memory_order_release);
        // If there was anyone waiting, wake them all up.
        // Fast path: no one was waiting, so we're done.
        if (previous_state == UnsetWithWaiters)
            futex_wake(state_futex_ptr(), UINT32_MAX, false);
    }

    void wait()
    {
        // If the state is UnsetNoWaiters, set it to UnsetWithWaiters.
        State expected_state = UnsetNoWaiters;
        bool have_exchanged = m_state.compare_exchange_strong(
            expected_state, UnsetWithWaiters,
            AK::memory_order_acquire);
        if (have_exchanged)
            expected_state = UnsetWithWaiters;

        // We need to check the state in a loop and not just once
        // because of the possibility of spurious wakeups.
        // Fast path: if the state was already Set, we're done.
        while (expected_state != Set) {
            futex_wait(state_futex_ptr(), expected_state, nullptr, 0, false);
            expected_state = m_state.load(AK::memory_order_acquire);
        }
    }
};

#History

The name "futex" stands for "fast userspace mutex".

The futex() system call originally appeared in Linux. Since then, many other kernels implemented support for futex-like operations, under various names, in particular:

#Further reading