# info > FUTEX

yaml
---
type: CommandReference
command: futex
mode: man
section: 7
source: man-pages
---

## Quick Reference
- **Unlock (up):** Atomically increment integer; if changed from 0 to 1, done. Else (contended), set to 1 and call `futex(FUTEX_WAKE)`.
- **Lock (down):** Atomically decrement integer; if result 0, done. Else set to -1 and call `futex(FUTEX_WAIT)`.
- **Timed wait:** `futex(FUTEX_WAIT_BITSET, timeout)`
- **Asynchronous wait:** Use `FUTEX_WAIT_BITSET` with appropriate bitset

## Name
futex - fast user-space locking

## Synopsis
c
#include <linux/futex.h>
Core system call: [`futex(2)`](https://www.chedong.com/phpMan.php/man/futex/2/markdown) with operations like `FUTEX_WAIT`, `FUTEX_WAKE`, etc.

## Key Operations
- `FUTEX_WAIT` — wait until futex value changes or timeout expires
- `FUTEX_WAKE` — wake one or more waiters
- `FUTEX_REQUEUE` — move waiters to another futex
- `FUTEX_CMP_REQUEUE` — conditional requeue
- `FUTEX_WAKE_OP` — atomically wake and perform an operation on another futex
- `FUTEX_LOCK_PI` / `FUTEX_TRYLOCK_PI` / `FUTEX_UNLOCK_PI` — priority‑inheritance locks
- `FUTEX_WAIT_BITSET` / `FUTEX_WAKE_BITSET` — selective wake‑up using bitsets
- `FUTEX_WAIT_REQUEUE_PI` / `FUTEX_CMP_REQUEUE_PI` — wait/requeue with priority inheritance
- `FUTEX_FD` — (obsolete) create a file descriptor for asynchronous notification

## Examples
c
/* Unlock (up) a futex, waking a waiter if necessary */
int futex_up(int *futexp) {
    int old = __sync_fetch_and_add(futexp, 1);
    if (old == 0)          /* no waiters */
        return 0;
    *futexp = 1;
    return futex(futexp, FUTEX_WAKE, 1, NULL, NULL, 0);
}

/* Lock (down) a futex, sleeping on contention */
int futex_down(int *futexp) {
    int old = __sync_fetch_and_sub(futexp, 1);
    if (old == 1)          /* uncontended lock */
        return 0;
    *futexp = -1;
    return futex(futexp, FUTEX_WAIT, -1, NULL, NULL, 0);
}
## See Also
- [clone(2)](https://www.chedong.com/phpMan.php/man/clone/2/markdown)
- [futex(2)](https://www.chedong.com/phpMan.php/man/futex/2/markdown)
- [get_robust_list(2)](https://www.chedong.com/phpMan.php/man/getrobustlist/2/markdown)
- [set_robust_list(2)](https://www.chedong.com/phpMan.php/man/setrobustlist/2/markdown)
- [set_tid_address(2)](https://www.chedong.com/phpMan.php/man/settidaddress/2/markdown)
- [pthreads(7)](https://www.chedong.com/phpMan.php/man/pthreads/7/markdown)
- _Fuss, Futexes and Furwocks: Fast Userlevel Locking in Linux_ (OLS 2002) – example library available at [ftp://ftp.kernel.org/pub/linux/kernel/people/rusty/](ftp://ftp.kernel.org/pub/linux/kernel/people/rusty/)

## Exit Codes
Not applicable.
