콘텐츠로 이동
Search

Futex

lastmod 2026-11-16created 2025-08-225 edits

컴퓨터 과학에서 futex(fast userspace mutex, 빠른 사용자 공간 상호 배제, 퓨텍스)는 개발자가 기본적인 잠금을 구현하기 위해 사용되거나 세마포어, POSIX 뮤텍스, 조건 변수와 같은 상위 계층의 잠금 추상화를 위한 빌딩 블록으로서 쓰일 수 있는 리눅스 커널에서 제공하는 시스템 호출이다.

동작

futex의 기본 동작들은 WAIT, WAKE라는 두 개의 특정 동작에만 기반한다. 특정 버전의 리눅스 커널에만 의존하는 일부 futex 구현체들은 특정 목적을 위해 동작들이 몇 개 더 많은 경우도 있다.[1]

WAIT (addr, val)
addr 주소에 저장된 값이 val인지 확인하며, 만일 그러할 경우 현재의 스레드를 sleep 상태로 둔다.
WAKE (addr, val)
addr 주소에서 대기 중인 스레드의 수만큼 val을 깨운다.

About

서론

  • Lee T(h4x0r.org)가 2025년 8월에 쓴 글. Phil Eaton 의 북클럽에서 읽는 'The Art of Multiprocessor Programming, 2nd Edition'(2021년 개정)이 학부 4학년·대학원생 교재라면서 퓨텍스를 다루지 않는다고 비판하고, 빠진 내용을 직접 구현으로 보충함

퓨텍스란 무엇인가 – 왜 중요한가

  • 이름은 fast user space mutex 지만 뮤텍스 자체가 아니라 동기화 원시 연산을 만드는 OS 기능. 그 전에는 락이 대부분 System V IPC 세마포어 위에 만들어져 스레드가 많으면 확장이 안 됐음
  • 2002년 원 논문에서 병렬 작업 1000개 기준 System V 락보다 20~120배 빨랐고, Windows(2012년, WaitOnAddress)와 macOS(2016년)도 비슷한 기능을 들임. pthreads 같은 시스템 라이브러리의 락도 퓨텍스를 씀

퓨텍스의 동작 원리 및 차별점

  • 세마포어가 락과 대기를 묶었다면 퓨텍스는 락과 대기/깨우기를 분리함. 그래서 기다리는 스레드가 없다고 확신하면 unlock 때 커널에 들어가지 않아도 됨 (System V 에서는 unlock 이 늘 시스템 콜)
  • wait 는 특정 메모리 주소(보통 32비트 정수)에 묶인 커널 대기열에 스레드를 넣고 타임아웃을 줄 수 있음. 호출할 때 지금 값이라고 믿는 값을 넘겨야 하고, 값이 이미 바뀌었으면 실패해서 이미 지나간 깨우기를 기다리는 일을 막음. wake 는 보통 1개나 전부를 깨움

퓨텍스의 실질적 활용 – 직접 구현

  • C11 atomic 으로 값을 다루고, Linux 는 syscall(SYS_futex, ...), macOS 는 문서화되지 않은 __ulock 인터페이스로 감쌈. macOS 에는 작년에 os_sync_wait_on_address 가 새로 생겼다고 덧붙임

뮤텍스/스핀락/재귀락 구현의 실전 예

스핀락

  • 비트 하나에 atomic_fetch_or 를 반복해 락을 잡을 때까지 도는 가장 단순한 형태. 경합이 심하면 CPU 를 낭비함

하이브리드 뮤텍스 (‘unsafe’ 뮤텍스)

  • 16번 스핀하고 실패하면 퓨텍스로 잠듦(16회는 특별한 근거 없이 쓰는 값이라고 밝힘). 책이 보여 주는 sleep() 기반 지수 백오프와 달리 락이 풀릴 때 스레드 하나만 정확히 깨움. 잘못된 unlock 을 막지 못해 unsafe 라고 부름

대기자 카운터 뮤텍스

  • 최상위 비트를 락 플래그로, 나머지 비트를 대기자 수로 써서 unlock 때 대기자가 0 이면 wake 시스템 콜을 건너뜀

소유권 관리 포함 뮤텍스

  • pthread_t 소유자와 owned 플래그를 따로 두어 재귀 사용이나 남의 락 해제를 잡아내고 abort 함

재귀 락

  • 중첩 깊이(depth)를 세어 같은 스레드가 다시 잡을 수 있게 하고, depth 가 0 이 될 때만 실제로 풂. 저자는 뮤텍스의 재귀 사용이 엉성한 코드를 부추긴다며 쓰지 않는 쪽에 가깝다고 함

전체 코드 예제

#include <stdint.h>    // For uint32_t
#include <stdbool.h>   // For bool
#include <time.h>      // For struct timespec
#include <stdatomic.h> // For atomic_fetch_or, atomic_fetch_add, ...
#include <pthread.h>   // For pthread_self
#include <stdlib.h>    // For abort
#include <stdio.h>     // For printf
#include <errno.h>     // For ETIMEDOUT
#include <limits.h>

typedef _Atomic(uint32_t) h4x0r_futex_t;

#if defined(__linux__)
#if !defined(_GNU_SOURCE)
#define _GNU_SOURCE
#endif
#include <linux/futex.h>
#include <sys/syscall.h>
#include <unistd.h>

static inline int
h4x0r_futex_wait_timespec(h4x0r_futex_t  *futex,
                         uint32_t         expected,
                         struct timespec *timeout_ptr)
{
    int err = syscall(SYS_futex,
                      futex,
                      FUTEX_WAIT_PRIVATE,
                      expected,
                      timeout_ptr,
                      NULL,
                      0);
    if (err == -1) {
        return errno;
    }

    return 0;
}

static inline int
h4x0r_futex_wake(h4x0r_futex_t *futex, bool all)
{
    uint32_t n = all ? INT_MAX : 1;

    return syscall(SYS_futex,
                   futex,
                   FUTEX_WAKE_PRIVATE,
                   n,
                   NULL,
                   NULL,
                   0);
}
#elif defined(__APPLE__)

// These were never exposed in any headers.
extern int __ulock_wait2(uint32_t, void *, uint64_t, uint64_t, uint64_t);
extern int __ulock_wake(uint32_t, void *, uint64_t);

#define H4X0R_NSEC_PER_SEC 1000000000
#define H4X0R_LOCK_COMPARE_AND_WAIT          1
#define H4X0R_LOCK_WAKE_ALL                  0x00000100
#define H4X0R_LOCK_WAKE_THREAD               0x00000200

#define H4X0R_WAKE_ALL    (H4X0R_LOCK_COMPARE_AND_WAIT | H4X0R_LOCK_WAKE_ALL)
#define H4X0R_WAKE_THREAD (H4X0R_LOCK_COMPARE_AND_WAIT | H4X0R_LOCK_WAKE_THREAD)

static inline int
h4x0r_futex_wait_timespec(h4x0r_futex_t   *futex,
                         uint32_t         expected,
                         struct timespec *timeout)
{
    uint64_t timeout_ns = 0;

    if (timeout) {
        timeout_ns = timeout->tv_nsec + timeout->tv_sec * H4X0R_NSEC_PER_SEC;
    }
    return __ulock_wait2(H4X0R_LOCK_COMPARE_AND_WAIT,
                         futex,
                         (uint64_t)expected,
                         timeout_ns,
                         0);
}

static inline int
h4x0r_futex_wake(h4x0r_futex_t *futex, bool all)
{
    return __ulock_wake(all ? H4X0R_WAKE_ALL : H4X0R_WAKE_THREAD,
                        futex,
                        0ULL);
}
#endif


#define H4X0R_SPIN_COUNT 16

typedef h4x0r_futex_t h4x0r_mutex_unsafe_t;

static inline void
h4x0r_mutex_unsafe_init(h4x0r_mutex_unsafe_t *lock)
{
    atomic_store(lock, 0);
}

static inline void
h4x0r_mutex_unsafe_acquire(h4x0r_mutex_unsafe_t *lock)
{
    for (uint32_t i = 0; i < H4X0R_SPIN_COUNT; i++) {
        if (!atomic_fetch_or(lock, 1)) {
            return;
        }
    }
    while (true) {
        h4x0r_futex_wait_timespec((h4x0r_futex_t *)lock, 1, NULL);
        if (!atomic_fetch_or(lock, 1)) {
            return;
        }
    }
}

static inline void
h4x0r_mutex_unsafe_release(h4x0r_mutex_unsafe_t *lock)
{
   atomic_store(lock, 0);
   h4x0r_futex_wake(lock, false);
}

// First one is OR'd in, the second is AND'd in.
#define H4X0R_MUTEX_LOCK_ON (1 << 31)
#define H4X0R_MUTEX_LOCK_OFF ~(H4X0R_MUTEX_LOCK_ON)

static inline bool
h4x0r_mutex_value_is_unlocked(uint32_t value)
{
    return !(value & H4X0R_MUTEX_LOCK_ON);
}

static inline bool
h4x0r_mutex_unsafe2_try_lock(h4x0r_mutex_unsafe_t *lock)
{
    uint32_t value = atomic_fetch_or(lock, H4X0R_MUTEX_LOCK_ON);
    return h4x0r_mutex_value_is_unlocked(value);
}

static inline uint32_t
h4x0r_mutex_unsafe2_add_waiter(h4x0r_mutex_unsafe_t *lock)
{
    return 1 + atomic_fetch_add(lock, 1);
}

static inline void
h4x0r_mutex_unsafe2_acquire(h4x0r_mutex_unsafe_t *lock)
{
    uint32_t expected;

    for (uint32_t i = 0; i < H4X0R_SPIN_COUNT; i++) {
        if (h4x0r_mutex_unsafe2_try_lock(lock)) {
            return;
        }
    }

    expected = h4x0r_mutex_unsafe2_add_waiter(lock);

    while (true) {
        if (h4x0r_mutex_value_is_unlocked(expected)
        && h4x0r_mutex_unsafe2_try_lock(lock)) {
            atomic_fetch_add(lock, -1);
            return;
        }

        h4x0r_futex_wait_timespec((h4x0r_futex_t *)lock, expected, NULL);
        expected = atomic_load(lock);
    }
}

static inline void
h4x0r_mutex_unsafe2_release(h4x0r_mutex_unsafe_t *lock)
{
   uint32_t waiters = atomic_fetch_and(lock, H4X0R_MUTEX_LOCK_OFF);

   if (waiters != H4X0R_MUTEX_LOCK_ON) {
       h4x0r_futex_wake(lock, false);
   }
}


typedef struct {
    h4x0r_futex_t      futex;
    _Atomic(pthread_t) owner;
    _Atomic(bool)      owned;
} h4x0r_mutex_t;

static inline void
h4x0r_mutex_init(h4x0r_mutex_t *mutex)
{
    *mutex = (h4x0r_mutex_t) {
    .futex = 0,
    .owned = false,
    };
}

static inline bool
h4x0r_mutex_try_lock(h4x0r_mutex_t *lock)
{

    uint32_t value = atomic_fetch_or(&lock->futex, H4X0R_MUTEX_LOCK_ON);
    pthread_t self;

    if (!h4x0r_mutex_value_is_unlocked(value)) {
    return false;
    }
    // If what we read when we wrote says "unlocked", then we
    // successfully acquired the lock.
    self = pthread_self();

    if (atomic_load(&lock->owned)) {
    if (pthread_equal(self, atomic_load(&lock->owner))) {
        fprintf(stderr, "Mutex was used recursively.\n");
    }
    else {
        fprintf(stderr, "Acquired a lock owner didn't properly yield.\n");
    }
    abort();
    }

    // We have the lock, so we make it known.
    atomic_store(&lock->owned, true);
    atomic_store(&lock->owner, self);

    return true;
}

static inline uint32_t
h4x0r_mutex_add_waiter(h4x0r_mutex_t *lock)
{
    return 1 + atomic_fetch_add(&lock->futex, 1);
}

static inline bool
h4x0r_mutex_acquire(h4x0r_mutex_t *lock, struct timespec *timeout)
{
    uint32_t  expected;

    for (uint32_t i = 0; i < H4X0R_SPIN_COUNT; i++) {
        if (h4x0r_mutex_try_lock(lock)) {
            return true;
        }
    }

    expected = h4x0r_mutex_add_waiter(lock);

    while (true) {
        if (h4x0r_mutex_value_is_unlocked(expected)
        && h4x0r_mutex_try_lock(lock)) {
            atomic_fetch_add(&lock->futex, -1);
            return true;
        }

        int err = h4x0r_futex_wait_timespec((h4x0r_futex_t *)&lock->futex,
                        expected,
                        timeout);

    if (err == ETIMEDOUT) {
        return false;
    }
        expected = atomic_load(&lock->futex);
    }
}

static inline void
h4x0r_mutex_release(h4x0r_mutex_t *lock)
{
    if (!atomic_load(&lock->owned)
        || !pthread_equal(pthread_self(), atomic_load(&lock->owner))) {
    fprintf(stderr, "Thread unlocked a mutex it doesn't own.\n");
    abort();
    }

    atomic_store(&lock->owned, true);
    uint32_t waiters = atomic_fetch_and(&lock->futex, H4X0R_MUTEX_LOCK_OFF);

    if (waiters != H4X0R_MUTEX_LOCK_ON) {
    h4x0r_futex_wake(&lock->futex, false);
    }
}

typedef struct {
    h4x0r_futex_t      futex;
    _Atomic(uint32_t)  depth;
    _Atomic(pthread_t) owner;
    _Atomic(bool)      owned;
} h4x0r_mutex_recursive_t;


static inline void
h4x0r_mutex_recursive_init(h4x0r_mutex_recursive_t *mutex)
{
    *mutex = (h4x0r_mutex_recursive_t) {
    .futex = 0,
    .depth = 0,
    .owned = false,
    };
}

static inline bool
h4x0r_mutex_recursive_check_ownership(h4x0r_mutex_recursive_t *lock,
                      pthread_t                self)
{
    if (!atomic_load(&lock->owned)) {
    return false;
    }
    if (pthread_equal(self, atomic_load(&lock->owner))) {
    atomic_fetch_add(&lock->depth, 1);
    return true;
    }

    return false;
}

// Called from our internal try-lock call, once it knows we definitely
// just acquired ownership.
static inline void
h4x0r_mutex_recursive_new_ownership(h4x0r_mutex_recursive_t *lock,
                    pthread_t                self)
{
    if (atomic_load(&lock->owned)) {
    fprintf(stderr, "Acquired a lock owner didn't properly yield.\n");
    abort();
    }
    atomic_store(&lock->owned, true);
    atomic_store(&lock->owner, self);
    atomic_store(&lock->depth, 1);
}

// Called when definitely holding the lock.
// Returns true if we are nested, and false if we aren't (proper unlock).
static inline bool
h4x0r_mutex_recursive_nesting_check(h4x0r_mutex_recursive_t *lock)
{

    if (!pthread_equal(pthread_self(), atomic_load(&lock->owner))) {
    fprintf(stderr, "Thread is trying to unlock a lock it doesn't own.\n");
    abort();
    }

    if (atomic_fetch_add(&lock->depth, -1) > 1) {
    return true;
    }
    atomic_store(&lock->owned, false);
    return false;
}

static inline bool
h4x0r_mutex_recursive_internal_try_lock(h4x0r_mutex_recursive_t *lock, pthread_t self)
{
    uint32_t value = atomic_fetch_or(&lock->futex, H4X0R_MUTEX_LOCK_ON);
    bool result    =  h4x0r_mutex_value_is_unlocked(value);

    if (result) {
    h4x0r_mutex_recursive_new_ownership(lock, self);
    }

    return result;
}

static inline uint32_t
h4x0r_mutex_recursive_add_waiter(h4x0r_mutex_recursive_t *lock)
{
    return 1 + atomic_fetch_add(&lock->futex, 1);
}

static inline bool
h4x0r_mutex_recursive_acquire(h4x0r_mutex_recursive_t *lock,
                  struct timespec         *timeout)
{
    uint32_t  expected;
    pthread_t self = pthread_self();

    if (h4x0r_mutex_recursive_check_ownership(lock, self)) {
    // We already owned the lock, and incremented the nesting count.
    return true;
    }

    for (uint32_t i = 0; i < H4X0R_SPIN_COUNT; i++) {
        if (h4x0r_mutex_recursive_internal_try_lock(lock, self)) {
        // internal_try_lock will set up ownership.
            return true;
        }
    }

    expected = h4x0r_mutex_recursive_add_waiter(lock);

    while (true) {
        if (h4x0r_mutex_value_is_unlocked(expected)
        && h4x0r_mutex_recursive_internal_try_lock(lock, self)) {
            atomic_fetch_add(&lock->futex, -1);
            return true;
        }

        int err = h4x0r_futex_wait_timespec((h4x0r_futex_t *)&lock->futex,
                        expected,
                        timeout);
    if (err == ETIMEDOUT) {
        return false;
    }
        expected = atomic_load(&lock->futex);
    }
}

static inline bool
h4x0r_mutex_recursive_try_lock(h4x0r_mutex_recursive_t *lock)
{
    pthread_t self = pthread_self();

    if (h4x0r_mutex_recursive_check_ownership(lock, self)) {
    // We already owned the lock, and incremented the nesting count.
    return true;
    }
    return h4x0r_mutex_recursive_internal_try_lock(lock, self);
}

static inline void
h4x0r_mutex_recursive_release(h4x0r_mutex_recursive_t *lock)
{
    if (h4x0r_mutex_recursive_nesting_check(lock)) {
    // We were nested, and the decrement happened, so we're done.
    return;
    }

    uint32_t waiters = atomic_fetch_and(&lock->futex, H4X0R_MUTEX_LOCK_OFF);

    if (waiters != H4X0R_MUTEX_LOCK_ON) {
    h4x0r_futex_wake(&lock->futex, false);
    }
}

남은 과제 및 실제 엔지니어링 현실

  • 락을 쥔 스레드가 죽는 경우를 처리하려면 스레드별 보유 락 목록과 종료 콜백이 필요하고, 프로세스 간에 공유하는 뮤텍스는 락을 쥔 프로세스가 fork 할 때 문제가 생김
  • POSIX 는 RW 락의 재귀 잠금을 정의하지 않아 구현마다 동작이 다름. 책은 이런 문제도, async 런타임도 다루지 않는다고 지적함

결론

  • 이 책은 컴퓨터 과학 교과서라기보다 역사책이라는 평가. 지금 교재를 쓴다면 이번 천년의 내용도 다뤄 달라는 주문

See also

Favorite site

author Zer0, MCPBot sitemap