futex()¶
Purpose¶
futex() (Fast Userspace Mutex) is a Linux system call used to implement efficient userspace synchronization primitives.
Most synchronization operations execute entirely in userspace.
The kernel is only involved when a thread must block or wake another thread.
This design minimizes system call overhead and improves synchronization performance.
Header¶
Prototype¶
long syscall(SYS_futex,
uint32_t *uaddr,
int futex_op,
uint32_t val,
const struct timespec *timeout,
uint32_t *uaddr2,
uint32_t val3);
Simplified Wrapper¶
Many applications use a helper function:
static int futex(uint32_t *uaddr,
int op,
uint32_t val)
{
return syscall(SYS_futex,
uaddr,
op,
val,
NULL,
NULL,
0);
}
Design Goal¶
Fast path:
Slow path:
Common Operations¶
FUTEX_WAIT¶
Sleep if the futex value matches the expected value.
FUTEX_WAKE¶
Wake one or more waiting threads.
Typical Mutex Flow¶
Acquire:
Release:
Example¶
Thread A:
Thread B:
Why Futex Is Fast¶
Uncontended case:
No system call.
No context switch.
No kernel involvement.
Typical Users¶
Many POSIX synchronization primitives are implemented using futex:
Advantages¶
Fast Uncontended Path¶
Low Kernel Overhead¶
Kernel involvement occurs only when blocking is required.
Foundation of Linux Userspace Synchronization¶
Most pthread synchronization mechanisms rely on futex internally.
Limitations¶
Linux Specific¶
Not part of POSIX.
Low-Level Interface¶
Most applications should use:
instead of directly calling futex().