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/08/26 14:28:06 UTC

(asyncband) branch main updated: test: add multithreaded contention benchmarks (#202)

This is an automated email from the ASF dual-hosted git repository.

tisonkun pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/asyncband.git


The following commit(s) were added to refs/heads/main by this push:
     new c461305  test: add multithreaded contention benchmarks (#202)
c461305 is described below

commit c46130566e8581cc41c70e6d2232724cdad075a8
Author: An Long <ai...@users.noreply.github.com>
AuthorDate: Wed Aug 26 23:28:00 2026 +0900

    test: add multithreaded contention benchmarks (#202)
    
    Co-authored-by: Claude Fable 5 <no...@anthropic.com>
---
 benchmarks/once_map.rs     | 125 ++++++++++++++++++++++++++++++++++++++++++++-
 benchmarks/singleflight.rs |  55 +++++++++++++++++++-
 benchmarks/support.rs      |  49 ++++++++++++++++++
 3 files changed, 227 insertions(+), 2 deletions(-)

diff --git a/benchmarks/once_map.rs b/benchmarks/once_map.rs
index 7f5b039..512fc0e 100644
--- a/benchmarks/once_map.rs
+++ b/benchmarks/once_map.rs
@@ -15,6 +15,8 @@
 // specific language governing permissions and limitations
 // under the License.
 
+use std::cell::Cell;
+
 use asyncband::once::OnceMap;
 use divan::Bencher;
 use divan::black_box;
@@ -24,10 +26,17 @@ use super::support::defer_input_drop;
 use super::support::poll_pending;
 use super::support::poll_pinned_ready;
 use super::support::poll_ready;
+use super::support::spin_poll_ready;
+use super::support::thread_slot_ticket;
 use super::support::wait_until_open;
+use super::support::yield_polls;
 
 const CACHED_ENTRY_COUNTS: &[usize] = &[0, 64, 1024];
 const WAITER_COUNTS: &[usize] = &[1, 8, 32];
+const CONTENDED_ENTRY_COUNTS: &[usize] = &[64, 1024];
+const THREAD_COUNTS: &[usize] = &[1, 2, 8, 32];
+const MISS_KEY_SPAN: usize = 1 << 16;
+const COALESCED_LEADER_POLLS: usize = 32;
 
 #[divan::bench]
 fn compute_vacant(bencher: Bencher) {
@@ -103,4 +112,118 @@ fn coalesced_compute_batch(bencher: Bencher, waiter_count: usize) {
         }
     });
 }
-use std::cell::Cell;
+
+fn preloaded_map(cached_entries: usize) -> OnceMap<usize, usize> {
+    (0..cached_entries).map(|key| (key, key)).collect()
+}
+
+// The contended benches share one map across OS threads and spread keys with thread_slot_ticket,
+// so "disjoint" means threads mostly touch different keys at any moment rather than strict
+// per-thread key ownership.
+#[divan::bench(threads = THREAD_COUNTS)]
+fn contended_get_hit_same_key(bencher: Bencher) {
+    let map = [(0, 1)].into_iter().collect::<OnceMap<_, _>>();
+
+    bencher.bench(|| black_box(map.get(black_box(&0))));
+}
+
+#[divan::bench(threads = THREAD_COUNTS, args = CONTENDED_ENTRY_COUNTS)]
+fn contended_get_hit_disjoint(bencher: Bencher, cached_entries: usize) {
+    let map = preloaded_map(cached_entries);
+
+    bencher.bench(|| {
+        let (slot, ticket) = thread_slot_ticket();
+        let key = (slot + ticket) % cached_entries;
+        black_box(map.get(black_box(&key)))
+    });
+}
+
+#[divan::bench(threads = THREAD_COUNTS)]
+fn contended_compute_hit_same_key(bencher: Bencher) {
+    let map = [(0, 1)].into_iter().collect::<OnceMap<_, _>>();
+
+    bencher.bench(|| {
+        let mut context = bench_context();
+        black_box(spin_poll_ready(
+            map.compute(black_box(0), || async { unreachable!() }),
+            &mut context,
+        ))
+    });
+}
+
+#[divan::bench(threads = THREAD_COUNTS, args = CONTENDED_ENTRY_COUNTS)]
+fn contended_compute_hit_disjoint(bencher: Bencher, cached_entries: usize) {
+    let map = preloaded_map(cached_entries);
+
+    bencher.bench(|| {
+        let mut context = bench_context();
+        let (slot, ticket) = thread_slot_ticket();
+        let key = (slot + ticket) % cached_entries;
+        black_box(spin_poll_ready(
+            map.compute(black_box(key), || async { unreachable!() }),
+            &mut context,
+        ))
+    });
+}
+
+#[divan::bench(threads = THREAD_COUNTS, args = CONTENDED_ENTRY_COUNTS)]
+fn contended_compute_miss_churn(bencher: Bencher, cached_entries: usize) {
+    let map = preloaded_map(cached_entries);
+
+    bencher.bench(|| {
+        let mut context = bench_context();
+        let (slot, ticket) = thread_slot_ticket();
+        let key = cached_entries + slot * MISS_KEY_SPAN + ticket % MISS_KEY_SPAN;
+        let value = spin_poll_ready(
+            map.compute(black_box(key), || async move { key }),
+            &mut context,
+        );
+        map.discard(&key);
+        black_box(value)
+    });
+}
+
+#[divan::bench(threads = THREAD_COUNTS, args = CONTENDED_ENTRY_COUNTS)]
+fn contended_compute_mixed(bencher: Bencher, cached_entries: usize) {
+    let map = preloaded_map(cached_entries);
+
+    bencher.bench(|| {
+        let mut context = bench_context();
+        let (slot, ticket) = thread_slot_ticket();
+        if ticket % 2 == 0 {
+            let key = (slot + ticket / 2) % cached_entries;
+            black_box(spin_poll_ready(
+                map.compute(black_box(key), || async { unreachable!() }),
+                &mut context,
+            ))
+        } else {
+            let key = cached_entries + slot * MISS_KEY_SPAN + (ticket / 2) % MISS_KEY_SPAN;
+            let value = spin_poll_ready(
+                map.compute(black_box(key), || async move { key }),
+                &mut context,
+            );
+            map.discard(&key);
+            black_box(value)
+        }
+    });
+}
+
+// The leader stays in flight for several polls so calls on other threads coalesce as duplicate
+// waiters, and discards the key while in flight so every cycle re-runs the vacant-leader path
+// instead of settling into steady-state hits.
+#[divan::bench(threads = THREAD_COUNTS)]
+fn contended_compute_coalesced(bencher: Bencher) {
+    let map = OnceMap::<usize, usize>::new();
+
+    bencher.bench(|| {
+        let mut context = bench_context();
+        black_box(spin_poll_ready(
+            map.compute(black_box(0), || async {
+                yield_polls(COALESCED_LEADER_POLLS).await;
+                map.discard(&0);
+                black_box(1)
+            }),
+            &mut context,
+        ))
+    });
+}
diff --git a/benchmarks/singleflight.rs b/benchmarks/singleflight.rs
index 76134bb..2e0b00f 100644
--- a/benchmarks/singleflight.rs
+++ b/benchmarks/singleflight.rs
@@ -15,6 +15,8 @@
 // specific language governing permissions and limitations
 // under the License.
 
+use std::cell::Cell;
+
 use asyncband::singleflight::Group;
 use divan::Bencher;
 use divan::black_box;
@@ -24,9 +26,15 @@ use super::support::defer_input_drop;
 use super::support::poll_pending;
 use super::support::poll_pinned_ready;
 use super::support::poll_ready;
+use super::support::spin_poll_ready;
+use super::support::thread_slot_ticket;
 use super::support::wait_until_open;
+use super::support::yield_polls;
 
 const WAITER_COUNTS: &[usize] = &[1, 8, 32];
+const THREAD_COUNTS: &[usize] = &[1, 2, 8, 32];
+const DISJOINT_KEY_SPAN: usize = 1 << 16;
+const COALESCED_LEADER_POLLS: usize = 32;
 
 #[divan::bench]
 fn work_ready(bencher: Bencher) {
@@ -84,4 +92,49 @@ fn coalesced_work_batch(bencher: Bencher, waiter_count: usize) {
         }
     });
 }
-use std::cell::Cell;
+
+#[divan::bench(threads = THREAD_COUNTS)]
+fn contended_work_same_key(bencher: Bencher) {
+    let group = Group::<usize, usize>::new();
+
+    bencher.bench(|| {
+        let mut context = bench_context();
+        black_box(spin_poll_ready(
+            group.work(black_box(0), || async { black_box(1) }),
+            &mut context,
+        ))
+    });
+}
+
+// The leader stays in flight for several polls so calls on other threads coalesce as duplicate
+// waiters instead of leading their own cycles.
+#[divan::bench(threads = THREAD_COUNTS)]
+fn contended_work_coalesced(bencher: Bencher) {
+    let group = Group::<usize, usize>::new();
+
+    bencher.bench(|| {
+        let mut context = bench_context();
+        black_box(spin_poll_ready(
+            group.work(black_box(0), || async {
+                yield_polls(COALESCED_LEADER_POLLS).await;
+                black_box(1)
+            }),
+            &mut context,
+        ))
+    });
+}
+
+#[divan::bench(threads = THREAD_COUNTS)]
+fn contended_work_disjoint_churn(bencher: Bencher) {
+    let group = Group::<usize, usize>::new();
+
+    bencher.bench(|| {
+        let mut context = bench_context();
+        let (slot, ticket) = thread_slot_ticket();
+        let key = slot * DISJOINT_KEY_SPAN + ticket % DISJOINT_KEY_SPAN;
+        black_box(spin_poll_ready(
+            group.work(black_box(key), || async move { key }),
+            &mut context,
+        ))
+    });
+}
diff --git a/benchmarks/support.rs b/benchmarks/support.rs
index 22ce1b7..ce12a63 100644
--- a/benchmarks/support.rs
+++ b/benchmarks/support.rs
@@ -22,6 +22,8 @@ use std::pin::Pin;
 use std::pin::pin;
 use std::sync::Arc;
 use std::sync::LazyLock;
+use std::sync::atomic::AtomicUsize;
+use std::sync::atomic::Ordering;
 use std::task::Context;
 use std::task::Poll;
 use std::task::Wake;
@@ -61,6 +63,53 @@ pub(super) fn poll_pending<F: Future>(mut future: Pin<&mut F>, context: &mut Con
     assert!(future.as_mut().poll(context).is_pending());
 }
 
+// Polls the future to completion, yielding between polls so a leader running on another thread can
+// make progress. The bench waker never wakes, so pending futures must be re-polled unconditionally.
+pub(super) fn spin_poll_ready<F: Future>(future: F, context: &mut Context<'_>) -> F::Output {
+    let mut future = pin!(future);
+    loop {
+        match future.as_mut().poll(context) {
+            Poll::Ready(output) => return output,
+            Poll::Pending => std::thread::yield_now(),
+        }
+    }
+}
+
+static NEXT_THREAD_SLOT: AtomicUsize = AtomicUsize::new(0);
+
+thread_local! {
+    static THREAD_SLOT: usize = NEXT_THREAD_SLOT.fetch_add(1, Ordering::Relaxed);
+    static THREAD_TICKET: Cell<usize> = const { Cell::new(0) };
+}
+
+// Key derivation for the contended benches: a shared counter would itself be a cross-thread
+// contention point inside the timed loop, so keys derive from a slot that is distinct for every OS
+// thread and a ticket that counts this thread's calls.
+pub(super) fn thread_slot_ticket() -> (usize, usize) {
+    let slot = THREAD_SLOT.with(|slot| *slot);
+    let ticket = THREAD_TICKET.with(|ticket| {
+        let current = ticket.get();
+        ticket.set(current.wrapping_add(1));
+        current
+    });
+    (slot, ticket)
+}
+
+// Stays pending for the given number of polls without registering a waker, so it must only be
+// polled through spin_poll_ready. Keeps a leader in flight long enough for calls on other threads
+// to join as waiters.
+pub(super) async fn yield_polls(mut polls: usize) {
+    poll_fn(move |_| {
+        if polls == 0 {
+            Poll::Ready(())
+        } else {
+            polls -= 1;
+            Poll::Pending
+        }
+    })
+    .await
+}
+
 // Move the input into the benchmark output so Divan drops it outside the timed section.
 #[inline]
 pub(super) fn defer_input_drop<I, O>(input: I, output: O) -> (I, O) {


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@asyncband.apache.org
For additional commands, e-mail: commits-help@asyncband.apache.org