Skip to content

Evaluate an inline lock for internal::mutex::Mutex on Apple targets #425

Open

Description

@tisonkun

crate::internal::mutex::Mutex wraps std::sync::Mutex to synchronize short critical sections over internal state and waker registries across Asyncband primitives.

On Linux, Windows, FreeBSD, and OpenBSD, std::sync::Mutex uses an inline futex word and does not allocate. On macOS and other Apple targets, std::sync::Mutex still backs onto pthread_mutex_t and heap-allocates 64 bytes (OnceBox<AllocatedMutex>) on its first .lock(), adding an allocation, non-inlined pthread calls, and pthread_mutex_destroy teardown to every short-lived primitive that touches its lock (observed in #397 and #398).

In #421, WaitGroup works around this locally by storing its waiter registry in crate::internal::rwlock::RwLock (std::sync::RwLock) and acquiring only .write(), because std::sync::RwLock on Apple targets uses Rust's inline queue::RwLock with zero heap allocations (~45 ms vs ~145 ms across 3.5M short-lived lock/unlock cycles on Apple Silicon). Using RwLock for exclusive-only state is semantically awkward and makes the lock 16 bytes instead of 8 bytes on futex platforms.

Scope to evaluate

  • Benchmark backing crate::internal::mutex::Mutex on target_vendor = "apple" with an inline implementation (such as std::sync::RwLock write-locking, or an equivalent OS primitive) across short-lived (WaitGroup, OnceCell, Latch, Completion, Barrier) and contended (mpsc, mpmc, once_map, singleflight) workloads in cargo x bench.
  • Check contention, fairness, and thread-QoS implications on macOS where pthread_mutex_t provides kernel priority inheritance and queue::RwLock uses bounded spinning plus thread parking.
  • If an inline implementation holds up across workloads, switch WaitGroup back to crate::internal::mutex::Mutex and remove crate::internal::rwlock if no reader-writer consumer remains.

Activity

  1. tisonkun commented on Nov 14, 2026

    @tisonkun
    MemberAuthor

    The allocation cost is reproducible, but the measurements do not support replacing every internal mutex with one of the inline backends tested so far. A narrower optimization for waiter-registration state looks promising; shared-table locks should retain their current backend for now.

    Setup and methodology

    • Baseline: 63f7c76677680ed705e8955516edd38fcd1cb1f1.
    • Machine: Apple M4 Max, macOS 26.6.2, aarch64-apple-darwin.
    • Compiler: rustc 1.101.0-nightly (8006091eb 2026-10-17).
    • Experimental backends: exclusive std::sync::RwLock; os_unfair_lock_lock; and os_unfair_lock_lock_with_flags(..., OS_UNFAIR_LOCK_FLAG_ADAPTIVE_SPIN).
    • Used the existing cargo x bench workloads and fixed round counts, comparing Asyncband revisions rather than ecosystem peers. Benchmarks include fixture construction and cleanup according to the existing harness. Backend experiments were isolated and have not been committed.
    • The baseline already uses RwLock for WaitGroup. The RwLock experiment leaves that unchanged; the native-lock experiments route WaitGroup through the experimental mutex too.

    A counting-allocator probe confirmed one 64-byte Rust allocation per freshly locked standard Mutex: 3.5 million instances produced 3.5 million allocations totaling 224 million requested bytes. The RwLock path eliminated that per-instance allocation. This does not imply that thread-parking infrastructure is universally allocation-free.

    Short-lived and waiter-registration workloads

    Times below are medians in milliseconds, with three samples per backend. The initial standard-Mutex/RwLock runs alternated backend order; the two native variants were measured in subsequent batches. Treat small differences as inconclusive.

    Scenario Rounds Current RwLock write Unfair lock Unfair + adaptive spin
    once::get_or_init::initialize_cell_waiter_batch/1 1,000,000 164 122 122 120
    completion::notify_pending 2,000,000 173 125 127 127
    latch::wait::waiter_fan_out/1 1,000,000 102 68 65 70
    barrier::wait::cancel_pending 2,000,000 118 49 54 54
    waitgroup/complete-waiter 3,500,000 93 92 93 105

    The unqueued OnceCell initialization workload was only 11–13 ms at the median across these variants, so this experiment does not establish a meaningful improvement for that fast path. Removing an internal allocation only helps paths that actually touch the lock.

    Contention changes the result

    The following workloads were rerun with five samples per backend and alternating forward/reverse backend order. Cells show median [minimum–maximum], in milliseconds.

    Scenario Work Standard Mutex RwLock write Unfair lock Unfair + adaptive spin
    OnceMap get_hit_same_key/threads=2 4,000,000 total operations 49 [47–50] 34 [32–37] 226 [192–238] 196 [175–205]
    mpmc/bounded/tasks-2p2c-cap64-4w 270 rounds 291 [288–294] 169 [161–172] 442 [437–469] 427 [419–434]

    RwLock wins those cases, but regresses substantially at eight threads. Separate five-sample, alternating-order standard-Mutex/RwLock comparisons produced:

    Scenario Work Standard Mutex RwLock write RwLock/current
    OnceMap get_hit_same_key/threads=8 16,000,000 total operations 398 [384–422] 928 [811–1015] 2.33x
    SingleFlight distributed_leaders/threads=8 1,000,000 total operations 178 [175–189] 395 [377–402] 2.22x

    Ordinary unfair locking performed better in separate five-sample eight-thread comparisons: OnceMap was 373 [353–385] ms against its paired baseline of 393 [385–406] ms; SingleFlight was 158 [145–167] ms against 178 [174–192] ms. That does not offset its regressions in the two-thread and channel workloads above. The adaptive-spin variant also failed to remove those regressions.

    These are single-machine throughput measurements, not evidence of starvation freedom or acceptable mixed-QoS tail latency.

    Backend tradeoffs and implementation constraints

    • RwLock write-only: no new dependency or OS-version requirement, and the queue implementation already exists in Rust 1.86. It uses bounded spinning and parking, with stack-allocated waiter nodes. It is deliberately unfair and does not provide the same owner-based priority-inversion mitigation as Apple's mutexes. Its implementation details are not a permanent standard-library API guarantee. Rust 1.86 queue RwLock
    • Generic compatibility matters: simply replacing Mutex<T> with RwLock<T> strengthens the Sync requirement from T: Send to T: Send + Sync, affecting supported payloads such as Cell<u8>. An exclusive-only wrapper that restores mutex-like bounds must prevent all shared-read access, including formatting: forwarding to RwLock's Debug implementation would violate that design. The semaphore helper also explicitly names std::sync::MutexGuard and would need a backend-neutral internal guard type.
    • Native unfair lock: inline storage and owner information allow the OS to mitigate priority inversion. A Rust wrapper must establish address stability while the lock is in use, same-thread unlocking, correct guard traits, unwind behavior, and what happens if a guard is leaked before the containing value moves. It does not promise FIFO acquisition. The current internal wrapper already recovers poisoned locks, so preserving poisoning errors is not a caller requirement, but unwind and destruction behavior still need review. Apple lock contract
    • Native adaptive spinning: the public flag API requires macOS 15, iOS/tvOS 18, watchOS 11, or visionOS 2. Supporting older deployment targets needs an availability/fallback design. Apple recommends the flag only for consistently very short critical sections, and it was not a general performance win here.
    • QoS cannot be inferred from throughput: Apple explicitly distinguishes owner-aware pthread_mutex_t/os_unfair_lock from ownerless semaphore waits. A RwLock substitution changes this behavior even when used exclusively. Apple scheduling guidance
    • A custom futex mutex is not an obvious improvement: Apple's public wait-on-address API does not provide priority-inversion avoidance. Reimplementing a mutex over it adds synchronization code without resolving that tradeoff. Apple wait-on-address documentation

    The RwLock and ordinary native-lock prototypes each passed cargo x test (704 tests, including doctests). This establishes basic compatibility with the existing suite, not a complete unsafe-code or platform audit. No full Miri, older-OS, cross-architecture, or mixed-QoS latency validation was performed.

    Recommended follow-up scope

    1. Keep internal::mutex::Mutex on its current backend for general shared state, especially OnceMap and SingleFlight. The data does not justify a global replacement.
    2. Give the existing WaitGroup optimization an explicitly exclusive interface, exposing lock() rather than a reader/writer API. A narrowly scoped internal wrapper could use RwLock write-locking on Apple and standard Mutex elsewhere. Benchmark the non-Apple change separately; the measurements above only cover Apple.
    3. Evaluate Completion, Latch, and Barrier waiting state as the next bounded expansion. Their measured gains justify further work, but adopting the RwLock backend still requires an explicit decision about the QoS tradeoff and validation under mixed priorities and CPU saturation.
    4. Treat OnceCell separately because changing its shared semaphore machinery affects other primitives too. Keep channel backend changes separate as well: the favorable RwLock throughput results do not establish acceptable fairness or QoS behavior.
    5. Remove or rename internal::rwlock only as part of that exclusive-interface cleanup, once there is no remaining reader/writer consumer. Do not make a universal backend switch a prerequisite for cleaning up the WaitGroup special case.

    The useful next step is a focused waiter-state experiment with allocation, throughput, and mixed-QoS latency evidence. A broader replacement should require new evidence that addresses the contention regressions above.

  2. QwQBiG commented on Nov 20, 2026

    @QwQBiG
    Member

    I tested the proposed WaitGroup change on x86_64 Linux under WSL2 (Ryzen 9 8945HX, Rust 1.99.0, 60ebf37). Switching the waiter lock from a write-locked RwLock to Mutex reduced the single allocation in WaitGroup::new() from 56 to 48 bytes. The WaitGroup and Wait handles stayed at 8 and 24 bytes, respectively.

    I alternated the two builds over 10 pairs of runs. Median elapsed times were:

    Workload RwLock Mutex
    wait-after-work, 5.5M rounds 295 ms 299 ms
    complete-waiter, 3.5M rounds 258 ms 268 ms
    drain-4-observers, 2.5M rounds 533.5 ms 505 ms
    4 threads, 800k register/cancel pairs total 175.0 ms 182.3 ms

    The timing ranges overlapped in every workload. On this host, the clearest reason to use Mutex for the waiter list is the 8-byte saving per group. cargo x test and cargo x check both passed with the change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions