You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@asyncband.apache.org by ti...@apache.org on 2026/09/03 17:35:21 UTC
(asyncband) 01/07: refactor(internal): extract lifecycle-free waker set
This is an automated email from the ASF dual-hosted git repository.
tisonkun pushed a commit to branch codex/specialize-waker-sets
in repository https://gitbox.apache.org/repos/asf/asyncband.git
commit 52a0db2c696dea3fa078c9eadd3ee1dbe0a1cefb
Author: tison <wa...@gmail.com>
AuthorDate: Fri Sep 4 01:27:42 2026 +0800
refactor(internal): extract lifecycle-free waker set
---
asyncband/src/internal/mod.rs | 15 ++++
asyncband/src/internal/waitset.rs | 65 +++++---------
asyncband/src/internal/wakerset.rs | 175 +++++++++++++++++++++++++++++++++++++
asyncband/src/waitgroup/mod.rs | 33 +++----
4 files changed, 226 insertions(+), 62 deletions(-)
diff --git a/asyncband/src/internal/mod.rs b/asyncband/src/internal/mod.rs
index fd01bc7..10bede0 100644
--- a/asyncband/src/internal/mod.rs
+++ b/asyncband/src/internal/mod.rs
@@ -129,6 +129,7 @@ pub(crate) mod waitlist;
feature = "once",
feature = "rwlock",
feature = "semaphore",
+ feature = "waitgroup",
feature = "watch",
))]
// Wait-set primitives know the exact batch capacity, while linked-list primitives use the
@@ -148,3 +149,17 @@ pub(crate) mod waker_batch;
// primitives use `new`. One constructor is therefore unused in every single-primitive build.
#[allow(dead_code)]
pub(crate) mod waitset;
+
+#[cfg(any(
+ feature = "barrier",
+ feature = "broadcast",
+ feature = "completion",
+ feature = "latch",
+ feature = "once",
+ feature = "waitgroup",
+ feature = "watch",
+))]
+// Reusable wait sets and terminal primitives use different lifecycle policies, so some feature
+// subsets leave one constructor or detach operation unused.
+#[allow(dead_code)]
+pub(crate) mod wakerset;
diff --git a/asyncband/src/internal/waitset.rs b/asyncband/src/internal/waitset.rs
index e34a499..1aff440 100644
--- a/asyncband/src/internal/waitset.rs
+++ b/asyncband/src/internal/waitset.rs
@@ -21,12 +21,10 @@
//! borrowed [`Waker`], while replacement and removal return owned wakers so callers can drop or
//! wake them after unlocking.
-use std::mem;
use std::task::Waker;
-use crate::internal::arena::Arena;
-use crate::internal::arena::SlotId;
-use crate::internal::waker_batch::WakerBatch;
+use crate::internal::wakerset;
+use crate::internal::wakerset::WakerSet;
/// An exclusive handle to one waiter slot in a [`WaitSet`].
///
@@ -36,13 +34,13 @@ use crate::internal::waker_batch::WakerBatch;
#[derive(Debug)]
pub struct WakerToken {
epoch: u64,
- slot: SlotId,
+ token: wakerset::WakerToken,
}
#[derive(Debug)]
pub struct WaitSet {
epoch: u64,
- waiters: Arena<Waker>,
+ wakers: WakerSet,
}
impl WaitSet {
@@ -50,7 +48,7 @@ impl WaitSet {
pub const fn new() -> Self {
Self {
epoch: 0,
- waiters: Arena::new(),
+ wakers: WakerSet::new(),
}
}
@@ -58,7 +56,7 @@ impl WaitSet {
pub fn with_capacity(capacity: usize) -> Self {
Self {
epoch: 0,
- waiters: Arena::with_capacity(capacity),
+ wakers: WakerSet::with_capacity(capacity),
}
}
@@ -69,13 +67,11 @@ impl WaitSet {
/// releasing the lock that protects this wait set.
#[inline]
pub fn drain(&mut self) -> impl Iterator<Item = Waker> + 'static {
- let mut wakers = WakerBatch::with_capacity(self.waiters.len());
- if self.waiters.is_empty() {
- return wakers.into_iter();
+ if self.wakers.is_empty() {
+ return self.wakers.drain();
}
self.advance_epoch();
- wakers.extend(self.waiters.drain());
- wakers.into_iter()
+ self.wakers.drain()
}
/// Takes all registered wakers and the wait set's backing allocation without waking them.
@@ -85,10 +81,10 @@ impl WaitSet {
/// this wait set.
#[inline]
pub fn take_all(&mut self) -> impl Iterator<Item = Waker> + 'static {
- if !self.waiters.is_empty() {
+ if !self.wakers.is_empty() {
self.advance_epoch();
}
- self.waiters.take_all()
+ self.wakers.take_all()
}
/// Registers or updates a waker in the current wake epoch.
@@ -98,18 +94,16 @@ impl WaitSet {
#[inline]
#[must_use = "drop the returned waker after releasing the wait set's state lock"]
pub fn register(&mut self, token: &mut Option<WakerToken>, waker: &Waker) -> Option<Waker> {
- if let Some(current) = self.current_waker(token) {
- if current.will_wake(waker) {
- return None;
- }
- return Some(mem::replace(current, waker.clone()));
- }
-
- *token = Some(WakerToken {
+ let mut current = match token.take() {
+ Some(token) if token.epoch == self.epoch => Some(token.token),
+ _ => None,
+ };
+ let retired = self.wakers.register(&mut current, waker);
+ *token = current.map(|token| WakerToken {
epoch: self.epoch,
- slot: self.waiters.insert(waker.clone()),
+ token,
});
- None
+ retired
}
/// Removes the waker identified by `token` if it still belongs to the current wake epoch.
@@ -119,23 +113,12 @@ impl WaitSet {
#[must_use = "drop the returned waker after releasing the wait set's state lock"]
pub fn unregister(&mut self, token: &mut Option<WakerToken>) -> Option<Waker> {
let token = token.take()?;
- if token.epoch == self.epoch {
- return Some(self.waiters.remove(token.slot));
- }
- // A drain advanced the epoch and already took ownership of this token's waker.
- None
- }
-
- fn current_waker(&mut self, token: &Option<WakerToken>) -> Option<&mut Waker> {
- let current = token.as_ref()?;
- if current.epoch != self.epoch {
+ if token.epoch != self.epoch {
+ // A drain advanced the epoch and already took ownership of this token's waker.
return None;
}
- Some(
- self.waiters
- .get_mut(current.slot)
- .expect("current waker token must refer to an occupied slot"),
- )
+ let mut current = Some(token.token);
+ self.wakers.unregister(&mut current)
}
fn advance_epoch(&mut self) {
@@ -144,7 +127,7 @@ impl WaitSet {
#[cfg(test)]
fn registered_len(&self) -> usize {
- self.waiters.len()
+ self.wakers.registered_len()
}
}
diff --git a/asyncband/src/internal/wakerset.rs b/asyncband/src/internal/wakerset.rs
new file mode 100644
index 0000000..eb11366
--- /dev/null
+++ b/asyncband/src/internal/wakerset.rs
@@ -0,0 +1,175 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Cancellable storage for task wakers whose lifecycle is owned by the caller.
+//!
+//! A `WakerSet` is protected by the state lock of its owning primitive. The owner must clear a
+//! token instead of unregistering it after an operation that detached the set. This lets each
+//! primitive use its existing terminal state or generation to recognize stale registrations.
+
+use std::mem;
+use std::task::Waker;
+
+use crate::internal::arena::Arena;
+use crate::internal::arena::SlotId;
+use crate::internal::waker_batch::WakerBatch;
+
+/// An exclusive handle to one waker slot in a [`WakerSet`].
+///
+/// This token deliberately does not implement `Clone` or `Copy`. Its owner must not pass it back
+/// to the set after the registration has been detached by [`WakerSet::drain`] or
+/// [`WakerSet::take_all`].
+#[derive(Debug)]
+pub struct WakerToken(SlotId);
+
+/// Cancellable waker storage without an implicit lifecycle or generation.
+#[derive(Debug)]
+pub struct WakerSet {
+ wakers: Arena<Waker>,
+}
+
+impl WakerSet {
+ /// Constructs an empty waker set.
+ pub const fn new() -> Self {
+ Self {
+ wakers: Arena::new(),
+ }
+ }
+
+ /// Constructs an empty waker set with the specified capacity.
+ pub fn with_capacity(capacity: usize) -> Self {
+ Self {
+ wakers: Arena::with_capacity(capacity),
+ }
+ }
+
+ /// Drains all registered wakers into an owning batch while retaining slot capacity.
+ ///
+ /// The caller must invalidate every outstanding token and consume or drop the iterator after
+ /// releasing the lock that protects this set.
+ #[inline]
+ pub fn drain(&mut self) -> impl Iterator<Item = Waker> + 'static {
+ let mut wakers = WakerBatch::with_capacity(self.wakers.len());
+ if self.wakers.is_empty() {
+ return wakers.into_iter();
+ }
+ wakers.extend(self.wakers.drain());
+ wakers.into_iter()
+ }
+
+ /// Takes all registered wakers together with the set's backing allocation.
+ ///
+ /// The caller must invalidate every outstanding token and consume or drop the iterator after
+ /// releasing the lock that protects this set.
+ #[inline]
+ pub fn take_all(&mut self) -> impl Iterator<Item = Waker> + 'static {
+ self.wakers.take_all()
+ }
+
+ /// Registers or updates a waker.
+ ///
+ /// If an existing waker is replaced, it is returned so the caller can drop it after releasing
+ /// the lock that protects this set.
+ #[inline]
+ #[must_use = "drop the returned waker after releasing the waker set's state lock"]
+ pub fn register(&mut self, token: &mut Option<WakerToken>, waker: &Waker) -> Option<Waker> {
+ if let Some(current) = token.as_ref().map(|token| {
+ self.wakers
+ .get_mut(token.0)
+ .expect("waker token must refer to an occupied slot")
+ }) {
+ if current.will_wake(waker) {
+ return None;
+ }
+ return Some(mem::replace(current, waker.clone()));
+ }
+
+ *token = Some(WakerToken(self.wakers.insert(waker.clone())));
+ None
+ }
+
+ /// Removes the waker identified by `token`.
+ ///
+ /// The owner must clear stale tokens without calling this method after detaching the set. The
+ /// returned waker must be dropped after releasing the lock that protects this set.
+ #[inline]
+ #[must_use = "drop the returned waker after releasing the waker set's state lock"]
+ pub fn unregister(&mut self, token: &mut Option<WakerToken>) -> Option<Waker> {
+ token.take().map(|token| self.wakers.remove(token.0))
+ }
+
+ #[cfg(test)]
+ fn registered_len(&self) -> usize {
+ self.wakers.len()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::mem::size_of;
+ use std::sync::Arc;
+ use std::sync::atomic::AtomicBool;
+ use std::sync::atomic::AtomicUsize;
+ use std::sync::atomic::Ordering;
+ use std::task::Wake;
+
+ use super::*;
+
+ struct DropWake {
+ dropped: Arc<AtomicBool>,
+ wake_count: AtomicUsize,
+ }
+
+ impl Wake for DropWake {
+ fn wake(self: Arc<Self>) {
+ self.wake_count.fetch_add(1, Ordering::Relaxed);
+ }
+ }
+
+ impl Drop for DropWake {
+ fn drop(&mut self) {
+ self.dropped.store(true, Ordering::Relaxed);
+ }
+ }
+
+ #[test]
+ fn waker_token_preserves_the_option_niche() {
+ assert_eq!(size_of::<WakerToken>(), size_of::<usize>());
+ assert_eq!(size_of::<WakerToken>(), size_of::<Option<WakerToken>>());
+ }
+
+ #[test]
+ fn unregister_returns_the_waker_for_deferred_drop() {
+ let dropped = Arc::new(AtomicBool::new(false));
+ let waker = Waker::from(Arc::new(DropWake {
+ dropped: dropped.clone(),
+ wake_count: AtomicUsize::new(0),
+ }));
+ let mut wakers = WakerSet::new();
+ let mut token = None;
+
+ drop(wakers.register(&mut token, &waker));
+ drop(waker);
+
+ let removed = wakers.unregister(&mut token);
+ assert_eq!(wakers.registered_len(), 0);
+ assert!(!dropped.load(Ordering::Relaxed));
+
+ drop(removed);
+ assert!(dropped.load(Ordering::Relaxed));
+ }
+}
diff --git a/asyncband/src/waitgroup/mod.rs b/asyncband/src/waitgroup/mod.rs
index 03a0cb9..3ea48a5 100644
--- a/asyncband/src/waitgroup/mod.rs
+++ b/asyncband/src/waitgroup/mod.rs
@@ -60,26 +60,25 @@ use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::task::Context;
use std::task::Poll;
-use std::task::Waker;
-use crate::internal::arena::Arena;
-use crate::internal::arena::SlotId;
use crate::internal::mutex::Mutex;
use crate::internal::wake_all;
+use crate::internal::wakerset::WakerSet;
+use crate::internal::wakerset::WakerToken;
#[derive(Debug)]
struct State {
// Wait futures also own the state allocation, so Arc's strong count cannot represent handles.
// Zero is terminal: after it is published, no new handle or waiter can be registered.
handles: AtomicUsize,
- waiters: Mutex<Arena<Waker>>,
+ waiters: Mutex<WakerSet>,
}
impl State {
fn new() -> Self {
Self {
handles: AtomicUsize::new(1),
- waiters: Mutex::new(Arena::new()),
+ waiters: Mutex::new(WakerSet::new()),
}
}
@@ -105,7 +104,7 @@ impl State {
wake_all(wakers);
}
- fn poll_wait(&self, token: &mut Option<SlotId>, cx: &mut Context<'_>) -> Poll<()> {
+ fn poll_wait(&self, token: &mut Option<WakerToken>, cx: &mut Context<'_>) -> Poll<()> {
if self.handles.load(Ordering::Acquire) == 0 {
*token = None;
return Poll::Ready(());
@@ -118,25 +117,16 @@ impl State {
return Poll::Ready(());
}
- if let Some(current) = token.and_then(|id| waiters.get_mut(id)) {
- if current.will_wake(cx.waker()) {
- None
- } else {
- Some(std::mem::replace(current, cx.waker().clone()))
- }
- } else {
- *token = Some(waiters.insert(cx.waker().clone()));
- None
- }
+ waiters.register(token, cx.waker())
};
drop(retired_waker);
Poll::Pending
}
- fn unregister(&self, token: &mut Option<SlotId>) {
- let Some(id) = token.take() else {
+ fn unregister(&self, token: &mut Option<WakerToken>) {
+ if token.is_none() {
return;
- };
+ }
let removed_waker = {
let mut waiters = self.waiters.lock();
@@ -144,9 +134,10 @@ impl State {
// already taken it. Unlike reusable wait sets, no epoch is needed to disambiguate a
// later registration.
if self.handles.load(Ordering::Acquire) == 0 {
+ *token = None;
None
} else {
- Some(waiters.remove(id))
+ waiters.unregister(token)
}
};
drop(removed_waker);
@@ -235,7 +226,7 @@ impl IntoFuture for WaitGroup {
/// adding a worker to the group.
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Wait {
- token: Option<SlotId>,
+ token: Option<WakerToken>,
state: Arc<State>,
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@asyncband.apache.org
For additional commands, e-mail: commits-help@asyncband.apache.org