folly::SharedMutex 분석
#한 줄 요약
folly::SharedMutex는 std::shared_mutex와 동등한 reader-writer lock이지만 작고(4-byte) 빠르며 reader-priority/writer-priority/uncontended path 최적화를 가진다. fbcode 의 동기화 default.
#동기
std::shared_mutex는 표준이지만 다음 한계가 있다.
- 구현 크기 40+ byte (libstdc++/libc++).
- writer starvation에 대한 policy가 implementation-defined.
- uncontended 케이스가 system call까지 가는 경우가 있다.
server에서 ConcurrentHashMap의 shard마다 mutex가 박혀 있다 보면 mutex 자체의 메모리도 무시 못 한다. folly는 sizeof = 4 byte의 SharedMutex를 만들었다. 또한 reader/writer priority를 template parameter로 선택.
folly::SharedMutexReadPriority m1; // reader 우선folly::SharedMutexWritePriority m2; // writer 우선 (default)folly::SharedMutex m3; // alias of WritePriority#API & 사용법
#include <folly/SharedMutex.h>
folly::SharedMutex mu;
// 1. write lock{ std::unique_lock<folly::SharedMutex> g(mu); // 쓰기}
// 2. read lock{ std::shared_lock<folly::SharedMutex> g(mu); // 읽기}
// 3. upgrade lock (folly 확장){ folly::SharedMutex::UpgradeHolder uh(mu); // read access — 하지만 동시 다른 upgrade는 막힘 // 필요하면 write로 승격 folly::SharedMutex::WriteHolder wh(std::move(uh));}
// 4. tryif (mu.try_lock()) { /* exclusive */ }if (mu.try_lock_shared()) { /* shared */ }표준 unique_lock/shared_lock과 호환. C++17 RAII가 그대로 동작.
#내부 구현
// 약식 — folly/SharedMutex.hclass SharedMutex { // 한 word (32-bit) 에 모든 상태 std::atomic<uint32_t> state_; // bit layout: // bit 0 : has writer // bit 1 : has upgrade // bit 2-31 : reader count};state 한 32-bit에 모든 lock 상태. 4-byte total.
#Uncontended write
// 약식void lock() { uint32_t expected = 0; if (state_.compare_exchange_weak(expected, kWriterMask, std::memory_order_acquire)) { return; // 성공 — 한 instruction } // 경쟁 — 느린 path slowLock();}contention 없으면 CAS 한 번으로 끝. 30-40 cycle. std::mutex는 보통 50-100 cycle.
#Uncontended read
void lock_shared() { uint32_t old = state_.fetch_add(kReaderIncrement, std::memory_order_acquire); if (!(old & kWriterMask)) return; // writer 없으면 성공 // writer 있음 — fetch_sub로 취소 후 wait state_.fetch_sub(kReaderIncrement); slowLockShared();}writer가 없으면 atomic add 한 번. cache line이 dirty 되긴 하지만 CAS retry는 없다.
#경쟁 시 — Park/Unpark
contended path는 futex 기반 park. spin 몇 cycle 후 sleep, writer가 unlock 시 wake. linux의 futex_wait/futex_wake, macOS/BSD의 __ulock_*.
// 약식void slowLock() { for (int spin = 0; spin < kMaxSpins; ++spin) { if (try_lock()) return; cpu_pause(); } // park while (!try_lock()) { futex_wait(&state_, current); }}
void unlock() { state_.fetch_and(~kWriterMask, std::memory_order_release); if (waiters_) futex_wake_all(&state_);}spin → futex_wait의 hybrid. 짧은 critical section은 spin으로 끝, 긴 건 sleep.
#Reader vs Writer Priority
// 약식 — Writer priority (default)void lock_shared() { uint32_t old = state_.load(); while (true) { if (old & (kWriterMask | kWriterPendingMask)) { // writer가 대기 중이면 reader는 양보 park(); continue; } if (state_.compare_exchange_weak(old, old + kReaderIncrement)) return; }}WritePriority는 writer가 대기 중이면 새 reader를 들이지 않는다. writer starvation 방지. fbcode default.
ReadPriority는 반대로 reader를 우선. write throughput이 낮아도 reader latency가 최소.
#std/abseil 비교
// stdstd::shared_mutex mu;{ std::unique_lock g(mu); ... }
// abseilabsl::Mutex mu;{ absl::MutexLock l(&mu); ... }{ absl::ReaderMutexLock l(&mu); ... }// 추가로 conditional critical section, debug deadlock detection
// follyfolly::SharedMutex mu;{ std::unique_lock g(mu); ... }| 항목 | std::shared_mutex | absl::Mutex | folly::SharedMutex |
|---|---|---|---|
| sizeof | 40+ byte | 8 byte | 4 byte |
| Uncontended cost | 50-100 ns | 30-50 ns | 20-30 ns |
| Priority policy | implementation defined | 고정 (writer 우선) | template parameter |
| Conditional CS | X | Mutex::Await | X |
| Deadlock detection | X | debug build | X |
absl::Mutex는 조건 변수까지 통합된 형태. folly::SharedMutex는 pure RW lock에 집중.
#성능
benchmark: N reader threads + 1 writer thread, hot loop (N=8) std::shared_mutex 1.2M ops/s/reader absl::Mutex (Reader) 2.4M folly::SharedMutex (WritePriority) 3.8M folly::SharedMutex (ReadPriority) 4.2M no lock 18.0M (baseline)folly가 2-3배 빠름. 4-byte size + uncontended fast path 효과.
#코드 리뷰 포인트
// Good — Synchronized와 함께folly::Synchronized<Data, folly::SharedMutex> data;auto r = data.rlock(); // sharedauto w = data.wlock(); // exclusive
// Bad — 외부 lock 객체로 SharedMutex 직접 노출folly::SharedMutex mu;Data d;{ std::unique_lock g(mu); d.x = 1; }// 잠금 누락 위험 — Synchronized로 묶기가능한 한 Synchronized<T, SharedMutex>로 사용. raw mutex는 lock 누락 가능성.
// 주의 — 매우 짧은 critical section엔 RWLock 오버킬folly::SharedMutex mu;{ std::shared_lock g(mu); return data.size(); // 1 instruction}// RWSpinLock 또는 atomic이 더 빠를 수 있음critical section이 100 cycle 이하면 spin lock 또는 atomic 직접 사용이 빠르다. SharedMutex의 가치는 contention 시 park 가능성.
#안티패턴
- upgrade lock을 길게 유지: upgrade lock은 reader-blocking이 아니지만 다른 upgrade-blocking. 짧게.
- 사용자 코드가
state_bit를 직접 조작: implementation detail, 절대 의존 금지. SharedMutex_ReadPriority를 default로 선택: writer starvation 위험. fbcode 표준은 WritePriority.
#정리
folly::SharedMutex는 4-byte의 빠른 reader-writer lock.- Uncontended write/read: CAS/atomic add 한 번.
- Contended는 spin-then-futex-park hybrid.
- Reader/Writer priority를 template parameter로 선택.
Synchronized와 함께 쓰는 것이 표준 패턴.
#다음 편
Baton은 한 번만 발사되는 wait/notify primitive. condition variable보다 가볍다.
#관련 항목
- Part 9-01: Synchronized — SharedMutex의 wrapper
- Part 9-04: RWSpinLock — 더 짧은 critical section 용
- Part 8-04: ConcurrentHashMap — shard별 SharedMutex 사용
- 원문 — folly/SharedMutex.h
Folly Code Review · 42 of 89
- 1 Folly Code Review — Meta의 production-grade C++ 라이브러리 코드 분석
- 2 Folly 개요 — Meta가 production에서 검증한 utility 모음 분석
- 3 Folly vs Abseil 철학 비교 — performance-first vs std-compatible
- 4 Folly 빌드와 fbcode 환경 — monorepo의 그림자
- 5 Folly API stability 정책 — 어떤 보장도 없다는 솔직함
- 6 Folly production validation 문화 — peta-scale에서 단련된 코드
- 7 folly::Future 분석 — std::future의 한계를 넘는 composable async
- 8 folly::Promise·makeFuture — Future를 만드는 두 길
- 9 folly::SemiFuture vs Future — executor binding의 명시화
- 10 folly::Future thenValue·thenError·thenTry — continuation 체인 분석
- 11 folly::collect·collectAll·collectAny — fan-in 패턴 분석
- 12 folly::Future retry·window·via — 제어 흐름 조합자
- 13 folly::fibers 분석 — M:N stackful coroutine
- 14 folly::InlineExecutor — 호출자 thread에서 즉시 실행
- 15 folly::CPUThreadPoolExecutor — CPU-bound 작업의 표준 thread pool
- 16 folly::IOThreadPoolExecutor — libevent 기반 I/O pool
- 17 folly::ManualExecutor — 결정적 테스트를 위한 수동 진행
- 18 folly::EventBase 분석 — libevent 이벤트 루프의 핵심
- 19 folly::IOBuf 분석 — zero-copy buffer chain의 기본 단위
- 20 folly::IOBufQueue — chain의 push/pull 추상화
- 21 folly::io::Cursor·RWCursor — chain 위의 stream
- 22 folly Zero-copy 패턴 — IOBuf로 ScatterGather I/O 표현
- 23 folly::IOBuf shared semantics — clone·unshare·takeOwnership
- 24 folly::FBString 분석 — SSO + COW 구현
- 25 folly의 fmt::format 통합 — 모던 포맷팅 채택
- 26 folly::StringPiece — string_view 호환 분석
- 27 folly Join·Split utilities — 문자열 분해와 결합
- 28 folly::to·tryTo — text↔num 변환 분석
- 29 folly Conv Customization — 사용자 타입 지원
- 30 folly Conv 성능 비교 — sprintf·stringstream 대비
- 31 folly::F14ValueMap vs std::unordered_map
- 32 folly::F14NodeMap — stable pointer가 필요할 때
- 33 folly::F14VectorMap — cache-friendly iteration
- 34 folly::F14FastMap — auto-select 동작
- 35 folly F14 internals — SIMD probing 메커니즘
- 36 folly::small_vector — inline storage 분석
- 37 folly::FixedString — compile-time string
- 38 folly::AtomicHashMap — lock-free read 분석
- 39 folly::ConcurrentHashMap — sharded 동시 해시 맵
- 40 folly::EvictingCacheMap — LRU 구현 분석
- 41 folly::Synchronized — lock wrapper 패턴
- 42 folly::SharedMutex 분석
- 43 folly::Baton — one-shot wait 동기화
- 44 folly::RWSpinLock 분석
- 45 folly::PicoSpinLock — 1-byte spinlock
- 46 folly::ProducerConsumerQueue — SPSC 큐 분석
- 47 folly::MPMCQueue — multi-producer multi-consumer
- 48 folly::UnboundedQueue — 동적 크기 lock-free
- 49 folly::fibers::Channel — Go-like channel
- 50 folly::dynamic — JSON-like dynamic type 분석
- 51 folly JSON conversion — toJson·parseJson
- 52 folly dynamic ↔ struct — manual marshaling
- 53 folly dynamic Visitor pattern — type별 분기
- 54 folly::Singleton vs Meyers/static — 왜 Folly의 Singleton인가
- 55 folly::SingletonVault 분석 — 등록·소멸·의존성
- 56 folly::Singleton try_get·try_get_fast — TLS-cached 접근
- 57 folly::ExceptionWrapper — type-erased exception holder
- 58 folly::ScopeGuard·SCOPE_EXIT — RAII cleanup
- 59 folly::Optional vs std::optional
- 60 folly::Function vs std::function
- 61 folly::Lazy — 지연 초기화 wrapper
- 62 folly Meta 스타일 code review 패턴
- 63 folly anti-patterns — 잘못 쓰면 std보다 느림
- 64 folly vs std 선택 기준 분석
- 65 folly::coro 개요 — production C++20 코루틴 어댑터
- 66 folly::coro::Task — lazy single-shot 코루틴
- 67 folly::coro::AsyncGenerator — 비동기 스트림
- 68 folly coro blockingWait·collectAll — 동기 경계와 fan-in
- 69 folly::coro::Baton·Mutex — 코루틴-aware 동기화
- 70 folly::Expected — 결과 또는 오류
- 71 folly::Try — Future 결과 wrapper
- 72 folly::Try vs Expected 선택 기준
- 73 folly::Range — 일반 iterator pair
- 74 folly::Uri — URL 파서
- 75 folly Fingerprint64·128 — 분산 hash
- 76 folly SpookyHashV2 — fast non-crypto hash
- 77 folly::Init — main() 부트스트랩
- 78 folly::Indestructible — global lifetime 패턴
- 79 folly::MicroLock — 1-byte 락
- 80 folly::MicroSpinLock — 가장 좁은 spin lock
- 81 folly::format — legacy formatter 분석
- 82 folly::demangle — typeid 디망글링
- 83 folly::DynamicConverter — dynamic ↔ struct
- 84 folly::RecordIO — append-only 로그 파일 포맷
- 85 folly::io::Compression — zstd·lz4·snappy wrapper
- 86 folly::AsyncIO — io_uring·Linux AIO
- 87 folly::CancellationToken — 코루틴·Future 취소 전파
- 88 folly::observer — hot config의 atomic refresh
- 89 fbcode 패턴 모음 — folly 사용의 실전
관련 글
folly::RWSpinLock 분석
folly::RWSpinLock — spin-only reader-writer lock, 매우 짧은 critical section에 SharedMutex보다 빠르다.
같은 시리즈에서 이어 읽기
folly::PicoSpinLock — 1-byte spinlock
PicoSpinLock — integer type의 한 bit을 lock으로 사용. 객체 안에 lock을 끼워 넣어 메모리 절약.
같은 시리즈에서 이어 읽기
folly::Baton — one-shot wait 동기화
folly::Baton — 한 번 post, 한 번 wait의 경량 signal primitive. condition variable보다 가볍다.
같은 시리즈에서 이어 읽기