본문으로 건너뛰기
Folly Code Review · 79/89

folly::MicroSpinLock — 가장 좁은 spin lock

· Hawk · 5분 읽기

한 줄 요약: MicroSpinLock은 1-byte spin lock이다. 절대 sleep 하지 않고 CPU를 점유하며 대기한다. critical section이 수십 nanosecond 수준일 때 가장 빠르다.

#동기

std::mutexMicroLock은 contention 시 futex로 sleep한다. sleep의 cost는 context switch — 보통 수 μs. critical section이 수십 ns면 sleep이 훨씬 더 비싸다.

시나리오: 10ns critical section, 가끔 contention
std::mutex contended : 1000ns (futex syscall + wake)
MicroSpinLock contended : 50ns (CPU spin ~ critical section 길이)

CPU를 잠깐 태우는 게 sleep보다 싸다는 결정. 단 critical section이 길면 spin 비용이 누적돼 context switch보다 비싸진다 — trade-off가 critical section 길이에 결정적.

#API

#include <folly/SpinLock.h>
folly::MicroSpinLock m{}; // 명시적으로 {} (POD-aggregate init)
m.lock();
// critical section
m.unlock();
// RAII
{
std::lock_guard lk(m);
// ...
}

MicroLock과 같은 표면. 차이는 contention 시 동작.

#init

folly::MicroSpinLock m;
m.init(); // 명시적 init — 일부 컴파일러에서 zero-init 보장 위해

또는 zero-init 영역(static, calloc)에 두면 자동으로 unlocked.

#내부 구현

// folly/SpinLock.h 약식
class MicroSpinLock {
public:
void lock() noexcept {
while (!try_lock()) {
asm_volatile_pause(); // PAUSE / YIELD
}
}
bool try_lock() noexcept {
return __atomic_test_and_set(&lock_, __ATOMIC_ACQUIRE) == 0;
}
void unlock() noexcept {
__atomic_clear(&lock_, __ATOMIC_RELEASE);
}
private:
uint8_t lock_;
};

#acquire / release가 보장하는 것

lock의 try-set은 ACQUIRE, clear는 RELEASE다. 이 조합이 mutex의 의미를 만든다.

Happens-before via release/acquire

unlock 이전의 CS 안 쓰기들이 다음에 lock을 잡는 스레드의 읽기에 visible해진다. spin-lock도 결국 release/acquire pair로 데이터 visibility를 보장하는 도구다.

핵심은 셋.

  1. test_and_set — atomic 1-bit set. acquire fence.
  2. PAUSE 명령 — x86의 pause, ARM의 yield. spin loop hint로 CPU power 절감, hyperthread 양보.
  3. clear with release — release fence.
spin loop:
PAUSE ; CPU에게 spin 중임을 알림
TEST_AND_SET ; atomic
JZ done ; 0이면 (이전 unlocked) 잠금 성공
JMP spin loop
done:

PAUSE는 1-15 cycle. CPU에 짧은 backoff를 알린다. memory ordering buffer를 비워 cache line 경합을 줄인다. PAUSE 없는 spin은 심각하게 성능을 깎는다.

#언제 spin이 옳은가

상황권장
critical section ≈ context switch cost (수 μs)mutex가 더 나음
critical section << context switch cost (수십 ns)spin이 압도적
대기자 많고 critical section 김spin이 CPU를 낭비. mutex

짧고 자주, contention 적음 → spin이 이긴다.

#안전 사용 — preemption

spin 도중 OS가 lock holder를 preempt하면 spinner는 그 quantum 내내 헛 spin한다. preemption-aware 시스템 (RT scheduler, sched_setscheduler)에서는 lock holder의 priority를 spinner와 동등 이상으로 두는 게 안전.

userland에서 일반적으로는 두 가지 가이드.

  1. critical section 안에 절대 syscall/blocking I/O 두지 않음.
  2. critical section은 가능한 한 짧게 — assignment, increment, 짧은 list 조작.

#std::atomic_flag와의 비교

std::atomic_flag flag = ATOMIC_FLAG_INIT;
void lock() {
while (flag.test_and_set(std::memory_order_acquire)) {
// PAUSE? — 직접 짜야 함
}
}
void unlock() { flag.clear(std::memory_order_release); }

std::atomic_flag + spin loop가 가능하지만 PAUSE/yield hint, RAII guard, 사용자 6-bit 같은 편의가 없다. MicroSpinLock이 그 boilerplate를 묶은 형태.

#실전 — 매우 짧은 critical section

struct Counter {
folly::MicroSpinLock lock;
uint64_t value;
};
void Increment(Counter& c) {
std::lock_guard lk(c.lock);
++c.value; // 1 instruction
}

std::atomic<uint64_t> value + fetch_add 가 더 깔끔. spin lock이 진가를 보이는 건 critical section이 atomic 한 instruction을 넘어선, 그러나 극도로 짧은 경우.

struct Slot {
folly::MicroSpinLock lock;
uint8_t flags;
uint16_t refCount;
uint32_t generation;
};
void TouchSlot(Slot& s) {
std::lock_guard lk(s.lock);
s.flags |= kAccessed;
++s.refCount;
s.generation = NowGen();
}

3-4 field를 atomic 하게 일관 갱신 — atomic 하나로 표현 어렵다. spin lock으로 묶는다.

#사용자 7-bit

MicroSpinLock은 8 bit 중 1 bit만 lock에 쓴다. 나머지 7 bit이 사용자 data로 쓸 수 있다. MicroLock(6 bit user)보다 1 bit 더. 단 비공식적 활용이라 직접 비트 조작 필요.

#코드 리뷰 포인트

  • critical section 안에 syscall/mutex/blocking 호출 → 즉시 std::mutex로 교체.
  • spin이 hot path인데 PAUSE/yield 없음 → 다른 hyperthread를 굶긴다. MicroSpinLock 사용 (이미 PAUSE 포함).
  • contention이 항상 큼 → spin 비용이 누적. mutex가 나음.
  • userland realtime priority에서 spin → priority inversion.

#자주 보는 안티패턴

// 1. critical section에 LOG
{
std::lock_guard lk(m);
LOG(INFO) << "in critical"; // I/O — context switch가 spin 중에 일어남
}
// 2. spin lock으로 condition variable 흉내
folly::MicroSpinLock m;
bool ready = false;
void Wait() {
while (true) {
std::lock_guard lk(m);
if (ready) return;
}
// → CPU 100% spin. condition variable + std::mutex가 옳음.
}
// 3. 100 라인 critical section
{
std::lock_guard lk(m);
ProcessLargeBatch(items); // ms-scale
}
// → spin 다른 thread가 ms 동안 헛 spin. std::mutex로.

#std::mutex / MicroLock / MicroSpinLock 선택

시나리오추천
critical section μs ~ msstd::mutex
critical section 100 ns ~ μs, sleep OKMicroLock
critical section ~ 50 ns, contention 적음MicroSpinLock
수억 객체, lock 자체가 가끔 contendedMicroLock
짧은 lock + 사용자 비트 1 byteMicroSpinLock
read 압도, write 드묾RWSpinLock / SharedMutex

#정리

  • MicroSpinLock은 1-byte spin lock, sleep 없음.
  • PAUSE/yield 명령으로 cache 경합과 power 줄임.
  • critical section이 수십 ns일 때 가장 빠름.
  • 길어지면 mutex가 나음 — trade-off가 critical section 길이로 결정.
  • atomic flag로도 가능하지만 RAII + 사용자 비트가 추가 가치.

#다음 편

Part 19로 넘어가 format, demangle, DynamicConverter를 본다.

#관련 항목

Folly Code Review · 80 of 89

  1. 1 Folly Code Review — Meta의 production-grade C++ 라이브러리 코드 분석
  2. 2 Folly 개요 — Meta가 production에서 검증한 utility 모음 분석
  3. 3 Folly vs Abseil 철학 비교 — performance-first vs std-compatible
  4. 4 Folly 빌드와 fbcode 환경 — monorepo의 그림자
  5. 5 Folly API stability 정책 — 어떤 보장도 없다는 솔직함
  6. 6 Folly production validation 문화 — peta-scale에서 단련된 코드
  7. 7 folly::Future 분석 — std::future의 한계를 넘는 composable async
  8. 8 folly::Promise·makeFuture — Future를 만드는 두 길
  9. 9 folly::SemiFuture vs Future — executor binding의 명시화
  10. 10 folly::Future thenValue·thenError·thenTry — continuation 체인 분석
  11. 11 folly::collect·collectAll·collectAny — fan-in 패턴 분석
  12. 12 folly::Future retry·window·via — 제어 흐름 조합자
  13. 13 folly::fibers 분석 — M:N stackful coroutine
  14. 14 folly::InlineExecutor — 호출자 thread에서 즉시 실행
  15. 15 folly::CPUThreadPoolExecutor — CPU-bound 작업의 표준 thread pool
  16. 16 folly::IOThreadPoolExecutor — libevent 기반 I/O pool
  17. 17 folly::ManualExecutor — 결정적 테스트를 위한 수동 진행
  18. 18 folly::EventBase 분석 — libevent 이벤트 루프의 핵심
  19. 19 folly::IOBuf 분석 — zero-copy buffer chain의 기본 단위
  20. 20 folly::IOBufQueue — chain의 push/pull 추상화
  21. 21 folly::io::Cursor·RWCursor — chain 위의 stream
  22. 22 folly Zero-copy 패턴 — IOBuf로 ScatterGather I/O 표현
  23. 23 folly::IOBuf shared semantics — clone·unshare·takeOwnership
  24. 24 folly::FBString 분석 — SSO + COW 구현
  25. 25 folly의 fmt::format 통합 — 모던 포맷팅 채택
  26. 26 folly::StringPiece — string_view 호환 분석
  27. 27 folly Join·Split utilities — 문자열 분해와 결합
  28. 28 folly::to·tryTo — text↔num 변환 분석
  29. 29 folly Conv Customization — 사용자 타입 지원
  30. 30 folly Conv 성능 비교 — sprintf·stringstream 대비
  31. 31 folly::F14ValueMap vs std::unordered_map
  32. 32 folly::F14NodeMap — stable pointer가 필요할 때
  33. 33 folly::F14VectorMap — cache-friendly iteration
  34. 34 folly::F14FastMap — auto-select 동작
  35. 35 folly F14 internals — SIMD probing 메커니즘
  36. 36 folly::small_vector — inline storage 분석
  37. 37 folly::FixedString — compile-time string
  38. 38 folly::AtomicHashMap — lock-free read 분석
  39. 39 folly::ConcurrentHashMap — sharded 동시 해시 맵
  40. 40 folly::EvictingCacheMap — LRU 구현 분석
  41. 41 folly::Synchronized — lock wrapper 패턴
  42. 42 folly::SharedMutex 분석
  43. 43 folly::Baton — one-shot wait 동기화
  44. 44 folly::RWSpinLock 분석
  45. 45 folly::PicoSpinLock — 1-byte spinlock
  46. 46 folly::ProducerConsumerQueue — SPSC 큐 분석
  47. 47 folly::MPMCQueue — multi-producer multi-consumer
  48. 48 folly::UnboundedQueue — 동적 크기 lock-free
  49. 49 folly::fibers::Channel — Go-like channel
  50. 50 folly::dynamic — JSON-like dynamic type 분석
  51. 51 folly JSON conversion — toJson·parseJson
  52. 52 folly dynamic ↔ struct — manual marshaling
  53. 53 folly dynamic Visitor pattern — type별 분기
  54. 54 folly::Singleton vs Meyers/static — 왜 Folly의 Singleton인가
  55. 55 folly::SingletonVault 분석 — 등록·소멸·의존성
  56. 56 folly::Singleton try_get·try_get_fast — TLS-cached 접근
  57. 57 folly::ExceptionWrapper — type-erased exception holder
  58. 58 folly::ScopeGuard·SCOPE_EXIT — RAII cleanup
  59. 59 folly::Optional vs std::optional
  60. 60 folly::Function vs std::function
  61. 61 folly::Lazy — 지연 초기화 wrapper
  62. 62 folly Meta 스타일 code review 패턴
  63. 63 folly anti-patterns — 잘못 쓰면 std보다 느림
  64. 64 folly vs std 선택 기준 분석
  65. 65 folly::coro 개요 — production C++20 코루틴 어댑터
  66. 66 folly::coro::Task — lazy single-shot 코루틴
  67. 67 folly::coro::AsyncGenerator — 비동기 스트림
  68. 68 folly coro blockingWait·collectAll — 동기 경계와 fan-in
  69. 69 folly::coro::Baton·Mutex — 코루틴-aware 동기화
  70. 70 folly::Expected — 결과 또는 오류
  71. 71 folly::Try — Future 결과 wrapper
  72. 72 folly::Try vs Expected 선택 기준
  73. 73 folly::Range — 일반 iterator pair
  74. 74 folly::Uri — URL 파서
  75. 75 folly Fingerprint64·128 — 분산 hash
  76. 76 folly SpookyHashV2 — fast non-crypto hash
  77. 77 folly::Init — main() 부트스트랩
  78. 78 folly::Indestructible — global lifetime 패턴
  79. 79 folly::MicroLock — 1-byte 락
  80. 80 folly::MicroSpinLock — 가장 좁은 spin lock
  81. 81 folly::format — legacy formatter 분석
  82. 82 folly::demangle — typeid 디망글링
  83. 83 folly::DynamicConverter — dynamic ↔ struct
  84. 84 folly::RecordIO — append-only 로그 파일 포맷
  85. 85 folly::io::Compression — zstd·lz4·snappy wrapper
  86. 86 folly::AsyncIO — io_uring·Linux AIO
  87. 87 folly::CancellationToken — 코루틴·Future 취소 전파
  88. 88 folly::observer — hot config의 atomic refresh
  89. 89 fbcode 패턴 모음 — folly 사용의 실전