Repository navigation
perf(semaphore): avoid allocating queue storage for the first waiter - #415
rokadepiyush49-rgb wants to merge 1 commit into
Conversation
Keep the only waiter of a WaitList inline instead of allocating arena storage for it. A second concurrent waiter moves the node into the arena under the same WaiterId, and the arena is then retained for reuse.
|
Thanks @rokadepiyush49-rgb for the clean Those benchmark numbers answered the core question in #400 decisively: while fresh single-waiter cases speed up by avoiding the initial Because See #400 for the full summary. Closing this PR accordingly—thanks again for the thorough benchmark data! |
Summary
Keep the only node of a
WaitListinline so the first wait on a fresh primitive no longer allocates queue storage. A second concurrent waiter moves that node into the arena under theWaiterIdits owner already holds, and the arena is then retained, so waiter order, permit accounting, and cancellation are unchanged.A fresh zero-permit
Semaphorehandoff drops from two allocations (256 bytes) to one: the 64-byte lazily boxed macOS mutex, which Linux does not have. Reused handoffs stay at zero allocations.Measured on an Apple M4 (macOS, Rust 1.94.1) with alternating runs. The host had background load, so each cell is the fastest run observed for that build. Lower is faster.
semaphore::acquire::handoff_permitsemaphore::acquire::cancel_pending_acquirecondvar::wait::notify_waiterevent::wait::cancel_pendingrwlock::write::readers_then_queued_writer/1semaphore::acquire::reused_handoff_permitsemaphore::acquire::queued_owned_burst/4semaphore::acquire::queued_owned_burst/16mutex::lock::queued_handoff_cycle/4once::get_or_init::initialize_cell_waiter_batch/4event::wait::waiter_fan_out/4This is a trade-off. Across the 31 semaphore, mutex, rwlock, once, condvar, and event rows measured, single-waiter rows range from 0.70× to 1.05× and rows queueing four or more waiters range from 0.86× to 1.11×, because every node lookup now checks which storage is active.
Add a
reused_handoff_permitbenchmark for the reused case and regression coverage for multi-permit ordering, cancellation after a partial or full grant, a granted waiter surviving queue growth, waker replacement after growth, and missed wakeups on fresh semaphores.Fixes #400.
Design Notes
The two storage forms share space, so
WaitListgrows by 8 bytes (Semaphorefrom 88 to 96) andWaiterIdkeeps its niche, leaving the acquisition futures from #394 unchanged. A separate inline field would add 48 bytes and measured slower. Storing the node in the future would undo #394.