Repository navigation
fix(once): broadcast completion across Once and OnceCell and add OnceCell::wait - #446
Merged
Merged
Conversation
…state `Once` previously combined a `CountdownState` for observers with a one-permit `Semaphore` for `call_once` callers. That representation carried two mutexes (`144 B`), locked the semaphore queue on every uncontended completion because the single permit left `available == 0`, woke concurrent `call_once` followers one at a time as permits returned, and left trailing `call_once` callers blocked if the head follower stopped polling without dropping. Introduce `internal::once_state::OnceState` to separate exclusive initializer selection from completion notification. Uncontended initialization transitions `UNINIT -> RUNNING -> COMPLETE` with atomic compare-exchanges and no mutex acquisitions, single-waiter contention uses an inline slot without allocating an arena, aborted attempts hand leadership to at most one queued candidate in FIFO order without waking pure `wait` observers, and successful completion broadcasts to every queued candidate and observer at once.
…hore state `OnceCell` previously serialized `get_or_init` and `get_or_try_init` callers through a three-permit `Semaphore`, taking two permits per initializer. When the active initializer published a value and released its two permits, only the head waiting caller could become ready; each follower had to be scheduled and drop its temporary permit before the next follower was woken, and a head waiter that stopped polling without dropping kept trailing callers in `OnceCell`, `OnceMap`, and `singleflight::Group` blocked even after the value was published. Switch `OnceCell` from `Semaphore` to `OnceState` so publication wakes every queued caller at once and releases overflow waiter storage immediately, while failed, panicked, or cancelled attempts still hand off to at most one queued candidate in FIFO order.
`Once` provides `Once::wait` for callers that need to observe completion without supplying an initializer, whereas `OnceCell` required every waiting caller to pass a dummy closure to `get_or_init`. Expose `OnceCell::wait(&self) -> &T` backed by `OnceState::wait`. Pending observer waits stay asleep across failed or cancelled initialization attempts, wake in parallel when a value is published, and unregister cleanly on cancellation without affecting active initializers or other waiters.
8 tasks done
…sets Clearing `HAS_WAITERS` when the last waiter cancelled or claimed leadership previously left an empty `Box<OverflowWaiters>` in `Waiters::overflow`, allowing a subsequent lock-free `RUNNING -> COMPLETE` transition to retain burst waiter capacity until the primitive dropped. `OnceCell::get_mut_or_try_init` also called `complete_mut()` redundantly when a value was already stored. Take and drop `Waiters::overflow` outside the waiter lock whenever the last waiter leaves so `HAS_WAITERS == 0` implies no retained overflow allocation, guard `complete_mut` and `reset_mut` on `HAS_WAITERS` before taking `Waiters`, and replace the `get_mut_or_try_init` hit-path `complete_mut()` call with a debug assertion.
This was referenced Nov 21, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Part of #445.
Problem
OnceandOnceCellpreviously serialized concurrent initializers through fixed-permitSemaphoreinstances (Semaphore::new(1)alongside aCountdownStateinOnce, andSemaphore::new(3)with two permits per initializer inOnceCell):select!or state machine remained active), trailing callers inOnce,OnceCell,OnceMap, andsingleflight::Groupreceived no wakeup and remainedPendingeven though initialization was already complete.Oncealso carried two mutexes (144 Bon 64-bit Apple targets) and took the semaphore's waiter lock on every uncontended completion because its single permit leftavailable == 0.OnceCell: UnlikeOnce::wait,OnceCellhad no observer-only entry point for callers that want to await publication without supplying an initializer.Solution
internal::once_state::OnceState: Separate exclusive initializer ownership from completion broadcast behind a compact atomic state (UNINIT,RUNNING,HAS_WAITERS,COMPLETE) and one waiter mutex:UNINIT -> RUNNING -> COMPLETE(orRUNNING -> UNINITon error/cancellation) via single atomic compare-exchanges without locking.waitobservers.OnceandOnceCellontoOnceState: ShrinksOncefrom144 Bto56 BandOnceCell<u64>from88 Bto72 Bon 64-bit macOS while unblockingOnceMapandsingleflight::Groupfollowers simultaneously upon publication.OnceCell::wait(&self) -> &T: Allows observers to await value publication without providing a closure; cancelling a pendingwaitunregisters only that observer.Benchmarks
Apple M4 Max (macOS arm64), whole-batch medians across 7 runs (
once,once_map) and 5 runs (singleflight), lower is faster:main(d436cd9)once::get_or_init::initialize_cell-28.2%once::get_or_init::initialized_cell-3.8%once::get_or_init::initialize_cell_waiter_batch/1-22.0%once::get_or_init::initialize_cell_waiter_batch/4-24.6%once::get_or_init::initialize_cell_waiter_batch/16-37.9%once::wait::complete_waiter-36.1%once::wait::complete_waiter_batch/1-29.0%once::wait::complete_waiter_batch/4-1.7%once::wait::complete_waiter_batch/16-1.1%once::wait::cancel_pending_wait-32.5%once_map::initialize::initialize_same_key/2-27.6%once_map::initialize::initialize_same_key/4-20.8%once_map::initialize::initialize_same_key/16-31.2%singleflight::coalescing::complete_coalesced/2-17.5%singleflight::coalescing::complete_coalesced/4-12.9%singleflight::coalescing::complete_coalesced/16-30.0%singleflight::coalescing::coalesced_retry_after_leader_error/16-28.3%singleflight::leaders::leader_success-8.7%singleflight::leaders::leader_error-15.1%Validation
cargo x lintcargo x checkcargo x testWakeCounterregressions for paused head followers, FIFO cancellation handoff, and observer-only waits acrossonce_test,once_cell_test,singleflight_test, and Miri