Folly synchronization (C++)
Meta's toolbox of specialised locks rather than one general mutex: an 8-byte DistributedMutex that queues waiters as an MCS-like LIFO chain on their own stacks and can combine critical sections, a 4-byte SharedMutex with per-core deferred readers, a 1-byte MicroLock, futex-word Batons, a WebKit-style ParkingLot that emulates futex everywhere but Linux, and coroutine (coro::Mutex) and fiber (fibers::Baton) primitives that wait without blocking a thread.
| Kind | library (folly/synchronization, folly/detail, folly/coro, folly/fibers) |
| Language | C++17/20 |
| License | Apache-2.0 |
| Repository | facebook/folly at 643e26aee8e2 (2026-10-11) |
| Primitives covered | DistributedMutex, SharedMutex, MicroLock, Baton, ParkingLot, detail::Futex, atomic_wait/atomic_notify_*, WaitOptions, coro::Mutex, coro::Baton, fibers::Baton |
| Parking substrate | Linux: futex (FUTEX_WAIT_BITSET, private); elsewhere and for non-32-bit words: ParkingLot, a 4096-bucket hash table of std::mutex + std::condition_variable wait nodes |
| Fairness | per primitive: DistributedMutex hands off along LIFO chains; coro::Mutex strict FIFO; SharedMutex writer-priority by default |
| Source read | DistributedMutex.h, DistributedMutex-inl.h, test/SmallLocksBenchmark.cpp, SharedMutex.h, MicroLock.h, Baton.h, WaitOptions.h, ParkingLot.h, ParkingLot.cpp, detail/Futex.h, detail/Futex.cpp, AtomicNotification.h, AtomicNotification-inl.h, coro/Mutex.h, coro/Mutex.cpp, coro/Baton.h, fibers/Baton.h, fibers/Baton.cpp, fibers/Baton-inl.h, fibers/Fiber.cpp, fibers/FiberManager.cpp |
Overview
What it solves
Folly targets server workloads where a contended lock is the bottleneck, and attacks the coherence traffic of the lock word itself. DistributedMutex's header comment states the thesis (DistributedMutex.h L31–L143):
Theoretically, write locks promote concurrency when the critical sections are small as most of the work is done outside the lock. […] However, most times, the synchronization and scheduling overhead of a write lock in the critical path is so high, that after a certain point, making critical sections smaller does not actually increase the concurrency of the application and throughput plateaus. DistributedMutex moves this breaking point to the level of hardware atomic instructions, so applications keep getting concurrency even under very high contention. It does this by reducing cache misses and contention in userspace and in the kernel by making each thread wait on a thread local node and futex.
SharedMutex applies the same reasoning to readers (SharedMutex.h L45–L52): "Unlike most other reader-writer locks, its throughput with concurrent readers scales linearly; it is able to acquire and release the lock in shared mode without cache line ping-ponging."
Design philosophy
Spin briefly, then sleep precisely. WaitOptions gives the shared rationale for a 2 µs default spin (WaitOptions.h L33–L55):
In this state, we lose big 50% of the time if the wait blocks immediately. […] We use a default maximum of 2 usec of spinning. As partial consolation, since spinning as implemented in folly uses the pause instruction where available, we give a small speed boost to the colocated hyperthread.
On circa-2013 devbox hardware, it costs about 7 usec to FUTEX_WAIT and then be awoken. Spins on this hw take about 7 nsec, where all but 0.5 nsec is the pause instruction.
Each primitive is narrow and states its narrowness: Baton is "basically a stripped-down semaphore that supports only a single call to sem_post and a single call to sem_wait"; DistributedMutex "does not satisfy the Lockable concept"; MicroLock tells readers to prefer std::mutex unless space is the constraint.
How it works
DistributedMutex has one std::uintptr_t state_ (L328). lock() builds a Waiter on the caller's stack, ORs kLocked (bit 0) into its address, and does one exchange(address, acq_rel) on the word (lockImplementation L1156–L1276). If the previous value was kUnlocked (0) the lock is held. Otherwise the previous value is the address of the thread that enqueued just before — the new thread's successor — so contended threads form an intrusive LIFO contention chain threaded through their stacks, and each spins on the futex_ word in its own Waiter. The returned proxy carries next_ and expected_; unlock() (L1550–L1612) either commits expected → kUnlocked with one CAS, or, when the word changed, exchange(kLocked)s the whole chain off the word and hands the lock to its head by storing kWake into that waiter's futex_. The waker writes WakerMetadata (its own address and a list of sleepers it is responsible for) into the woken waiter before signalling.
lock_combine(task) stores a type-erased task (48 bytes inline) in the waiter. A lock holder walking the chain may run that task itself and report kCombined (or kExceptionOccurred, with the exception transported back) instead of handing over the lock — combining "up to a constant factor of 2 contention chains" (kMaxCombineIterations = 2).
ParkingLot is folly's user-space futex: park(key, data, toPark, preWait) runs toPark under the bucket lock, and unpark(key, func) lets a lambda decide, per waiter, whether to remove and wake it (ParkingLot.h L144–L163), citing WebKit's design (webkit-wtf-lock). detail::Futex and atomic_wait route to the real futex on Linux for 32-bit words and to the ParkingLot otherwise.
Analysis
State word and fast path
DistributedMutex: bit 0kLocked, bit 1kTimedWaiter, upper bits aWaiter*(L51–L76).tryLockNoLoadis a singleatomic_fetch_set(state_, 0, acquire)of bit 0, "slightly faster than usingstd::atomic::exchange()";try_lockfirst loads to avoid pulling the line exclusive when the lock is visibly held (L1121–L1150). The benchmark notes the uncontended case "is a few cycles faster thanfolly::MicroLockbut a bit slower thanstd::mutex".- Per-waiter word: the waiter's
futex_(64-bit) carries a signal in its low 8 bits —kUninitialized,kWaiting,kWake,kSkipped,kAboutToWait,kSleeping,kCombined,kCombineUninitialized,kCombineWaiting,kExceptionOccurred(L91–L148) — and a 56-bit TSC timestamp above them. SharedMutex: a 32-bitFutex state_with the reader count in bits 12–31 (kIncrHasS = 1 << 12) and flag bitskHasE,kBegunE,kHasU,kMayDefer,kPrevDefer, plus wait-identity bitskWaitingNotS,kWaitingESingle/kWaitingEMultiple,kWaitingU,kWaitingS(L1097–L1192). Shared acquisitions past the second concurrent reader (kNumSharedToStartDeferring = 2) setkMayDeferand record themselves in a global, per-core-stripeddeferredReaders[]array instead of the word: "Each SharedMutex instance is only 4 bytes, but all locks together share a 2K area in which they make a core-local record of lock acquisitions" (L160–L182). A writer must scan those slots.MicroLock: "Tiny exclusive lock that uses 2 bits. It is stored as 1 byte and has APIs for using the remaining 6 bits for storing user data" (MicroLock.hL31–L84).Baton: 4 bytes, statesINIT,EARLY_DELIVERY,WAITING,LATE_DELIVERY,TIMED_OUT(Baton.hL301–L305);postis a store when nobody waits and an exchange +futexWakeotherwise.
Waiting: spin, yield, park
DistributedMutexspins on its own stack line and publishes a timestamp each iteration (publishL839–L890,spinL892–L922):pausewhileelapsed < kMaxSpinTime(40,000 TSC ticks), thensleep_for(kMinYieldingSleep). A gap of more thankScheduledAwaySpinThreshold(200 ticks, "just a magic number from benchmarks") between two of its own iterations means it was descheduled. The waker reads the published timestamp: if the waiter looks preempted, it storeskSkippedand moves on along the chain (preemptedL1278–L1289,tryWakeL1368–L1474), so the lock never stalls behind a thread that is not running. A skipped thread re-enqueues inkAboutToWaitmode — the second of the "two phased sleeping" — and then sleeps on a futex in itsWakerMetadata(doFutexWaitL961–L1011). This is the lock-holder-preemption answer for waiters: hand-off skips preempted successors instead of waiting on them.SharedMutex: spin up tomax_spin_cycles = 4000, then up tomax_soft_yield_count = 1"soft yields" (~900 ns: twosched_yieldplus agetrusagepreemption check), thenfutexWait(SharedMutexPolicyDefaultL260–L265, L1194–L1203).Baton::tryWaitSlow:spin_pause_untilforWaitOptions::spin_max(2 µs), thenspin_yield_until, then CASINIT → WAITINGandMemoryIdler::futexWaitUntil(L309–L395) —MemoryIdlermay release the thread's stack and arena memory before a long sleep.MicroLock:MaxSpins+MaxYieldstemplate parameters, thenatomic_wait— which, for an 8-bit word, means theParkingLot.
The parking substrate
- Linux futex, with bitsets.
nativeFutexWaitImplusesFUTEX_WAIT_BITSET | FUTEX_PRIVATE_FLAG(absolute timeouts) andfutexWaketakes awakeMask(Futex.cppL48–L160).SharedMutexuses the masks to keep several wait identities on one 32-bit word ("We give this a separate wait identity … so that we can perform partial wakeups (wake one instead of wake all)", L1154–L1158). - Everything else is the
ParkingLot. On any non-Linux OS, and for anyatomic_waiton a word that is not 32 bits wide, waits go to a single static table: "Our emulated futex uses 4096 lists of wait nodes. There are two levels of locking: a per-list mutex that controls access to the list and a per-node mutex, condvar, and bool that are used for the actual wakeups. The per-node mutex allows us to do precise wakeups without thundering herds" (ParkingLot.hL76–L80). The table has 256 buckets on mobile builds (ParkingLot.cppL24–L31); keys aretwang_mix64(address); each bucket keeps an atomiccount_sounparkcan return without locking when it is zero, guarded by a matched pair ofseq_cstoperations ("A: Must be seq_cst. Matches B.",park_untilL250–L295,unparkL297–L330). Wait nodes live on the parked thread's stack. - No
__ulock,WaitOnAddressor_umtx_op.futexWaitImplis#ifdef __linux__native, else emulated (Futex.cppL229–L260), so macOS and Windows park every Folly primitive on astd::condition_variable. DistributedMutexparks on its own stack, too. Non-timed waiters sleep onWakerMetadata::sleeper_in their stackWaiter; the waker that collected them later callsdoFutexWake, which storeskWakeand callsfutexWakeon that address — the comment works through why a wake on a possibly-dangling stack address is still safe, because "futexWake()does not actually change the memory of the futex word" (L925–L958). Timed waiters instead setkTimedWaiterand sleep on the 64-bit central word viaatomic_wait_until— theParkingLot, even on Linux.
Fairness, handoff and starvation
DistributedMutexhands off directly (futex_.store(kWake)passes ownership; the central word keepskLocked), so threads already queued are not barged by arrivals during a chain. Chains are LIFO, but a chain is detached as a whole at wake-up and new arrivals start a new chain, which "preserves global fairness through a constant factor which is limited to the number of concurrent failed mutex acquisition attempts" (L83–L101). The LIFO order is deliberate: "the head of the chain is likely to not have slept on futex() after exhausting its spin quantum". Combining is capped at two chains "to ensure that we don't starve the combiner thread".coro::Mutexis strict FIFO ("This mutex guarantees a FIFO scheduling algorithm",coro/Mutex.hL39–L41): the unlocker reverses the LIFO arrival stack into a FIFO list and resumes its head.SharedMutexdefaults to writer priority, "because writer starvation is more likely than reader starvation for the read-heavy workloads targeted by SharedMutex", with aSharedMutexReadPriorityvariant.ParkingLotbuckets are FIFO lists;unpark's callback can stop at any waiter.
Condition variables and predicates
Folly has no general condition variable in folly/synchronization; blocking-on-predicate is expressed through narrower tools:
ParkingLotis the predicate primitive.toParkis evaluated under the bucket lock (a validate-then-sleep, like a futex compare but arbitrary), andpreWait"is usually used to implement condition variable like things, such that you can unlock the condition variable's lock at the appropriate time" (ParkingLot.hL183–L190).unpark's per-waiter callback can select waiters by theirData, implementing selective wakeups, but there is no requeue to a mutex queue (no wait morphing).Batonis a one-shot event,SaturatingSemaphorea multi-waiter latch,EventCounta prepare/commit/cancel wait protocol for lock-free structures (not analysed here).DistributedMutexcombining is an alternative to waiting on a condition: instead of the waiter sleeping until it can run its critical section, the holder runs it. The header lists the constraint this imposes: the task must not depend on thread-local state or lock other mutexes.
Footprint and layout
| Primitive | Size | Where waiter state lives |
|---|---|---|
DistributedMutex | 8 bytes (one pointer) | Waiter on each contending thread's stack, padded to its own cache line(s) |
SharedMutex | 4 bytes | in-word bits; deferred readers in a global striped slot array shared by all instances |
MicroLock | 1 byte (2 bits used) | ParkingLot nodes on the waiter's stack |
Baton | 4 bytes | the word itself (futex) or ParkingLot |
ParkingLot table | 4096 (mobile: 256) buckets, static | WaitNode (std::mutex + std::condition_variable + links) on the waiter's stack |
coro::Mutex | two pointers | LockAwaiter in the awaiting coroutine's frame |
fibers::Baton | one intptr_t | a Waiter subclass on the fiber's stack |
The DistributedMutex header compares itself to "std::mutex and pthread_mutex_t [which] are both 40 bytes", and argues small locks often waste the difference in alignment padding. The cost of on-stack waiters is stated as a usage restriction: no thread, fiber or coroutine migration inside a critical section, and no segmented stacks (L176–L199).
Portability
Linux gets native futex for 32-bit words; every other platform, and every other width, gets the ParkingLot over std::mutex/std::condition_variable (which in turn sit on pthreads or Windows SRW/condition variables). The TSC read in DistributedMutex ("faster than std::chrono::steady_clock because it avoids a VDSO access") is architecture-specific; TimePublishing is a template parameter so it can be disabled. All primitives are templated on an Atom type so DeterministicSchedule can model-check them in tests.
Async and fiber integration
Folly has the clearest split in this catalog between thread, fiber and coroutine waiting, and one primitive that bridges two of them.
coro::Mutex(coro/Mutex.h,Mutex.cppL33–L106) stores in onestd::atomic<void*> state_eitherthis(unlocked),nullptr(locked, no new waiters) or the head of a LIFO stack ofLockAwaiters living in the awaiting coroutines' frames.co_lockis a CAS; a contendedco_awaitpushes the awaiter with a release CAS and suspends.unlockpops from a holder-private FIFO listwaiters_(refilling it by exchanging the stack out ofstate_and reversing it) and callsawaitingCoroutine_.resume()on the unlocking thread — ownership is not tied to a thread. Which executor the resumed coroutine continues on is decided byviaIfAsync: "Chain a call to.viaIfAsync()to specify the executor to resume on when the lock is eventually acquired", implicit when awaited from aTask. Thread wake-up is therefore the executor's job, not the mutex's.coro::Batonuses the samevoid*state (this= signalled, else a waiter stack);postexchanges in the signalled state and resumes every waiter (coro/Baton.hL29–L64). "As a primitive, this is not cancellation-aware."fibers::Batonis a word that serves both a thread and a fiber (fibers/Baton.hL236–L262). Itsstd::atomic<intptr_t> waiter_holds a sentinel (NO_WAITER = 0,POSTED = -1,TIMEOUT = -2,THREAD_WAITING = -3) or a pointer to aWaiterobject, and is unioned with a 32-bitFutexover its low half. A thread waits by CASingTHREAD_WAITINGin andfutexWaiting; a fiber waits by installing aFiberWaiterfrom the fiber manager's main context and yielding (Baton-inl.hL50–L72).post(Baton.cppL94–L130) eitherfutexWakes the thread or callsWaiter::post(), which for a fiber isFiber::resume(Fiber.cppL51–L61): on the fiber's own loop thread it pushes ontoreadyFibers_; from any other thread it callsremoteReadyInsert, which inserts into a lock-free intrusive list and callsloopController_->scheduleThreadSafe()only if the list was empty (FiberManager.cppL143–L147). That one-word, two-kinds-of-waiter design and the empty-to-non-empty wake deduplication are the closest prior art in this catalog for a SparklesWaitWord.- Thread primitives are not fiber-aware.
DistributedMutexexplicitly forbids fiber or coroutine migration within a critical section, andSharedMutex,BatonandMicroLockblock the OS thread.
Evaluation
The numbers below are Folly's own, recorded in SmallLocksBenchmark.cpp on an Intel Xeon E5-2680 v4 @ 2.40 GHz (time per critical section, relative to std::mutex; higher % is faster):
| Benchmark (16 threads) | Time/iter | vs std::mutex |
|---|---|---|
std_mutex_simple | 12.26 µs | 100% |
folly_microlock_simple | 18.46 µs | 66.39% |
folly_sharedmutex_simple | 18.85 µs | 65.00% |
folly_distributedmutex_simple | 7.15 µs | 171.32% |
folly_flatcombining_no_caching_simple | 5.95 µs | 206.11% |
folly_distributedmutex_combining_simple | 2.75 µs | 445.11% |
atomics_fetch_add | 2.48 µs | 494.82% |
At 64 threads DistributedMutex runs at 161% and its combining mode at 604% of std::mutex, the latter between atomic_cas (607%) and atomic_fetch_xor (756%). These support the header's claims of "~2x faster than std::mutex" contended and "2-3x faster than flat combining" when combining; the "4-5x faster than the smaller locks" claim compares against MicroLock and PicoSpinLock. The header's tail-latency claim ("up to 10x lower") is not reproduced here.
Strengths
DistributedMutex: 8 bytes, no allocation, local spinning on a private cache line, direct hand-off, preemption-aware skipping, and combining that approaches raw atomic throughput.SharedMutex: 4 bytes with linear read scaling through shared per-core stripes; futex wait masks give precise, per-role wakeups.ParkingLotgives any-widthatomic_waitand arbitrary park/unpark callbacks on every platform.fibers::Batonshows one word serving thread and fiber waiters, with deduplicated cross-thread wakeups of the fiber loop.WaitOptionscentralises the spin budget with a measured justification.
Weaknesses
- No general mutex:
DistributedMutexis notLockable, forbids migration inside a critical section, and needs a proxy passed tounlock. - On macOS and Windows every primitive parks on a
std::condition_variablethrough the emulated futex; native wait-on-address APIs are unused. MicroLockand timedDistributedMutexwaits go throughParkingLoteven on Linux, because their words are not 32 bits.SharedMutex's global deferred-reader slots couple unrelated locks; a writer on any lock may scan slots dirtied by readers of others.- No condition variable with wait morphing;
coro::Mutex::unlockruns the next waiter inline on the unlocker's stack unless an executor is attached. - TSC-based preemption detection is a heuristic tuned by "magic numbers from benchmarks".
Key design decisions and trade-offs
| Decision | Rationale | Trade-off |
|---|---|---|
Waiter nodes on the contending thread's stack, linked by exchange | no allocation, each waiter spins on a private line, one RMW to enqueue | no migration while holding; unlock needs the proxy; segmented stacks unsupported |
| LIFO contention chains, detached whole on wake | head is likely still spinning, avoiding syscalls; bounded unfairness | not FIFO; fairness bounded only by the number of concurrent failed attempts |
| Timestamp publishing + skip preempted waiters | hand-off never waits for a descheduled successor | TSC dependence; heuristic thresholds; skipped threads must re-enqueue |
| Combining critical sections | holder runs waiters' work; no line transfer per critical section | tasks must be thread-agnostic and not take other locks |
Emulated futex (ParkingLot) for non-Linux and non-32-bit words | one portable, any-width atomic_wait | std::condition_variable per waiter; no WaitOnAddress/__ulock fast path |
Futex bitsets for wait identities (SharedMutex) | readers, writers and upgraders on one word can be woken separately | Linux-only optimisation; emulated path must replicate masks |
fibers::Baton word = sentinel or Waiter*, futex in low half | one primitive serves threads and fibers; remote wakes deduplicated by empty-queue check | 64-bit word with a 32-bit futex view; pointer waiter must outlive the wait |
coro::Mutex resumes the next waiter inline, executor via viaIfAsync | no thread or loop dependency in the mutex | deep resumption on the unlocker's stack when no executor is attached |
Sources
- Folly source at commit
643e26aee8e27c7f32e331402992af04b5080f10(2026-10-11):folly/synchronization/DistributedMutex.h,DistributedMutex-inl.h,test/SmallLocksBenchmark.cpp,folly/SharedMutex.h,folly/MicroLock.h,Baton.h,WaitOptions.h,ParkingLot.h,ParkingLot.cpp,folly/detail/Futex.h,folly/detail/Futex.cpp,AtomicNotification.h,AtomicNotification-inl.h,folly/coro/Mutex.h,folly/coro/Mutex.cpp,folly/coro/Baton.h,folly/fibers/Baton.h,folly/fibers/Baton.cpp,folly/fibers/Baton-inl.h,folly/fibers/Fiber.cpp,folly/fibers/FiberManager.cpp. - Hendler, Incze, Shavit, Tzafrir, "Flat Combining and the Synchronization-Parallelism Tradeoff", SPAA 2010 — cited by
DistributedMutex.has the inspiration forlock_combine. - WG21 P1135R0 (
atomic_wait), cited byAtomicNotification.h. - Siblings:
webkit-wtf-lock(theParkingLotmodel),queue-locks(MCS and combining),abseil-mutex,linux-futex.
NOTE
The benchmark figures are copied from the comment block in SmallLocksBenchmark.cpp; they were not re-run. EventCount, SaturatingSemaphore, LifoSem and Hazptr/Rcu exist in the same directory but are outside this page's scope.