futex() — Linux system interface
Low-level fast userspace mutex building block: a kernel-assisted wait or wake on a suitably aligned 32-bit word. There is no dedicated glibc futex wrapper; use syscall with operation-specific arguments. FUTEX_WAIT compares the word with an expected value and sleeps only if equal, with an optional relative timeout; EAGAIN means the value differed, ETIMEDOUT means timeout, EINTR may mean interruption. FUTEX_WAKE returns the number woken. PRIVATE operations are for threads within one process, not interprocess mappings. A real lock needs C atomics, memory-ordering rules, a condition recheck and lifetime management; prefer pthread mutexes unless implementing synchronization primitives. This single-thread demonstration is not a mutex and has no competing waiter. Compile the complete C example in a fresh private working directory using gcc -std=c17 -Wall -Wextra -Wpedantic -Werror example.c -o example; run ./example. Linux-specific interface or flags; examples target Linux/glibc on x86_64. The generic libc syscall function invokes the Linux futex syscall; syscall number and argument ABI are architecture-specific.
Formal Syntax & Structure
#define _GNU_SOURCE#include <linux/futex.h>#include <sys/syscall.h>#include <unistd.h>long syscall(SYS_futex, uaddr, op, val, timeout_or_val2, uaddr2, val3); /* call form, not a C prototype */Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| uaddr | uint32_t * | Aligned 32-bit futex word. |
| op | int | Operation and flags. |
| val | uint32_t | Expected value for wait or maximum wake count. |
| timeout_or_val2 | operation-dependent | Relative timespec pointer for FUTEX_WAIT; other operations interpret differently. |
| uaddr2 | uint32_t * | Second futex word for applicable operations. |
| val3 | uint32_t | Operation-specific additional value. |
Return Value
Operation-specific result (0 for successful WAIT; wake count for WAKE), or -1 with errno via syscall.
Working Example
#define _GNU_SOURCE#define _POSIX_C_SOURCE 200809L#include <errno.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <linux/futex.h>#include <sys/syscall.h>#include <stdint.h>#include <time.h>
/* A failed check ends this short-lived demonstration. */#define CHECK(x) do { if (!(x)) { \ fprintf(stderr, "check failed at line %d: %s\n", __LINE__, #x); \ return EXIT_FAILURE; \} } while (0)
int main(void){ _Alignas(4) uint32_t word = 1; struct timespec t = {0, 1000000}; CHECK(syscall(SYS_futex, &word, FUTEX_WAIT_PRIVATE, 0u, &t, NULL, 0u) == -1 && errno == EAGAIN); CHECK(syscall(SYS_futex, &word, FUTEX_WAIT_PRIVATE, 1u, &t, NULL, 0u) == -1 && errno == ETIMEDOUT); CHECK(syscall(SYS_futex, &word, FUTEX_WAKE_PRIVATE, 1u, NULL, NULL, 0u) == 0); puts("value mismatch EAGAIN; bounded wait ETIMEDOUT; wake count 0"); return EXIT_SUCCESS;}