| 1 | use std::{ |
| 2 | collections::BinaryHeap, |
| 3 | sync::Arc, |
| 4 | thread, |
| 5 | time::{Duration, Instant}, |
| 6 | }; |
| 7 | |
| 8 | use parking_lot::{Condvar, Mutex}; |
| 9 | |
| 10 | use crate::{ |
| 11 | PlatformDispatcher, Priority, RunnableVariant, profiler, |
| 12 | queue::{PriorityQueueReceiver, PriorityQueueSender}, |
| 13 | }; |
| 14 | |
| 15 | const MIN_THREADS: usize = 2; |
| 16 | |
| 17 | /// A multithreaded [`PlatformDispatcher`] for tests and benchmarks. |
| 18 | /// |
| 19 | /// Background tasks run in parallel on a pool of worker threads and timers fire |
| 20 | /// in real time on a dedicated timer thread, mirroring the production |
| 21 | /// dispatchers (see `LinuxDispatcher`). Main-thread tasks are queued until the |
| 22 | /// creating thread drains them via [`Self::run_until_idle`], since there is no |
| 23 | /// platform run loop pumping them. |
| 24 | /// |
| 25 | /// Unlike [`TestDispatcher`](crate::TestDispatcher), which runs everything on a |
| 26 | /// single thread with a virtual clock, work dispatched through this dispatcher |
| 27 | /// executes with production concurrency. |
| 28 | pub struct ThreadedDispatcher { |
| 29 | background_sender: PriorityQueueSender<RunnableVariant>, |
| 30 | main_sender: PriorityQueueSender<RunnableVariant>, |
| 31 | main_receiver: Mutex<PriorityQueueReceiver<RunnableVariant>>, |
| 32 | timers: Arc<TimerQueue>, |
| 33 | idle: Arc<IdleTracker>, |
| 34 | main_thread_id: thread::ThreadId, |
| 35 | } |
| 36 | |
| 37 | /// Tracks how many background and timer runnables are queued or running so |
| 38 | /// [`ThreadedDispatcher::run_until_idle`] knows when to stop waiting. |
| 39 | #[derive(Default)] |
| 40 | struct IdleTracker { |
| 41 | inflight: Mutex<usize>, |
| 42 | condvar: Condvar, |
| 43 | } |
| 44 | |
| 45 | impl IdleTracker { |
| 46 | fn increment(&self) { |
| 47 | *self.inflight.lock() += 1; |
| 48 | } |
| 49 | |
| 50 | fn decrement(&self) { |
| 51 | let mut inflight = self.inflight.lock(); |
| 52 | *inflight -= 1; |
| 53 | if *inflight == 0 { |
| 54 | self.condvar.notify_all(); |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | /// Returns a guard that decrements the in-flight count when dropped, so |
| 59 | /// the count stays correct even if the runnable being executed panics. |
| 60 | fn decrement_on_drop(&self) -> impl Drop + '_ { |
| 61 | gpui_util::defer(|| self.decrement()) |
| 62 | } |
| 63 | |
| 64 | /// Notifies waiters while holding the in-flight lock. `run_until_idle` |
| 65 | /// re-checks its wake conditions under this lock before waiting, so the |
| 66 | /// notification can't slip between its check and its wait and be lost. |
| 67 | fn notify_under_lock(&self) { |
| 68 | let _inflight = self.inflight.lock(); |
| 69 | self.condvar.notify_all(); |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | struct TimerQueue { |
| 74 | state: Mutex<TimerQueueState>, |
| 75 | condvar: Condvar, |
| 76 | } |
| 77 | |
| 78 | struct TimerQueueState { |
| 79 | heap: BinaryHeap<TimerEntry>, |
| 80 | next_seq: u64, |
| 81 | } |
| 82 | |
| 83 | struct TimerEntry { |
| 84 | due: Instant, |
| 85 | seq: u64, |
| 86 | runnable: RunnableVariant, |
| 87 | } |
| 88 | |
| 89 | impl PartialEq for TimerEntry { |
| 90 | fn eq(&self, other: &Self) -> bool { |
| 91 | self.due == other.due && self.seq == other.seq |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | impl Eq for TimerEntry {} |
| 96 | |
| 97 | impl PartialOrd for TimerEntry { |
| 98 | fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { |
| 99 | Some(self.cmp(other)) |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | impl Ord for TimerEntry { |
| 104 | fn cmp(&self, other: &Self) -> std::cmp::Ordering { |
| 105 | // Reversed so that the entry with the earliest due time (breaking ties |
| 106 | // by insertion order) is at the top of the max-heap. |
| 107 | other |
| 108 | .due |
| 109 | .cmp(&self.due) |
| 110 | .then_with(|| other.seq.cmp(&self.seq)) |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | impl Default for ThreadedDispatcher { |
| 115 | fn default() -> Self { |
| 116 | Self::new() |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | impl ThreadedDispatcher { |
| 121 | /// Creates a dispatcher whose main thread is the calling thread. |
| 122 | /// |
| 123 | /// Worker and timer threads live for the lifetime of the process; the |
| 124 | /// dispatcher is expected to be created once and reused. |
| 125 | pub fn new() -> Self { |
| 126 | let (background_sender, background_receiver) = PriorityQueueReceiver::new(); |
| 127 | let (main_sender, main_receiver) = PriorityQueueReceiver::new(); |
| 128 | let idle = Arc::new(IdleTracker::default()); |
| 129 | |
| 130 | let thread_count = |
| 131 | thread::available_parallelism().map_or(MIN_THREADS, |i| i.get().max(MIN_THREADS)); |
| 132 | for i in 0..thread_count { |
| 133 | let mut receiver: PriorityQueueReceiver<RunnableVariant> = background_receiver.clone(); |
| 134 | let idle = idle.clone(); |
| 135 | thread::Builder::new() |
| 136 | .name(format!("ThreadedDispatcherWorker-{i}")) |
| 137 | .spawn(move || { |
| 138 | while let Ok(runnable) = receiver.pop() { |
| 139 | let _decrement = idle.decrement_on_drop(); |
| 140 | let location = runnable.metadata().location; |
| 141 | let spawned = runnable.metadata().spawned; |
| 142 | profiler::update_running_task(spawned, location); |
| 143 | runnable.run(); |
| 144 | profiler::save_task_timing(); |
| 145 | } |
| 146 | }) |
| 147 | .expect("failed to spawn threaded dispatcher worker"); |
| 148 | } |
| 149 | drop(background_receiver); |
| 150 | |
| 151 | let timers = Arc::new(TimerQueue { |
| 152 | state: Mutex::new(TimerQueueState { |
| 153 | heap: BinaryHeap::new(), |
| 154 | next_seq: 0, |
| 155 | }), |
| 156 | condvar: Condvar::new(), |
| 157 | }); |
| 158 | { |
| 159 | let timers = timers.clone(); |
| 160 | let idle = idle.clone(); |
| 161 | thread::Builder::new() |
| 162 | .name("ThreadedDispatcherTimer".to_owned()) |
| 163 | .spawn(move || { |
| 164 | let mut state = timers.state.lock(); |
| 165 | loop { |
| 166 | let Some(entry) = state.heap.peek() else { |
| 167 | timers.condvar.wait(&mut state); |
| 168 | continue; |
| 169 | }; |
| 170 | let due = entry.due; |
| 171 | if due > Instant::now() { |
| 172 | timers.condvar.wait_until(&mut state, due); |
| 173 | continue; |
| 174 | } |
| 175 | let Some(entry) = state.heap.pop() else { |
| 176 | continue; |
| 177 | }; |
| 178 | // Count the firing timer as in-flight before releasing |
| 179 | // the lock so it can spawn follow-up work that |
| 180 | // `run_until_idle` will wait for. Lock order is always |
| 181 | // timer state, then in-flight count; `run_until_idle` |
| 182 | // never takes them in the opposite order. |
| 183 | idle.increment(); |
| 184 | drop(state); |
| 185 | |
| 186 | { |
| 187 | let _decrement = idle.decrement_on_drop(); |
| 188 | let location = entry.runnable.metadata().location; |
| 189 | let spawned = entry.runnable.metadata().spawned; |
| 190 | profiler::update_running_task(spawned, location); |
| 191 | entry.runnable.run(); |
| 192 | profiler::save_task_timing(); |
| 193 | } |
| 194 | |
| 195 | state = timers.state.lock(); |
| 196 | } |
| 197 | }) |
| 198 | .expect("failed to spawn threaded dispatcher timer"); |
| 199 | } |
| 200 | |
| 201 | Self { |
| 202 | background_sender, |
| 203 | main_sender, |
| 204 | main_receiver: Mutex::new(main_receiver), |
| 205 | timers, |
| 206 | idle, |
| 207 | main_thread_id: thread::current().id(), |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | /// Runs queued main thread tasks and waits until no background or timer |
| 212 | /// work is queued, running, or already due. |
| 213 | /// |
| 214 | /// Timers that haven't reached their due time yet are *not* waited for: |
| 215 | /// the dispatcher runs in real time and cannot skip ahead like the |
| 216 | /// `TestDispatcher`'s virtual clock, so waiting on a future timer would |
| 217 | /// block for its full real duration. Tasks sleeping on such timers are |
| 218 | /// considered idle. Must be called on the thread that created this |
| 219 | /// dispatcher. |
| 220 | pub fn run_until_idle(&self) { |
| 221 | self.run_until_idle_with(|| self.drain_main_queue()); |
| 222 | } |
| 223 | |
| 224 | pub(crate) fn run_until_idle_with(&self, mut run_turn: impl FnMut() -> bool) { |
| 225 | assert!( |
| 226 | self.is_main_thread(), |
| 227 | "run_until_idle must be called on the threaded dispatcher's main thread" |
| 228 | ); |
| 229 | loop { |
| 230 | if run_turn() { |
| 231 | continue; |
| 232 | } |
| 233 | |
| 234 | // Checked before taking the in-flight lock; the timer thread |
| 235 | // locks them in the opposite order, so nesting would deadlock. |
| 236 | if self.has_due_timer() { |
| 237 | // Poll briefly: a firing timer leaves the heap just before it |
| 238 | // registers as in-flight. |
| 239 | let mut inflight = self.idle.inflight.lock(); |
| 240 | self.idle |
| 241 | .condvar |
| 242 | .wait_for(&mut inflight, Duration::from_millis(1)); |
| 243 | continue; |
| 244 | } |
| 245 | |
| 246 | let mut inflight = self.idle.inflight.lock(); |
| 247 | // Re-checked under the lock that `dispatch_on_main_thread` |
| 248 | // notifies under, so the notification can't be lost. |
| 249 | if self.main_queue_has_work() { |
| 250 | continue; |
| 251 | } |
| 252 | if *inflight == 0 { |
| 253 | // Main-thread sends happen before in-flight decrements, and |
| 254 | // decrements happen under this lock, so the check above |
| 255 | // observed all completed work. |
| 256 | return; |
| 257 | } |
| 258 | // Woken when main-thread work arrives or the in-flight count |
| 259 | // reaches zero; both notify under this lock. |
| 260 | self.idle.condvar.wait(&mut inflight); |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | /// Drives main-thread work until `ready` returns a value. |
| 265 | /// |
| 266 | /// Unlike [`Self::run_until_idle`], this waits across temporary quiescence. |
| 267 | /// This is required when completion can arrive from an external worker that |
| 268 | /// is not represented in the dispatcher's in-flight count. |
| 269 | /// |
| 270 | /// Readiness is checked before every main-thread runnable, so this returns |
| 271 | /// as soon as `ready` observes completion rather than after the queue |
| 272 | /// drains — deferred work that re-queues itself (idle sweeps, pollers) |
| 273 | /// must not extend a benchmark's measured interval past the completion it |
| 274 | /// awaits. |
| 275 | #[cfg(test)] |
| 276 | pub(crate) fn run_until<R>(&self, ready: impl FnMut() -> Option<R>) -> R { |
| 277 | self.run_until_with_frames(ready, || false) |
| 278 | } |
| 279 | |
| 280 | /// Runs at most one queued main-thread task, returning whether one ran. |
| 281 | /// |
| 282 | /// Stepping tasks individually lets callers check completion between polls |
| 283 | /// even when work continually re-queues itself. |
| 284 | fn run_one_main_task(&self) -> bool { |
| 285 | assert!( |
| 286 | self.is_main_thread(), |
| 287 | "main tasks must run on the main thread" |
| 288 | ); |
| 289 | let runnable = self.main_receiver.lock().try_pop(); |
| 290 | match runnable { |
| 291 | Ok(Some(runnable)) => { |
| 292 | let location = runnable.metadata().location; |
| 293 | let spawned = runnable.metadata().spawned; |
| 294 | profiler::update_running_task(spawned, location); |
| 295 | runnable.run(); |
| 296 | profiler::save_task_timing(); |
| 297 | true |
| 298 | } |
| 299 | Ok(None) | Err(_) => false, |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | /// Runs up to the initial queue length of main-thread tasks. |
| 304 | /// |
| 305 | /// Returns whether any ran. This snapshots the count, not task identities: |
| 306 | /// newly dispatched higher-priority tasks can overtake the original tasks. |
| 307 | pub fn run_ready_main_tasks(&self) -> bool { |
| 308 | self.run_ready_main_tasks_with(|| true, || {}) |
| 309 | } |
| 310 | |
| 311 | /// Runs a count-bounded ready turn, checking `should_continue` before every poll. |
| 312 | /// Calls `after_poll` after each runnable returns, outside the queue lock. |
| 313 | pub(crate) fn run_ready_main_tasks_with( |
| 314 | &self, |
| 315 | mut should_continue: impl FnMut() -> bool, |
| 316 | mut after_poll: impl FnMut(), |
| 317 | ) -> bool { |
| 318 | assert!( |
| 319 | self.is_main_thread(), |
| 320 | "run_ready_main_tasks must be called on the threaded dispatcher's main thread" |
| 321 | ); |
| 322 | let pending = self.main_receiver.lock().len(); |
| 323 | let mut ran_any = false; |
| 324 | for _ in 0..pending { |
| 325 | if !should_continue() || !self.run_one_main_task() { |
| 326 | break; |
| 327 | } |
| 328 | ran_any = true; |
| 329 | after_poll(); |
| 330 | } |
| 331 | ran_any |
| 332 | } |
| 333 | |
| 334 | #[cfg(any(test, feature = "bench-support"))] |
| 335 | pub(crate) fn run_until_with_frames<R>( |
| 336 | &self, |
| 337 | mut ready: impl FnMut() -> Option<R>, |
| 338 | mut dispatch_frames: impl FnMut() -> bool, |
| 339 | ) -> R { |
| 340 | assert!( |
| 341 | self.is_main_thread(), |
| 342 | "main tasks must run on the main thread" |
| 343 | ); |
| 344 | loop { |
| 345 | if let Some(result) = ready() { |
| 346 | return result; |
| 347 | } |
| 348 | let ran_task = self.run_one_main_task(); |
| 349 | // A completion poll must not pull an unrelated animation frame |
| 350 | // into the measured operation. |
| 351 | if let Some(result) = ready() { |
| 352 | return result; |
| 353 | } |
| 354 | let dispatched_frames = dispatch_frames(); |
| 355 | if ran_task || dispatched_frames { |
| 356 | continue; |
| 357 | } |
| 358 | |
| 359 | let mut inflight = self.idle.inflight.lock(); |
| 360 | if self.main_queue_has_work() { |
| 361 | continue; |
| 362 | } |
| 363 | self.idle.condvar.wait(&mut inflight); |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | /// Cancels all pending timers so timers armed by one workload can't fire |
| 368 | /// during a later workload sharing this process-lifetime dispatcher. |
| 369 | /// |
| 370 | /// Dropping a timer runnable drops its completion sender, waking the task |
| 371 | /// awaiting the timer. Call [`Self::run_until_idle`] after this method to |
| 372 | /// drain any work that cancellation unblocks. |
| 373 | pub fn cancel_pending_timers(&self) -> usize { |
| 374 | let timers = { |
| 375 | let mut state = self.timers.state.lock(); |
| 376 | let timers: Vec<_> = state.heap.drain().collect(); |
| 377 | self.timers.condvar.notify_all(); |
| 378 | timers |
| 379 | }; |
| 380 | let canceled = timers.len(); |
| 381 | drop(timers); |
| 382 | canceled |
| 383 | } |
| 384 | |
| 385 | /// Describes the dispatcher's idle-tracking state, for diagnosing |
| 386 | /// workloads that fail to reach quiescence. |
| 387 | pub fn debug_state(&self) -> String { |
| 388 | let inflight = *self.idle.inflight.lock(); |
| 389 | let timers = self.timers.state.lock().heap.len(); |
| 390 | let main_queue_has_work = self.main_queue_has_work(); |
| 391 | format!( |
| 392 | "ThreadedDispatcher {{ inflight: {inflight}, pending_timers: {timers}, \ |
| 393 | main_queue_has_work: {main_queue_has_work} }}" |
| 394 | ) |
| 395 | } |
| 396 | |
| 397 | /// Whether no main-thread work is queued, no background or timer |
| 398 | /// runnables are queued or running, and no armed timer is due. Timers |
| 399 | /// that aren't due yet are ignored, as in [`Self::run_until_idle`]. |
| 400 | #[cfg(any(test, feature = "bench-support"))] |
| 401 | pub(crate) fn is_idle(&self) -> bool { |
| 402 | !self.main_queue_has_work() && !self.has_due_timer() && *self.idle.inflight.lock() == 0 |
| 403 | } |
| 404 | |
| 405 | fn has_due_timer(&self) -> bool { |
| 406 | let state = self.timers.state.lock(); |
| 407 | state |
| 408 | .heap |
| 409 | .peek() |
| 410 | .is_some_and(|entry| entry.due <= Instant::now()) |
| 411 | } |
| 412 | |
| 413 | fn main_queue_has_work(&self) -> bool { |
| 414 | !self.main_receiver.lock().is_empty() |
| 415 | } |
| 416 | |
| 417 | fn drain_main_queue(&self) -> bool { |
| 418 | let mut ran_any = false; |
| 419 | loop { |
| 420 | // Lock only around the pop so runnables can re-entrantly dispatch |
| 421 | // more main-thread work through the sender while they run. |
| 422 | let runnable = self.main_receiver.lock().try_pop(); |
| 423 | match runnable { |
| 424 | Ok(Some(runnable)) => { |
| 425 | let location = runnable.metadata().location; |
| 426 | let spawned = runnable.metadata().spawned; |
| 427 | profiler::update_running_task(spawned, location); |
| 428 | runnable.run(); |
| 429 | profiler::save_task_timing(); |
| 430 | ran_any = true; |
| 431 | } |
| 432 | Ok(None) | Err(_) => return ran_any, |
| 433 | } |
| 434 | } |
| 435 | } |
| 436 | } |
| 437 | |
| 438 | impl PlatformDispatcher for ThreadedDispatcher { |
| 439 | fn is_main_thread(&self) -> bool { |
| 440 | thread::current().id() == self.main_thread_id |
| 441 | } |
| 442 | |
| 443 | fn dispatch(&self, runnable: RunnableVariant, priority: Priority) { |
| 444 | self.idle.increment(); |
| 445 | self.background_sender |
| 446 | .send(priority, runnable) |
| 447 | .unwrap_or_else(|_| panic!("threaded dispatcher workers are no longer running")); |
| 448 | } |
| 449 | |
| 450 | fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority) { |
| 451 | if let Err(error) = self.main_sender.send(priority, runnable) { |
| 452 | // The main receiver lives as long as this dispatcher, so a failed |
| 453 | // send means we're mid-teardown. The runnable may wrap a !Send |
| 454 | // future, so forget it rather than dropping it on this thread |
| 455 | // (mirrors LinuxDispatcher). |
| 456 | std::mem::forget(error); |
| 457 | return; |
| 458 | } |
| 459 | // Wake `run_until_idle` if it's waiting for main-thread work. |
| 460 | self.idle.notify_under_lock(); |
| 461 | } |
| 462 | |
| 463 | fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant) { |
| 464 | let mut state = self.timers.state.lock(); |
| 465 | let seq = state.next_seq; |
| 466 | state.next_seq += 1; |
| 467 | state.heap.push(TimerEntry { |
| 468 | due: Instant::now() + duration, |
| 469 | seq, |
| 470 | runnable, |
| 471 | }); |
| 472 | self.timers.condvar.notify_one(); |
| 473 | } |
| 474 | |
| 475 | fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>) { |
| 476 | // This dispatcher does not need realtime scheduling priority; a plain |
| 477 | // thread keeps it portable. |
| 478 | thread::Builder::new() |
| 479 | .name("ThreadedDispatcherRealtime".to_owned()) |
| 480 | .spawn(f) |
| 481 | .expect("failed to spawn threaded dispatcher realtime thread"); |
| 482 | } |
| 483 | |
| 484 | fn as_threaded(&self) -> Option<&ThreadedDispatcher> { |
| 485 | Some(self) |
| 486 | } |
| 487 | } |
| 488 | |
| 489 | #[cfg(test)] |
| 490 | mod tests { |
| 491 | use std::future::Future; |
| 492 | use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; |
| 493 | |
| 494 | use super::*; |
| 495 | use crate::{BackgroundExecutor, ForegroundExecutor}; |
| 496 | |
| 497 | #[test] |
| 498 | fn is_idle_tracks_queued_work_but_ignores_undue_timers() { |
| 499 | let dispatcher = Arc::new(ThreadedDispatcher::new()); |
| 500 | let foreground = ForegroundExecutor::new(dispatcher.clone()); |
| 501 | assert!(dispatcher.is_idle()); |
| 502 | |
| 503 | foreground.spawn(async {}).detach(); |
| 504 | assert!(!dispatcher.is_idle()); |
| 505 | dispatcher.run_until_idle(); |
| 506 | assert!(dispatcher.is_idle()); |
| 507 | |
| 508 | let background = BackgroundExecutor::new(dispatcher.clone()); |
| 509 | let timer = background.timer(Duration::from_secs(60)); |
| 510 | // The timer future's initial poll runs on a worker thread; wait for |
| 511 | // it so only the armed, not-yet-due timer remains. |
| 512 | dispatcher.run_until_idle(); |
| 513 | assert!( |
| 514 | dispatcher.is_idle(), |
| 515 | "a timer that is not due yet should not count as pending work" |
| 516 | ); |
| 517 | drop(timer); |
| 518 | dispatcher.cancel_pending_timers(); |
| 519 | dispatcher.run_until_idle(); |
| 520 | assert!(dispatcher.is_idle()); |
| 521 | } |
| 522 | |
| 523 | #[test] |
| 524 | fn run_ready_main_tasks_does_not_wait_for_background_handoffs() { |
| 525 | let dispatcher = Arc::new(ThreadedDispatcher::new()); |
| 526 | let background = BackgroundExecutor::new(dispatcher.clone()); |
| 527 | let foreground = ForegroundExecutor::new(dispatcher.clone()); |
| 528 | |
| 529 | let (sender, receiver) = futures::channel::oneshot::channel(); |
| 530 | background |
| 531 | .spawn(async move { |
| 532 | thread::sleep(Duration::from_millis(10)); |
| 533 | sender.send(()).ok(); |
| 534 | }) |
| 535 | .detach(); |
| 536 | |
| 537 | let completed = Arc::new(AtomicBool::new(false)); |
| 538 | foreground |
| 539 | .spawn({ |
| 540 | let completed = completed.clone(); |
| 541 | async move { |
| 542 | receiver.await.ok(); |
| 543 | completed.store(true, Ordering::SeqCst); |
| 544 | } |
| 545 | }) |
| 546 | .detach(); |
| 547 | |
| 548 | assert!(dispatcher.run_ready_main_tasks()); |
| 549 | assert!(!completed.load(Ordering::SeqCst)); |
| 550 | |
| 551 | dispatcher.run_until_idle(); |
| 552 | assert!(completed.load(Ordering::SeqCst)); |
| 553 | } |
| 554 | |
| 555 | #[test] |
| 556 | fn run_until_idle_completes_background_to_main_handoffs() { |
| 557 | let dispatcher = Arc::new(ThreadedDispatcher::new()); |
| 558 | let background = BackgroundExecutor::new(dispatcher.clone()); |
| 559 | let foreground = ForegroundExecutor::new(dispatcher.clone()); |
| 560 | |
| 561 | let (sender, receiver) = futures::channel::oneshot::channel(); |
| 562 | background |
| 563 | .spawn(async move { |
| 564 | thread::sleep(Duration::from_millis(10)); |
| 565 | sender.send(()).ok(); |
| 566 | }) |
| 567 | .detach(); |
| 568 | |
| 569 | let completed = Arc::new(AtomicBool::new(false)); |
| 570 | foreground |
| 571 | .spawn({ |
| 572 | let completed = completed.clone(); |
| 573 | async move { |
| 574 | receiver.await.ok(); |
| 575 | completed.store(true, Ordering::SeqCst); |
| 576 | } |
| 577 | }) |
| 578 | .detach(); |
| 579 | |
| 580 | dispatcher.run_until_idle(); |
| 581 | assert!(completed.load(Ordering::SeqCst)); |
| 582 | } |
| 583 | |
| 584 | #[test] |
| 585 | fn run_until_waits_for_untracked_external_wakes() { |
| 586 | let dispatcher = Arc::new(ThreadedDispatcher::new()); |
| 587 | let foreground = ForegroundExecutor::new(dispatcher.clone()); |
| 588 | let (sender, receiver) = futures::channel::oneshot::channel(); |
| 589 | let sender_thread = thread::spawn(move || { |
| 590 | thread::sleep(Duration::from_millis(10)); |
| 591 | sender |
| 592 | .send(()) |
| 593 | .expect("foreground receiver should remain alive"); |
| 594 | }); |
| 595 | |
| 596 | let completed = Arc::new(AtomicBool::new(false)); |
| 597 | foreground |
| 598 | .spawn({ |
| 599 | let completed = completed.clone(); |
| 600 | async move { |
| 601 | receiver |
| 602 | .await |
| 603 | .expect("external sender should deliver its wake"); |
| 604 | completed.store(true, Ordering::SeqCst); |
| 605 | } |
| 606 | }) |
| 607 | .detach(); |
| 608 | |
| 609 | dispatcher.run_until(|| completed.load(Ordering::SeqCst).then_some(())); |
| 610 | sender_thread.join().expect("sender thread should finish"); |
| 611 | assert!(completed.load(Ordering::SeqCst)); |
| 612 | } |
| 613 | |
| 614 | #[test] |
| 615 | fn run_until_returns_at_readiness_despite_requeuing_main_work() { |
| 616 | const REQUEUE_LIMIT: usize = 10_000; |
| 617 | |
| 618 | let dispatcher = Arc::new(ThreadedDispatcher::new()); |
| 619 | let foreground = ForegroundExecutor::new(dispatcher.clone()); |
| 620 | |
| 621 | // Mirrors main-thread work that yields and immediately re-queues |
| 622 | // itself (e.g. an idle-time sweep): the main queue never drains until |
| 623 | // such work finishes every iteration, so readiness must be observed |
| 624 | // between runnables rather than only at quiescence. |
| 625 | let iterations = Arc::new(AtomicUsize::new(0)); |
| 626 | foreground |
| 627 | .spawn({ |
| 628 | let iterations = iterations.clone(); |
| 629 | async move { |
| 630 | for _ in 0..REQUEUE_LIMIT { |
| 631 | iterations.fetch_add(1, Ordering::SeqCst); |
| 632 | yield_once().await; |
| 633 | } |
| 634 | } |
| 635 | }) |
| 636 | .detach(); |
| 637 | |
| 638 | let completed = Arc::new(AtomicBool::new(false)); |
| 639 | foreground |
| 640 | .spawn({ |
| 641 | let completed = completed.clone(); |
| 642 | async move { |
| 643 | completed.store(true, Ordering::SeqCst); |
| 644 | } |
| 645 | }) |
| 646 | .detach(); |
| 647 | |
| 648 | dispatcher.run_until(|| completed.load(Ordering::SeqCst).then_some(())); |
| 649 | assert!( |
| 650 | iterations.load(Ordering::SeqCst) < REQUEUE_LIMIT, |
| 651 | "run_until should return at readiness instead of draining re-queued main work" |
| 652 | ); |
| 653 | } |
| 654 | |
| 655 | /// Completes after one re-schedule: the poll returns `Pending` and wakes |
| 656 | /// immediately, so the runnable re-enters the main queue. |
| 657 | fn yield_once() -> impl Future<Output = ()> { |
| 658 | let mut yielded = false; |
| 659 | std::future::poll_fn(move |poll_context| { |
| 660 | if yielded { |
| 661 | std::task::Poll::Ready(()) |
| 662 | } else { |
| 663 | yielded = true; |
| 664 | poll_context.waker().wake_by_ref(); |
| 665 | std::task::Poll::Pending |
| 666 | } |
| 667 | }) |
| 668 | } |
| 669 | |
| 670 | #[test] |
| 671 | fn run_ready_main_tasks_advances_requeuing_work_one_batch_per_call() { |
| 672 | const REQUEUE_LIMIT: usize = 10_000; |
| 673 | |
| 674 | let dispatcher = Arc::new(ThreadedDispatcher::new()); |
| 675 | let foreground = ForegroundExecutor::new(dispatcher.clone()); |
| 676 | |
| 677 | let iterations = Arc::new(AtomicUsize::new(0)); |
| 678 | foreground |
| 679 | .spawn({ |
| 680 | let iterations = iterations.clone(); |
| 681 | async move { |
| 682 | for _ in 0..REQUEUE_LIMIT { |
| 683 | iterations.fetch_add(1, Ordering::SeqCst); |
| 684 | yield_once().await; |
| 685 | } |
| 686 | } |
| 687 | }) |
| 688 | .detach(); |
| 689 | |
| 690 | assert!(dispatcher.run_ready_main_tasks()); |
| 691 | assert_eq!(iterations.load(Ordering::SeqCst), 1); |
| 692 | assert!(dispatcher.run_ready_main_tasks()); |
| 693 | assert_eq!(iterations.load(Ordering::SeqCst), 2); |
| 694 | } |
| 695 | |
| 696 | #[test] |
| 697 | fn timers_fire_in_real_time() { |
| 698 | let dispatcher = Arc::new(ThreadedDispatcher::new()); |
| 699 | let background = BackgroundExecutor::new(dispatcher); |
| 700 | |
| 701 | let fired = Arc::new(AtomicBool::new(false)); |
| 702 | let timer = background.timer(Duration::from_millis(10)); |
| 703 | background |
| 704 | .spawn({ |
| 705 | let fired = fired.clone(); |
| 706 | async move { |
| 707 | timer.await; |
| 708 | fired.store(true, Ordering::SeqCst); |
| 709 | } |
| 710 | }) |
| 711 | .detach(); |
| 712 | |
| 713 | let deadline = Instant::now() + Duration::from_secs(10); |
| 714 | while !fired.load(Ordering::SeqCst) && Instant::now() < deadline { |
| 715 | thread::sleep(Duration::from_millis(1)); |
| 716 | } |
| 717 | assert!(fired.load(Ordering::SeqCst)); |
| 718 | } |
| 719 | |
| 720 | #[test] |
| 721 | fn cancel_pending_timers_wakes_waiters_without_waiting_for_deadline() { |
| 722 | let dispatcher = Arc::new(ThreadedDispatcher::new()); |
| 723 | let background = BackgroundExecutor::new(dispatcher.clone()); |
| 724 | |
| 725 | let fired = Arc::new(AtomicBool::new(false)); |
| 726 | let timer = background.timer(Duration::from_secs(10)); |
| 727 | background |
| 728 | .spawn({ |
| 729 | let fired = fired.clone(); |
| 730 | async move { |
| 731 | timer.await; |
| 732 | fired.store(true, Ordering::SeqCst); |
| 733 | } |
| 734 | }) |
| 735 | .detach(); |
| 736 | |
| 737 | dispatcher.run_until_idle(); |
| 738 | assert_eq!(dispatcher.cancel_pending_timers(), 1); |
| 739 | dispatcher.run_until_idle(); |
| 740 | |
| 741 | assert!(fired.load(Ordering::SeqCst)); |
| 742 | assert_eq!(dispatcher.cancel_pending_timers(), 0); |
| 743 | } |
| 744 | } |