adriangb commented on code in PR #27932:
URL: https://github.com/apache/datafusion/pull/27932#discussion_r4763871370
##########
benchmarks/src/util/reset.rs:
##########
@@ -0,0 +1,226 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF)
under one or more contributor license agreements
+
+//! Returns memory to the OS between iterations, so that the speed of an
+//! iteration does not depend on what ran before it.
+//!
+//! mimalloc can collect only the heap of the calling thread, so
[`reset_memory`]
+//! runs a collection on every thread of the Tokio runtime:
+//!
+//! ```text
+//! each thread: arrive ── collect ── arrive ── collect ── arrive
+//! │ │
+//! │ └ frees memory that another thread
+//! │ owned and released in round one
+//! └ holds the thread, so no thread runs two of the tasks
+//! ```
+
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Condvar, Mutex};
+use std::time::Duration;
+
+use datafusion_common::instant::Instant;
+use tokio::runtime::{Builder, Handle, Runtime};
+
+/// Longest wait for a busy thread. An idle runtime needs milliseconds.
+const TIMEOUT: Duration = Duration::from_secs(2);
+
+/// How often the main thread wakes workers while it waits.
+const NUDGE_INTERVAL: Duration = Duration::from_millis(1);
+
+/// Worker and blocking threads of the runtime that [`build_runtime`] returns.
+static THREADS: AtomicUsize = AtomicUsize::new(0);
+
+/// Builds the multi-threaded runtime that `--reset-memory` needs.
+pub fn build_runtime() -> std::io::Result<Runtime> {
+ Builder::new_multi_thread()
+ .enable_all()
+ .on_thread_start(|| {
+ THREADS.fetch_add(1, Ordering::SeqCst);
+ })
+ .on_thread_stop(|| {
+ THREADS.fetch_sub(1, Ordering::SeqCst);
+ })
+ .build()
+}
+
+/// A barrier that stops waiting at a deadline.
+struct Gate {
+ expected: usize,
+ deadline: Instant,
+ state: Mutex<GateState>,
+ changed: Condvar,
+}
+
+impl Gate {
+ fn new(expected: usize, deadline: Instant) -> Self {
+ Self {
+ expected,
+ deadline,
+ state: Mutex::new(GateState::default()),
+ changed: Condvar::new(),
+ }
+ }
+
+ /// Returns whether all threads arrived before the deadline.
+ ///
+ /// A thread that the timeout releases can run the task of the busy thread.
+ /// That late arrival must not complete the count, so a timeout closes the
+ /// gate for all threads.
+ ///
+ /// A worker takes tasks in batches. It can block here with the task of a
+ /// parked worker in its local queue, and nothing wakes that worker. The
+ /// main thread passes `nudge` to spawn empty tasks, which wake workers
until
+ /// one of them steals the task.
+ fn arrive(&self, nudge: Option<&Handle>) -> bool {
+ let mut state = self.state.lock().unwrap();
+ state.arrived += 1;
+ if state.arrived == self.expected && !state.closed {
+ self.changed.notify_all();
+ return true;
+ }
+ while !state.closed && state.arrived < self.expected {
+ let now = Instant::now();
+ if now >= self.deadline {
+ state.closed = true;
+ self.changed.notify_all();
+ break;
+ }
+ let mut wait = self.deadline - now;
+ if let Some(handle) = nudge {
+ handle.spawn(async {});
+ wait = wait.min(NUDGE_INTERVAL);
+ }
+ (state, _) = self.changed.wait_timeout(state, wait).unwrap();
+ }
+ !state.closed
+ }
+}
+
+#[derive(Default)]
+struct GateState {
+ arrived: usize,
+ closed: bool,
+}
+
+fn on_every_thread(
+ handle: &Handle,
+ workers: usize,
+ blocking: usize,
+ timeout: Duration,
+ action: fn(),
+) -> bool {
+ let deadline = Instant::now() + timeout;
+ let expected = workers + blocking + 1;
+ let gates: Arc<[Gate; 3]> =
Review Comment:
That's exactly what it's trying to do. Do you know of an easier way to do
that? Maybe we can install some sort of listener hook on thread startup...
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]