Debian Codegraph @

third_party/rust/tokio/src/runtime/scheduler/multi_thread_alt/worker.rs

raw
1 //! A scheduler is initialized with a fixed number of workers. Each worker is
2 //! driven by a thread. Each worker has a "core" which contains data such as the
3 //! run queue and other state. When `block_in_place` is called, the worker's
4 //! "core" is handed off to a new thread allowing the scheduler to continue to
5 //! make progress while the originating thread blocks.
6 //!
7 //! # Shutdown
8 //!
9 //! Shutting down the runtime involves the following steps:
10 //!
11 //! 1. The Shared::close method is called. This closes the inject queue and
12 //! `OwnedTasks` instance and wakes up all worker threads.
13 //!
14 //! 2. Each worker thread observes the close signal next time it runs
15 //! Core::maintenance by checking whether the inject queue is closed.
16 //! The `Core::is_shutdown` flag is set to true.
17 //!
18 //! 3. The worker thread calls `pre_shutdown` in parallel. Here, the worker
19 //! will keep removing tasks from `OwnedTasks` until it is empty. No new
20 //! tasks can be pushed to the `OwnedTasks` during or after this step as it
21 //! was closed in step 1.
22 //!
23 //! 5. The workers call Shared::shutdown to enter the single-threaded phase of
24 //! shutdown. These calls will push their core to `Shared::shutdown_cores`,
25 //! and the last thread to push its core will finish the shutdown procedure.
26 //!
27 //! 6. The local run queue of each core is emptied, then the inject queue is
28 //! emptied.
29 //!
30 //! At this point, shutdown has completed. It is not possible for any of the
31 //! collections to contain any tasks at this point, as each collection was
32 //! closed first, then emptied afterwards.
33 //!
34 //! ## Spawns during shutdown
35 //!
36 //! When spawning tasks during shutdown, there are two cases:
37 //!
38 //! * The spawner observes the `OwnedTasks` being open, and the inject queue is
39 //! closed.
40 //! * The spawner observes the `OwnedTasks` being closed and doesn't check the
41 //! inject queue.
42 //!
43 //! The first case can only happen if the `OwnedTasks::bind` call happens before
44 //! or during step 1 of shutdown. In this case, the runtime will clean up the
45 //! task in step 3 of shutdown.
46 //!
47 //! In the latter case, the task was not spawned and the task is immediately
48 //! cancelled by the spawner.
49 //!
50 //! The correctness of shutdown requires both the inject queue and `OwnedTasks`
51 //! collection to have a closed bit. With a close bit on only the inject queue,
52 //! spawning could run in to a situation where a task is successfully bound long
53 //! after the runtime has shut down. With a close bit on only the `OwnedTasks`,
54 //! the first spawning situation could result in the notification being pushed
55 //! to the inject queue after step 6 of shutdown, which would leave a task in
56 //! the inject queue indefinitely. This would be a ref-count cycle and a memory
57 //! leak.
58
59 use crate::loom::sync::{Arc, Condvar, Mutex, MutexGuard};
60 use crate::runtime;
61 use crate::runtime::context;
62 use crate::runtime::driver::Driver;
63 use crate::runtime::scheduler::multi_thread_alt::{
64 idle, queue, stats, Counters, Handle, Idle, Overflow, Stats, TraceStatus,
65 };
66 use crate::runtime::scheduler::{self, inject, Lock};
67 use crate::runtime::task::OwnedTasks;
68 use crate::runtime::{blocking, coop, driver, task, Config, SchedulerMetrics, WorkerMetrics};
69 use crate::util::atomic_cell::AtomicCell;
70 use crate::util::rand::{FastRand, RngSeedGenerator};
71
72 use std::cell::{Cell, RefCell};
73 use std::task::Waker;
74 use std::time::Duration;
75 use std::{cmp, thread};
76
77 cfg_unstable_metrics! {
78 mod metrics;
79 }
80
81 mod taskdump_mock;
82
83 /// A scheduler worker
84 ///
85 /// Data is stack-allocated and never migrates threads
86 pub(super) struct Worker {
87 /// Used to schedule bookkeeping tasks every so often.
88 tick: u32,
89
90 /// True if the scheduler is being shutdown
91 pub(super) is_shutdown: bool,
92
93 /// True if the scheduler is being traced
94 is_traced: bool,
95
96 /// Counter used to track when to poll from the local queue vs. the
97 /// injection queue
98 num_seq_local_queue_polls: u32,
99
100 /// How often to check the global queue
101 global_queue_interval: u32,
102
103 /// Used to collect a list of workers to notify
104 workers_to_notify: Vec<usize>,
105
106 /// Snapshot of idle core list. This helps speedup stealing
107 idle_snapshot: idle::Snapshot,
108
109 stats: stats::Ephemeral,
110 }
111
112 /// Core data
113 ///
114 /// Data is heap-allocated and migrates threads.
115 #[repr(align(128))]
116 pub(super) struct Core {
117 /// Index holding this core's remote/shared state.
118 pub(super) index: usize,
119
120 lifo_slot: Option<Notified>,
121
122 /// The worker-local run queue.
123 run_queue: queue::Local<Arc<Handle>>,
124
125 /// True if the worker is currently searching for more work. Searching
126 /// involves attempting to steal from other workers.
127 pub(super) is_searching: bool,
128
129 /// Per-worker runtime stats
130 stats: Stats,
131
132 /// Fast random number generator.
133 rand: FastRand,
134 }
135
136 /// State shared across all workers
137 pub(crate) struct Shared {
138 /// Per-core remote state.
139 remotes: Box<[Remote]>,
140
141 /// Global task queue used for:
142 /// 1. Submit work to the scheduler while **not** currently on a worker thread.
143 /// 2. Submit work to the scheduler when a worker run queue is saturated
144 pub(super) inject: inject::Shared<Arc<Handle>>,
145
146 /// Coordinates idle workers
147 idle: Idle,
148
149 /// Collection of all active tasks spawned onto this executor.
150 pub(super) owned: OwnedTasks<Arc<Handle>>,
151
152 /// Data synchronized by the scheduler mutex
153 pub(super) synced: Mutex<Synced>,
154
155 /// Power's Tokio's I/O, timers, etc... the responsibility of polling the
156 /// driver is shared across workers.
157 driver: AtomicCell<Driver>,
158
159 /// Condition variables used to unblock worker threads. Each worker thread
160 /// has its own `condvar` it waits on.
161 pub(super) condvars: Vec<Condvar>,
162
163 /// The number of cores that have observed the trace signal.
164 pub(super) trace_status: TraceStatus,
165
166 /// Scheduler configuration options
167 config: Config,
168
169 /// Collects metrics from the runtime.
170 pub(super) scheduler_metrics: SchedulerMetrics,
171
172 pub(super) worker_metrics: Box<[WorkerMetrics]>,
173
174 /// Only held to trigger some code on drop. This is used to get internal
175 /// runtime metrics that can be useful when doing performance
176 /// investigations. This does nothing (empty struct, no drop impl) unless
177 /// the `tokio_internal_mt_counters` `cfg` flag is set.
178 _counters: Counters,
179 }
180
181 /// Data synchronized by the scheduler mutex
182 pub(crate) struct Synced {
183 /// When worker is notified, it is assigned a core. The core is placed here
184 /// until the worker wakes up to take it.
185 pub(super) assigned_cores: Vec<Option<Box<Core>>>,
186
187 /// Cores that have observed the shutdown signal
188 ///
189 /// The core is **not** placed back in the worker to avoid it from being
190 /// stolen by a thread that was spawned as part of `block_in_place`.
191 shutdown_cores: Vec<Box<Core>>,
192
193 /// The driver goes here when shutting down
194 shutdown_driver: Option<Box<Driver>>,
195
196 /// Synchronized state for `Idle`.
197 pub(super) idle: idle::Synced,
198
199 /// Synchronized state for `Inject`.
200 pub(crate) inject: inject::Synced,
201 }
202
203 /// Used to communicate with a worker from other threads.
204 struct Remote {
205 /// When a task is scheduled from a worker, it is stored in this slot. The
206 /// worker will check this slot for a task **before** checking the run
207 /// queue. This effectively results in the **last** scheduled task to be run
208 /// next (LIFO). This is an optimization for improving locality which
209 /// benefits message passing patterns and helps to reduce latency.
210 // lifo_slot: Lifo,
211
212 /// Steals tasks from this worker.
213 pub(super) steal: queue::Steal<Arc<Handle>>,
214 }
215
216 /// Thread-local context
217 pub(crate) struct Context {
218 // Current scheduler's handle
219 handle: Arc<Handle>,
220
221 /// Worker index
222 index: usize,
223
224 /// True when the LIFO slot is enabled
225 lifo_enabled: Cell<bool>,
226
227 /// Core data
228 core: RefCell<Option<Box<Core>>>,
229
230 /// Used to pass cores to other threads when `block_in_place` is called
231 handoff_core: Arc<AtomicCell<Core>>,
232
233 /// Tasks to wake after resource drivers are polled. This is mostly to
234 /// handle yielded tasks.
235 pub(crate) defer: RefCell<Vec<Notified>>,
236 }
237
238 /// Running a task may consume the core. If the core is still available when
239 /// running the task completes, it is returned. Otherwise, the worker will need
240 /// to stop processing.
241 type RunResult = Result<Box<Core>, ()>;
242 type NextTaskResult = Result<(Option<Notified>, Box<Core>), ()>;
243
244 /// A task handle
245 type Task = task::Task<Arc<Handle>>;
246
247 /// A notified task handle
248 type Notified = task::Notified<Arc<Handle>>;
249
250 /// Value picked out of thin-air. Running the LIFO slot a handful of times
251 /// seems sufficient to benefit from locality. More than 3 times probably is
252 /// overweighing. The value can be tuned in the future with data that shows
253 /// improvements.
254 const MAX_LIFO_POLLS_PER_TICK: usize = 3;
255
256 pub(super) fn create(
257 num_cores: usize,
258 driver: Driver,
259 driver_handle: driver::Handle,
260 blocking_spawner: blocking::Spawner,
261 seed_generator: RngSeedGenerator,
262 config: Config,
263 ) -> runtime::Handle {
264 let mut num_workers = num_cores;
265
266 // If the driver is enabled, we need an extra thread to handle polling the
267 // driver when all cores are busy.
268 if driver.is_enabled() {
269 num_workers += 1;
270 }
271
272 let mut cores = Vec::with_capacity(num_cores);
273 let mut remotes = Vec::with_capacity(num_cores);
274 // Worker metrics are actually core based
275 let mut worker_metrics = Vec::with_capacity(num_cores);
276
277 // Create the local queues
278 for i in 0..num_cores {
279 let (steal, run_queue) = queue::local(config.local_queue_capacity);
280
281 let metrics = WorkerMetrics::from_config(&config);
282 let stats = Stats::new(&metrics);
283
284 cores.push(Box::new(Core {
285 index: i,
286 lifo_slot: None,
287 run_queue,
288 is_searching: false,
289 stats,
290 rand: FastRand::from_seed(config.seed_generator.next_seed()),
291 }));
292
293 remotes.push(Remote {
294 steal,
295 // lifo_slot: Lifo::new(),
296 });
297 worker_metrics.push(metrics);
298 }
299
300 // Allocate num-cores + 1 workers, so one worker can handle the I/O driver,
301 // if needed.
302 let (idle, idle_synced) = Idle::new(cores, num_workers);
303 let (inject, inject_synced) = inject::Shared::new();
304
305 let handle = Arc::new(Handle {
306 shared: Shared {
307 remotes: remotes.into_boxed_slice(),
308 inject,
309 idle,
310 owned: OwnedTasks::new(num_cores),
311 synced: Mutex::new(Synced {
312 assigned_cores: (0..num_workers).map(|_| None).collect(),
313 shutdown_cores: Vec::with_capacity(num_cores),
314 shutdown_driver: None,
315 idle: idle_synced,
316 inject: inject_synced,
317 }),
318 driver: AtomicCell::new(Some(Box::new(driver))),
319 condvars: (0..num_workers).map(|_| Condvar::new()).collect(),
320 trace_status: TraceStatus::new(num_cores),
321 config,
322 scheduler_metrics: SchedulerMetrics::new(),
323 worker_metrics: worker_metrics.into_boxed_slice(),
324 _counters: Counters,
325 },
326 driver: driver_handle,
327 blocking_spawner,
328 seed_generator,
329 });
330
331 let rt_handle = runtime::Handle {
332 inner: scheduler::Handle::MultiThreadAlt(handle),
333 };
334
335 // Eagerly start worker threads
336 for index in 0..num_workers {
337 let handle = rt_handle.inner.expect_multi_thread_alt();
338 let h2 = handle.clone();
339 let handoff_core = Arc::new(AtomicCell::new(None));
340
341 handle
342 .blocking_spawner
343 .spawn_blocking(&rt_handle, move || run(index, h2, handoff_core, false));
344 }
345
346 rt_handle
347 }
348
349 #[track_caller]
350 pub(crate) fn block_in_place<F, R>(f: F) -> R
351 where
352 F: FnOnce() -> R,
353 {
354 // Try to steal the worker core back
355 struct Reset(coop::Budget);
356
357 impl Drop for Reset {
358 fn drop(&mut self) {
359 with_current(|maybe_cx| {
360 if let Some(cx) = maybe_cx {
361 let core = cx.handoff_core.take();
362 let mut cx_core = cx.core.borrow_mut();
363 assert!(cx_core.is_none());
364 *cx_core = core;
365
366 // Reset the task budget as we are re-entering the
367 // runtime.
368 coop::set(self.0);
369 }
370 });
371 }
372 }
373
374 let mut had_entered = false;
375
376 let setup_result = with_current(|maybe_cx| {
377 match (
378 crate::runtime::context::current_enter_context(),
379 maybe_cx.is_some(),
380 ) {
381 (context::EnterRuntime::Entered { .. }, true) => {
382 // We are on a thread pool runtime thread, so we just need to
383 // set up blocking.
384 had_entered = true;
385 }
386 (
387 context::EnterRuntime::Entered {
388 allow_block_in_place,
389 },
390 false,
391 ) => {
392 // We are on an executor, but _not_ on the thread pool. That is
393 // _only_ okay if we are in a thread pool runtime's block_on
394 // method:
395 if allow_block_in_place {
396 had_entered = true;
397 return Ok(());
398 } else {
399 // This probably means we are on the current_thread runtime or in a
400 // LocalSet, where it is _not_ okay to block.
401 return Err(
402 "can call blocking only when running on the multi-threaded runtime",
403 );
404 }
405 }
406 (context::EnterRuntime::NotEntered, true) => {
407 // This is a nested call to block_in_place (we already exited).
408 // All the necessary setup has already been done.
409 return Ok(());
410 }
411 (context::EnterRuntime::NotEntered, false) => {
412 // We are outside of the tokio runtime, so blocking is fine.
413 // We can also skip all of the thread pool blocking setup steps.
414 return Ok(());
415 }
416 }
417
418 let cx = maybe_cx.expect("no .is_some() == false cases above should lead here");
419
420 // Get the worker core. If none is set, then blocking is fine!
421 let core = match cx.core.borrow_mut().take() {
422 Some(core) => core,
423 None => return Ok(()),
424 };
425
426 // In order to block, the core must be sent to another thread for
427 // execution.
428 //
429 // First, move the core back into the worker's shared core slot.
430 cx.handoff_core.set(core);
431
432 // Next, clone the worker handle and send it to a new thread for
433 // processing.
434 //
435 // Once the blocking task is done executing, we will attempt to
436 // steal the core back.
437 let index = cx.index;
438 let handle = cx.handle.clone();
439 let handoff_core = cx.handoff_core.clone();
440 runtime::spawn_blocking(move || run(index, handle, handoff_core, true));
441 Ok(())
442 });
443
444 if let Err(panic_message) = setup_result {
445 panic!("{}", panic_message);
446 }
447
448 if had_entered {
449 // Unset the current task's budget. Blocking sections are not
450 // constrained by task budgets.
451 let _reset = Reset(coop::stop());
452
453 crate::runtime::context::exit_runtime(f)
454 } else {
455 f()
456 }
457 }
458
459 fn run(
460 index: usize,
461 handle: Arc<Handle>,
462 handoff_core: Arc<AtomicCell<Core>>,
463 blocking_in_place: bool,
464 ) {
465 struct AbortOnPanic;
466
467 impl Drop for AbortOnPanic {
468 fn drop(&mut self) {
469 if std::thread::panicking() {
470 eprintln!("worker thread panicking; aborting process");
471 std::process::abort();
472 }
473 }
474 }
475
476 // Catching panics on worker threads in tests is quite tricky. Instead, when
477 // debug assertions are enabled, we just abort the process.
478 #[cfg(debug_assertions)]
479 let _abort_on_panic = AbortOnPanic;
480
481 let num_workers = handle.shared.condvars.len();
482
483 let mut worker = Worker {
484 tick: 0,
485 num_seq_local_queue_polls: 0,
486 global_queue_interval: Stats::DEFAULT_GLOBAL_QUEUE_INTERVAL,
487 is_shutdown: false,
488 is_traced: false,
489 workers_to_notify: Vec::with_capacity(num_workers - 1),
490 idle_snapshot: idle::Snapshot::new(&handle.shared.idle),
491 stats: stats::Ephemeral::new(),
492 };
493
494 let sched_handle = scheduler::Handle::MultiThreadAlt(handle.clone());
495
496 crate::runtime::context::enter_runtime(&sched_handle, true, |_| {
497 // Set the worker context.
498 let cx = scheduler::Context::MultiThreadAlt(Context {
499 index,
500 lifo_enabled: Cell::new(!handle.shared.config.disable_lifo_slot),
501 handle,
502 core: RefCell::new(None),
503 handoff_core,
504 defer: RefCell::new(Vec::with_capacity(64)),
505 });
506
507 context::set_scheduler(&cx, || {
508 let cx = cx.expect_multi_thread_alt();
509
510 // Run the worker
511 let res = worker.run(&cx, blocking_in_place);
512 // `err` here signifies the core was lost, this is an expected end
513 // state for a worker.
514 debug_assert!(res.is_err());
515
516 // Check if there are any deferred tasks to notify. This can happen when
517 // the worker core is lost due to `block_in_place()` being called from
518 // within the task.
519 if !cx.defer.borrow().is_empty() {
520 worker.schedule_deferred_without_core(&cx, &mut cx.shared().synced.lock());
521 }
522 });
523 });
524 }
525
526 macro_rules! try_task {
527 ($e:expr) => {{
528 let (task, core) = $e?;
529 if task.is_some() {
530 return Ok((task, core));
531 }
532 core
533 }};
534 }
535
536 macro_rules! try_task_new_batch {
537 ($w:expr, $e:expr) => {{
538 let (task, mut core) = $e?;
539 if task.is_some() {
540 core.stats.start_processing_scheduled_tasks(&mut $w.stats);
541 return Ok((task, core));
542 }
543 core
544 }};
545 }
546
547 impl Worker {
548 fn run(&mut self, cx: &Context, blocking_in_place: bool) -> RunResult {
549 let (maybe_task, mut core) = {
550 if blocking_in_place {
551 if let Some(core) = cx.handoff_core.take() {
552 (None, core)
553 } else {
554 // Just shutdown
555 return Err(());
556 }
557 } else {
558 let mut synced = cx.shared().synced.lock();
559
560 // First try to acquire an available core
561 if let Some(core) = self.try_acquire_available_core(cx, &mut synced) {
562 // Try to poll a task from the global queue
563 let maybe_task = cx.shared().next_remote_task_synced(&mut synced);
564 (maybe_task, core)
565 } else {
566 // block the thread to wait for a core to be assigned to us
567 self.wait_for_core(cx, synced)?
568 }
569 }
570 };
571
572 cx.shared().worker_metrics[core.index].set_thread_id(thread::current().id());
573 core.stats.start_processing_scheduled_tasks(&mut self.stats);
574
575 if let Some(task) = maybe_task {
576 core = self.run_task(cx, core, task)?;
577 }
578
579 while !self.is_shutdown {
580 let (maybe_task, c) = self.next_task(cx, core)?;
581 core = c;
582
583 if let Some(task) = maybe_task {
584 core = self.run_task(cx, core, task)?;
585 } else {
586 // The only reason to get `None` from `next_task` is we have
587 // entered the shutdown phase.
588 assert!(self.is_shutdown);
589 break;
590 }
591 }
592
593 cx.shared().shutdown_core(&cx.handle, core);
594
595 // It is possible that tasks wake others during drop, so we need to
596 // clear the defer list.
597 self.shutdown_clear_defer(cx);
598
599 Err(())
600 }
601
602 // Try to acquire an available core, but do not block the thread
603 fn try_acquire_available_core(
604 &mut self,
605 cx: &Context,
606 synced: &mut Synced,
607 ) -> Option<Box<Core>> {
608 if let Some(mut core) = cx
609 .shared()
610 .idle
611 .try_acquire_available_core(&mut synced.idle)
612 {
613 self.reset_acquired_core(cx, synced, &mut core);
614 Some(core)
615 } else {
616 None
617 }
618 }
619
620 // Block the current thread, waiting for an available core
621 fn wait_for_core(
622 &mut self,
623 cx: &Context,
624 mut synced: MutexGuard<'_, Synced>,
625 ) -> NextTaskResult {
626 if cx.shared().idle.needs_searching() {
627 if let Some(mut core) = self.try_acquire_available_core(cx, &mut synced) {
628 cx.shared().idle.transition_worker_to_searching(&mut core);
629 return Ok((None, core));
630 }
631 }
632
633 cx.shared()
634 .idle
635 .transition_worker_to_parked(&mut synced, cx.index);
636
637 // Wait until a core is available, then exit the loop.
638 let mut core = loop {
639 if let Some(core) = synced.assigned_cores[cx.index].take() {
640 break core;
641 }
642
643 // If shutting down, abort
644 if cx.shared().inject.is_closed(&synced.inject) {
645 self.shutdown_clear_defer(cx);
646 return Err(());
647 }
648
649 synced = cx.shared().condvars[cx.index].wait(synced).unwrap();
650 };
651
652 self.reset_acquired_core(cx, &mut synced, &mut core);
653
654 if self.is_shutdown {
655 // Currently shutting down, don't do any more work
656 return Ok((None, core));
657 }
658
659 let n = cmp::max(core.run_queue.remaining_slots() / 2, 1);
660 let maybe_task = self.next_remote_task_batch_synced(cx, &mut synced, &mut core, n);
661
662 core.stats.unparked();
663 self.flush_metrics(cx, &mut core);
664
665 Ok((maybe_task, core))
666 }
667
668 /// Ensure core's state is set correctly for the worker to start using.
669 fn reset_acquired_core(&mut self, cx: &Context, synced: &mut Synced, core: &mut Core) {
670 self.global_queue_interval = core.stats.tuned_global_queue_interval(&cx.shared().config);
671
672 // Reset `lifo_enabled` here in case the core was previously stolen from
673 // a task that had the LIFO slot disabled.
674 self.reset_lifo_enabled(cx);
675
676 // At this point, the local queue should be empty
677 #[cfg(not(loom))]
678 debug_assert!(core.run_queue.is_empty());
679
680 // Update shutdown state while locked
681 self.update_global_flags(cx, synced);
682 }
683
684 /// Finds the next task to run, this could be from a queue or stealing. If
685 /// none are available, the thread sleeps and tries again.
686 fn next_task(&mut self, cx: &Context, mut core: Box<Core>) -> NextTaskResult {
687 self.assert_lifo_enabled_is_correct(cx);
688
689 if self.is_traced {
690 core = cx.handle.trace_core(core);
691 }
692
693 // Increment the tick
694 self.tick = self.tick.wrapping_add(1);
695
696 // Runs maintenance every so often. When maintenance is run, the
697 // driver is checked, which may result in a task being found.
698 core = try_task!(self.maybe_maintenance(&cx, core));
699
700 // Check the LIFO slot, local run queue, and the injection queue for
701 // a notified task.
702 core = try_task!(self.next_notified_task(cx, core));
703
704 // We consumed all work in the queues and will start searching for work.
705 core.stats.end_processing_scheduled_tasks(&mut self.stats);
706
707 super::counters::inc_num_no_local_work();
708
709 if !cx.defer.borrow().is_empty() {
710 // We are deferring tasks, so poll the resource driver and schedule
711 // the deferred tasks.
712 try_task_new_batch!(self, self.park_yield(cx, core));
713
714 panic!("what happened to the deferred tasks? 🤔");
715 }
716
717 while !self.is_shutdown {
718 // Search for more work, this involves trying to poll the resource
719 // driver, steal from other workers, and check the global queue
720 // again.
721 core = try_task_new_batch!(self, self.search_for_work(cx, core));
722
723 debug_assert!(cx.defer.borrow().is_empty());
724 core = try_task_new_batch!(self, self.park(cx, core));
725 }
726
727 // Shutting down, drop any deferred tasks
728 self.shutdown_clear_defer(cx);
729
730 Ok((None, core))
731 }
732
733 fn next_notified_task(&mut self, cx: &Context, mut core: Box<Core>) -> NextTaskResult {
734 self.num_seq_local_queue_polls += 1;
735
736 if self.num_seq_local_queue_polls % self.global_queue_interval == 0 {
737 super::counters::inc_global_queue_interval();
738
739 self.num_seq_local_queue_polls = 0;
740
741 // Update the global queue interval, if needed
742 self.tune_global_queue_interval(cx, &mut core);
743
744 if let Some(task) = self.next_remote_task(cx) {
745 return Ok((Some(task), core));
746 }
747 }
748
749 if let Some(task) = core.next_local_task() {
750 return Ok((Some(task), core));
751 }
752
753 self.next_remote_task_batch(cx, core)
754 }
755
756 fn next_remote_task(&self, cx: &Context) -> Option<Notified> {
757 if cx.shared().inject.is_empty() {
758 return None;
759 }
760
761 let mut synced = cx.shared().synced.lock();
762 cx.shared().next_remote_task_synced(&mut synced)
763 }
764
765 fn next_remote_task_batch(&self, cx: &Context, mut core: Box<Core>) -> NextTaskResult {
766 if cx.shared().inject.is_empty() {
767 return Ok((None, core));
768 }
769
770 // Other threads can only **remove** tasks from the current worker's
771 // `run_queue`. So, we can be confident that by the time we call
772 // `run_queue.push_back` below, there will be *at least* `cap`
773 // available slots in the queue.
774 let cap = usize::min(
775 core.run_queue.remaining_slots(),
776 usize::max(core.run_queue.max_capacity() / 2, 1),
777 );
778
779 let mut synced = cx.shared().synced.lock();
780 let maybe_task = self.next_remote_task_batch_synced(cx, &mut synced, &mut core, cap);
781 Ok((maybe_task, core))
782 }
783
784 fn next_remote_task_batch_synced(
785 &self,
786 cx: &Context,
787 synced: &mut Synced,
788 core: &mut Core,
789 max: usize,
790 ) -> Option<Notified> {
791 super::counters::inc_num_remote_batch();
792
793 // The worker is currently idle, pull a batch of work from the
794 // injection queue. We don't want to pull *all* the work so other
795 // workers can also get some.
796 let n = if core.is_searching {
797 cx.shared().inject.len() / cx.shared().idle.num_searching() + 1
798 } else {
799 cx.shared().inject.len() / cx.shared().remotes.len() + 1
800 };
801
802 let n = usize::min(n, max) + 1;
803
804 // safety: passing in the correct `inject::Synced`.
805 let mut tasks = unsafe { cx.shared().inject.pop_n(&mut synced.inject, n) };
806
807 // Pop the first task to return immediately
808 let ret = tasks.next();
809
810 // Push the rest of the on the run queue
811 core.run_queue.push_back(tasks);
812
813 ret
814 }
815
816 /// Function responsible for stealing tasks from another worker
817 ///
818 /// Note: Only if less than half the workers are searching for tasks to steal
819 /// a new worker will actually try to steal. The idea is to make sure not all
820 /// workers will be trying to steal at the same time.
821 fn search_for_work(&mut self, cx: &Context, mut core: Box<Core>) -> NextTaskResult {
822 #[cfg(not(loom))]
823 const ROUNDS: usize = 4;
824
825 #[cfg(loom)]
826 const ROUNDS: usize = 1;
827
828 debug_assert!(core.lifo_slot.is_none());
829 #[cfg(not(loom))]
830 debug_assert!(core.run_queue.is_empty());
831
832 if !core.run_queue.can_steal() {
833 return Ok((None, core));
834 }
835
836 if !self.transition_to_searching(cx, &mut core) {
837 return Ok((None, core));
838 }
839
840 // core = try_task!(self, self.poll_driver(cx, core));
841
842 // Get a snapshot of which workers are idle
843 cx.shared().idle.snapshot(&mut self.idle_snapshot);
844
845 let num = cx.shared().remotes.len();
846
847 for i in 0..ROUNDS {
848 // Start from a random worker
849 let start = core.rand.fastrand_n(num as u32) as usize;
850
851 if let Some(task) = self.steal_one_round(cx, &mut core, start) {
852 return Ok((Some(task), core));
853 }
854
855 core = try_task!(self.next_remote_task_batch(cx, core));
856
857 if i > 0 {
858 super::counters::inc_num_spin_stall();
859 std::thread::sleep(std::time::Duration::from_micros(i as u64));
860 }
861 }
862
863 Ok((None, core))
864 }
865
866 fn steal_one_round(&self, cx: &Context, core: &mut Core, start: usize) -> Option<Notified> {
867 let num = cx.shared().remotes.len();
868
869 for i in 0..num {
870 let i = (start + i) % num;
871
872 // Don't steal from ourself! We know we don't have work.
873 if i == core.index {
874 continue;
875 }
876
877 // If the core is currently idle, then there is nothing to steal.
878 if self.idle_snapshot.is_idle(i) {
879 continue;
880 }
881
882 let target = &cx.shared().remotes[i];
883
884 if let Some(task) = target
885 .steal
886 .steal_into(&mut core.run_queue, &mut core.stats)
887 {
888 return Some(task);
889 }
890 }
891
892 None
893 }
894
895 fn run_task(&mut self, cx: &Context, mut core: Box<Core>, task: Notified) -> RunResult {
896 let task = cx.shared().owned.assert_owner(task);
897
898 // Make sure the worker is not in the **searching** state. This enables
899 // another idle worker to try to steal work.
900 if self.transition_from_searching(cx, &mut core) {
901 super::counters::inc_num_relay_search();
902 cx.shared().notify_parked_local();
903 }
904
905 self.assert_lifo_enabled_is_correct(cx);
906
907 // Measure the poll start time. Note that we may end up polling other
908 // tasks under this measurement. In this case, the tasks came from the
909 // LIFO slot and are considered part of the current task for scheduling
910 // purposes. These tasks inherent the "parent"'s limits.
911 core.stats.start_poll(&mut self.stats);
912
913 // Make the core available to the runtime context
914 *cx.core.borrow_mut() = Some(core);
915
916 // Run the task
917 coop::budget(|| {
918 super::counters::inc_num_polls();
919 task.run();
920 let mut lifo_polls = 0;
921
922 // As long as there is budget remaining and a task exists in the
923 // `lifo_slot`, then keep running.
924 loop {
925 // Check if we still have the core. If not, the core was stolen
926 // by another worker.
927 let mut core = match cx.core.borrow_mut().take() {
928 Some(core) => core,
929 None => {
930 // In this case, we cannot call `reset_lifo_enabled()`
931 // because the core was stolen. The stealer will handle
932 // that at the top of `Context::run`
933 return Err(());
934 }
935 };
936
937 // Check for a task in the LIFO slot
938 let task = match core.next_lifo_task() {
939 Some(task) => task,
940 None => {
941 self.reset_lifo_enabled(cx);
942 core.stats.end_poll();
943 return Ok(core);
944 }
945 };
946
947 if !coop::has_budget_remaining() {
948 core.stats.end_poll();
949
950 // Not enough budget left to run the LIFO task, push it to
951 // the back of the queue and return.
952 core.run_queue
953 .push_back_or_overflow(task, cx.shared(), &mut core.stats);
954 // If we hit this point, the LIFO slot should be enabled.
955 // There is no need to reset it.
956 debug_assert!(cx.lifo_enabled.get());
957 return Ok(core);
958 }
959
960 // Track that we are about to run a task from the LIFO slot.
961 lifo_polls += 1;
962 super::counters::inc_lifo_schedules();
963
964 // Disable the LIFO slot if we reach our limit
965 //
966 // In ping-ping style workloads where task A notifies task B,
967 // which notifies task A again, continuously prioritizing the
968 // LIFO slot can cause starvation as these two tasks will
969 // repeatedly schedule the other. To mitigate this, we limit the
970 // number of times the LIFO slot is prioritized.
971 if lifo_polls >= MAX_LIFO_POLLS_PER_TICK {
972 cx.lifo_enabled.set(false);
973 super::counters::inc_lifo_capped();
974 }
975
976 // Run the LIFO task, then loop
977 *cx.core.borrow_mut() = Some(core);
978 let task = cx.shared().owned.assert_owner(task);
979 super::counters::inc_num_lifo_polls();
980 task.run();
981 }
982 })
983 }
984
985 fn schedule_deferred_with_core<'a>(
986 &mut self,
987 cx: &'a Context,
988 mut core: Box<Core>,
989 synced: impl FnOnce() -> MutexGuard<'a, Synced>,
990 ) -> NextTaskResult {
991 let mut defer = cx.defer.borrow_mut();
992
993 // Grab a task to run next
994 let task = defer.pop();
995
996 if task.is_none() {
997 return Ok((None, core));
998 }
999
1000 if !defer.is_empty() {
1001 let mut synced = synced();
1002
1003 // Number of tasks we want to try to spread across idle workers
1004 let num_fanout = cmp::min(defer.len(), cx.shared().idle.num_idle(&synced.idle));
1005
1006 // Cap the number of threads woken up at one time. This is to limit
1007 // the number of no-op wakes and reduce mutext contention.
1008 //
1009 // This number was picked after some basic benchmarks, but it can
1010 // probably be tuned using the mean poll time value (slower task
1011 // polls can leverage more woken workers).
1012 let num_fanout = cmp::min(2, num_fanout);
1013
1014 if num_fanout > 0 {
1015 cx.shared()
1016 .push_remote_task_batch_synced(&mut synced, defer.drain(..num_fanout));
1017
1018 cx.shared()
1019 .idle
1020 .notify_mult(&mut synced, &mut self.workers_to_notify, num_fanout);
1021 }
1022
1023 // Do not run the task while holding the lock...
1024 drop(synced);
1025 }
1026
1027 // Notify any workers
1028 for worker in self.workers_to_notify.drain(..) {
1029 cx.shared().condvars[worker].notify_one()
1030 }
1031
1032 if !defer.is_empty() {
1033 // Push the rest of the tasks on the local queue
1034 for task in defer.drain(..) {
1035 core.run_queue
1036 .push_back_or_overflow(task, cx.shared(), &mut core.stats);
1037 }
1038
1039 cx.shared().notify_parked_local();
1040 }
1041
1042 Ok((task, core))
1043 }
1044
1045 fn schedule_deferred_without_core<'a>(&mut self, cx: &Context, synced: &mut Synced) {
1046 let mut defer = cx.defer.borrow_mut();
1047 let num = defer.len();
1048
1049 if num > 0 {
1050 // Push all tasks to the injection queue
1051 cx.shared()
1052 .push_remote_task_batch_synced(synced, defer.drain(..));
1053
1054 debug_assert!(self.workers_to_notify.is_empty());
1055
1056 // Notify workers
1057 cx.shared()
1058 .idle
1059 .notify_mult(synced, &mut self.workers_to_notify, num);
1060
1061 // Notify any workers
1062 for worker in self.workers_to_notify.drain(..) {
1063 cx.shared().condvars[worker].notify_one()
1064 }
1065 }
1066 }
1067
1068 fn maybe_maintenance(&mut self, cx: &Context, mut core: Box<Core>) -> NextTaskResult {
1069 if self.tick % cx.shared().config.event_interval == 0 {
1070 super::counters::inc_num_maintenance();
1071
1072 core.stats.end_processing_scheduled_tasks(&mut self.stats);
1073
1074 // Run regularly scheduled maintenance
1075 core = try_task_new_batch!(self, self.park_yield(cx, core));
1076
1077 core.stats.start_processing_scheduled_tasks(&mut self.stats);
1078 }
1079
1080 Ok((None, core))
1081 }
1082
1083 fn flush_metrics(&self, cx: &Context, core: &mut Core) {
1084 core.stats.submit(&cx.shared().worker_metrics[core.index]);
1085 }
1086
1087 fn update_global_flags(&mut self, cx: &Context, synced: &mut Synced) {
1088 if !self.is_shutdown {
1089 self.is_shutdown = cx.shared().inject.is_closed(&synced.inject);
1090 }
1091
1092 if !self.is_traced {
1093 self.is_traced = cx.shared().trace_status.trace_requested();
1094 }
1095 }
1096
1097 fn park_yield(&mut self, cx: &Context, core: Box<Core>) -> NextTaskResult {
1098 // Call `park` with a 0 timeout. This enables the I/O driver, timer, ...
1099 // to run without actually putting the thread to sleep.
1100 if let Some(mut driver) = cx.shared().driver.take() {
1101 driver.park_timeout(&cx.handle.driver, Duration::from_millis(0));
1102
1103 cx.shared().driver.set(driver);
1104 }
1105
1106 // If there are more I/O events, schedule them.
1107 let (maybe_task, mut core) =
1108 self.schedule_deferred_with_core(cx, core, || cx.shared().synced.lock())?;
1109
1110 self.flush_metrics(cx, &mut core);
1111 self.update_global_flags(cx, &mut cx.shared().synced.lock());
1112
1113 Ok((maybe_task, core))
1114 }
1115
1116 /*
1117 fn poll_driver(&mut self, cx: &Context, core: Box<Core>) -> NextTaskResult {
1118 // Call `park` with a 0 timeout. This enables the I/O driver, timer, ...
1119 // to run without actually putting the thread to sleep.
1120 if let Some(mut driver) = cx.shared().driver.take() {
1121 driver.park_timeout(&cx.handle.driver, Duration::from_millis(0));
1122
1123 cx.shared().driver.set(driver);
1124
1125 // If there are more I/O events, schedule them.
1126 self.schedule_deferred_with_core(cx, core, || cx.shared().synced.lock())
1127 } else {
1128 Ok((None, core))
1129 }
1130 }
1131 */
1132
1133 fn park(&mut self, cx: &Context, mut core: Box<Core>) -> NextTaskResult {
1134 if let Some(f) = &cx.shared().config.before_park {
1135 f();
1136 }
1137
1138 if self.can_transition_to_parked(&mut core) {
1139 debug_assert!(!self.is_shutdown);
1140 debug_assert!(!self.is_traced);
1141
1142 core = try_task!(self.do_park(cx, core));
1143 }
1144
1145 if let Some(f) = &cx.shared().config.after_unpark {
1146 f();
1147 }
1148
1149 Ok((None, core))
1150 }
1151
1152 fn do_park(&mut self, cx: &Context, mut core: Box<Core>) -> NextTaskResult {
1153 let was_searching = core.is_searching;
1154
1155 // Acquire the lock
1156 let mut synced = cx.shared().synced.lock();
1157
1158 // The local queue should be empty at this point
1159 #[cfg(not(loom))]
1160 debug_assert!(core.run_queue.is_empty());
1161
1162 // Try one last time to get tasks
1163 let n = cmp::max(core.run_queue.remaining_slots() / 2, 1);
1164 if let Some(task) = self.next_remote_task_batch_synced(cx, &mut synced, &mut core, n) {
1165 return Ok((Some(task), core));
1166 }
1167
1168 if !was_searching {
1169 if cx
1170 .shared()
1171 .idle
1172 .transition_worker_to_searching_if_needed(&mut synced.idle, &mut core)
1173 {
1174 // Skip parking, go back to searching
1175 return Ok((None, core));
1176 }
1177 }
1178
1179 super::counters::inc_num_parks();
1180 core.stats.about_to_park();
1181 // Flush metrics to the runtime metrics aggregator
1182 self.flush_metrics(cx, &mut core);
1183
1184 // If the runtime is shutdown, skip parking
1185 self.update_global_flags(cx, &mut synced);
1186
1187 if self.is_shutdown {
1188 return Ok((None, core));
1189 }
1190
1191 // Release the core
1192 core.is_searching = false;
1193 cx.shared().idle.release_core(&mut synced, core);
1194
1195 drop(synced);
1196
1197 if was_searching {
1198 if cx.shared().idle.transition_worker_from_searching() {
1199 // cx.shared().idle.snapshot(&mut self.idle_snapshot);
1200 // We were the last searching worker, we need to do one last check
1201 for i in 0..cx.shared().remotes.len() {
1202 if !cx.shared().remotes[i].steal.is_empty() {
1203 let mut synced = cx.shared().synced.lock();
1204
1205 // Try to get a core
1206 if let Some(mut core) = self.try_acquire_available_core(cx, &mut synced) {
1207 cx.shared().idle.transition_worker_to_searching(&mut core);
1208 return Ok((None, core));
1209 } else {
1210 // Fall back to the park routine
1211 break;
1212 }
1213 }
1214 }
1215 }
1216 }
1217
1218 if let Some(mut driver) = cx.shared().take_driver() {
1219 // Wait for driver events
1220 driver.park(&cx.handle.driver);
1221
1222 synced = cx.shared().synced.lock();
1223
1224 if cx.shared().inject.is_closed(&mut synced.inject) {
1225 synced.shutdown_driver = Some(driver);
1226 self.shutdown_clear_defer(cx);
1227 cx.shared().shutdown_finalize(&cx.handle, &mut synced);
1228 return Err(());
1229 }
1230
1231 // Put the driver back
1232 cx.shared().driver.set(driver);
1233
1234 // Try to acquire an available core to schedule I/O events
1235 if let Some(core) = self.try_acquire_available_core(cx, &mut synced) {
1236 // This may result in a task being run
1237 self.schedule_deferred_with_core(cx, core, move || synced)
1238 } else {
1239 // Schedule any deferred tasks
1240 self.schedule_deferred_without_core(cx, &mut synced);
1241
1242 // Wait for a core.
1243 self.wait_for_core(cx, synced)
1244 }
1245 } else {
1246 synced = cx.shared().synced.lock();
1247
1248 // Wait for a core to be assigned to us
1249 self.wait_for_core(cx, synced)
1250 }
1251 }
1252
1253 fn transition_to_searching(&self, cx: &Context, core: &mut Core) -> bool {
1254 if !core.is_searching {
1255 cx.shared().idle.try_transition_worker_to_searching(core);
1256 }
1257
1258 core.is_searching
1259 }
1260
1261 /// Returns `true` if another worker must be notified
1262 fn transition_from_searching(&self, cx: &Context, core: &mut Core) -> bool {
1263 if !core.is_searching {
1264 return false;
1265 }
1266
1267 core.is_searching = false;
1268 cx.shared().idle.transition_worker_from_searching()
1269 }
1270
1271 fn can_transition_to_parked(&self, core: &mut Core) -> bool {
1272 !self.has_tasks(core) && !self.is_shutdown && !self.is_traced
1273 }
1274
1275 fn has_tasks(&self, core: &Core) -> bool {
1276 core.lifo_slot.is_some() || !core.run_queue.is_empty()
1277 }
1278
1279 fn reset_lifo_enabled(&self, cx: &Context) {
1280 cx.lifo_enabled
1281 .set(!cx.handle.shared.config.disable_lifo_slot);
1282 }
1283
1284 fn assert_lifo_enabled_is_correct(&self, cx: &Context) {
1285 debug_assert_eq!(
1286 cx.lifo_enabled.get(),
1287 !cx.handle.shared.config.disable_lifo_slot
1288 );
1289 }
1290
1291 fn tune_global_queue_interval(&mut self, cx: &Context, core: &mut Core) {
1292 let next = core.stats.tuned_global_queue_interval(&cx.shared().config);
1293
1294 // Smooth out jitter
1295 if abs_diff(self.global_queue_interval, next) > 2 {
1296 self.global_queue_interval = next;
1297 }
1298 }
1299
1300 fn shutdown_clear_defer(&self, cx: &Context) {
1301 let mut defer = cx.defer.borrow_mut();
1302
1303 for task in defer.drain(..) {
1304 drop(task);
1305 }
1306 }
1307 }
1308
1309 impl Context {
1310 pub(crate) fn defer(&self, waker: &Waker) {
1311 // TODO: refactor defer across all runtimes
1312 waker.wake_by_ref();
1313 }
1314
1315 fn shared(&self) -> &Shared {
1316 &self.handle.shared
1317 }
1318
1319 #[cfg_attr(not(feature = "time"), allow(dead_code))]
1320 pub(crate) fn get_worker_index(&self) -> usize {
1321 self.index
1322 }
1323 }
1324
1325 impl Core {
1326 fn next_local_task(&mut self) -> Option<Notified> {
1327 self.next_lifo_task().or_else(|| self.run_queue.pop())
1328 }
1329
1330 fn next_lifo_task(&mut self) -> Option<Notified> {
1331 self.lifo_slot.take()
1332 }
1333 }
1334
1335 impl Shared {
1336 fn next_remote_task_synced(&self, synced: &mut Synced) -> Option<Notified> {
1337 // safety: we only have access to a valid `Synced` in this file.
1338 unsafe { self.inject.pop(&mut synced.inject) }
1339 }
1340
1341 pub(super) fn schedule_task(&self, task: Notified, is_yield: bool) {
1342 use std::ptr;
1343
1344 with_current(|maybe_cx| {
1345 if let Some(cx) = maybe_cx {
1346 // Make sure the task is part of the **current** scheduler.
1347 if ptr::eq(self, &cx.handle.shared) {
1348 // And the current thread still holds a core
1349 if let Some(core) = cx.core.borrow_mut().as_mut() {
1350 if is_yield {
1351 cx.defer.borrow_mut().push(task);
1352 } else {
1353 self.schedule_local(cx, core, task);
1354 }
1355 } else {
1356 // This can happen if either the core was stolen
1357 // (`block_in_place`) or the notification happens from
1358 // the driver.
1359 cx.defer.borrow_mut().push(task);
1360 }
1361 return;
1362 }
1363 }
1364
1365 // Otherwise, use the inject queue.
1366 self.schedule_remote(task);
1367 })
1368 }
1369
1370 fn schedule_local(&self, cx: &Context, core: &mut Core, task: Notified) {
1371 core.stats.inc_local_schedule_count();
1372
1373 if cx.lifo_enabled.get() {
1374 // Push to the LIFO slot
1375 let prev = std::mem::replace(&mut core.lifo_slot, Some(task));
1376 // let prev = cx.shared().remotes[core.index].lifo_slot.swap_local(task);
1377
1378 if let Some(prev) = prev {
1379 core.run_queue
1380 .push_back_or_overflow(prev, self, &mut core.stats);
1381 } else {
1382 return;
1383 }
1384 } else {
1385 core.run_queue
1386 .push_back_or_overflow(task, self, &mut core.stats);
1387 }
1388
1389 self.notify_parked_local();
1390 }
1391
1392 fn notify_parked_local(&self) {
1393 super::counters::inc_num_inc_notify_local();
1394 self.idle.notify_local(self);
1395 }
1396
1397 fn schedule_remote(&self, task: Notified) {
1398 super::counters::inc_num_notify_remote();
1399 self.scheduler_metrics.inc_remote_schedule_count();
1400
1401 let mut synced = self.synced.lock();
1402 // Push the task in the
1403 self.push_remote_task(&mut synced, task);
1404
1405 // Notify a worker. The mutex is passed in and will be released as part
1406 // of the method call.
1407 self.idle.notify_remote(synced, self);
1408 }
1409
1410 pub(super) fn close(&self, handle: &Handle) {
1411 {
1412 let mut synced = self.synced.lock();
1413
1414 if let Some(driver) = self.driver.take() {
1415 synced.shutdown_driver = Some(driver);
1416 }
1417
1418 if !self.inject.close(&mut synced.inject) {
1419 return;
1420 }
1421
1422 // Set the shutdown flag on all available cores
1423 self.idle.shutdown(&mut synced, self);
1424 }
1425
1426 // Any unassigned cores need to be shutdown, but we have to first drop
1427 // the lock
1428 self.idle.shutdown_unassigned_cores(handle, self);
1429 }
1430
1431 fn push_remote_task(&self, synced: &mut Synced, task: Notified) {
1432 // safety: passing in correct `idle::Synced`
1433 unsafe {
1434 self.inject.push(&mut synced.inject, task);
1435 }
1436 }
1437
1438 fn push_remote_task_batch<I>(&self, iter: I)
1439 where
1440 I: Iterator<Item = task::Notified<Arc<Handle>>>,
1441 {
1442 unsafe {
1443 self.inject.push_batch(self, iter);
1444 }
1445 }
1446
1447 fn push_remote_task_batch_synced<I>(&self, synced: &mut Synced, iter: I)
1448 where
1449 I: Iterator<Item = task::Notified<Arc<Handle>>>,
1450 {
1451 unsafe {
1452 self.inject.push_batch(&mut synced.inject, iter);
1453 }
1454 }
1455
1456 fn take_driver(&self) -> Option<Box<Driver>> {
1457 if !self.driver_enabled() {
1458 return None;
1459 }
1460
1461 self.driver.take()
1462 }
1463
1464 fn driver_enabled(&self) -> bool {
1465 self.condvars.len() > self.remotes.len()
1466 }
1467
1468 pub(super) fn shutdown_core(&self, handle: &Handle, mut core: Box<Core>) {
1469 // Start from a random inner list
1470 let start = core.rand.fastrand_n(self.owned.get_shard_size() as u32);
1471 self.owned.close_and_shutdown_all(start as usize);
1472
1473 core.stats.submit(&self.worker_metrics[core.index]);
1474
1475 let mut synced = self.synced.lock();
1476 synced.shutdown_cores.push(core);
1477
1478 self.shutdown_finalize(handle, &mut synced);
1479 }
1480
1481 pub(super) fn shutdown_finalize(&self, handle: &Handle, synced: &mut Synced) {
1482 // Wait for all cores
1483 if synced.shutdown_cores.len() != self.remotes.len() {
1484 return;
1485 }
1486
1487 let driver = synced.shutdown_driver.take();
1488
1489 if self.driver_enabled() && driver.is_none() {
1490 return;
1491 }
1492
1493 debug_assert!(self.owned.is_empty());
1494
1495 for mut core in synced.shutdown_cores.drain(..) {
1496 // Drain tasks from the local queue
1497 while core.next_local_task().is_some() {}
1498 }
1499
1500 // Shutdown the driver
1501 if let Some(mut driver) = driver {
1502 driver.shutdown(&handle.driver);
1503 }
1504
1505 // Drain the injection queue
1506 //
1507 // We already shut down every task, so we can simply drop the tasks. We
1508 // cannot call `next_remote_task()` because we already hold the lock.
1509 //
1510 // safety: passing in correct `idle::Synced`
1511 while let Some(task) = self.next_remote_task_synced(synced) {
1512 drop(task);
1513 }
1514 }
1515 }
1516
1517 impl Overflow<Arc<Handle>> for Shared {
1518 fn push(&self, task: task::Notified<Arc<Handle>>) {
1519 self.push_remote_task(&mut self.synced.lock(), task);
1520 }
1521
1522 fn push_batch<I>(&self, iter: I)
1523 where
1524 I: Iterator<Item = task::Notified<Arc<Handle>>>,
1525 {
1526 self.push_remote_task_batch(iter)
1527 }
1528 }
1529
1530 impl<'a> Lock<inject::Synced> for &'a Shared {
1531 type Handle = SyncedGuard<'a>;
1532
1533 fn lock(self) -> Self::Handle {
1534 SyncedGuard {
1535 lock: self.synced.lock(),
1536 }
1537 }
1538 }
1539
1540 impl<'a> Lock<Synced> for &'a Shared {
1541 type Handle = SyncedGuard<'a>;
1542
1543 fn lock(self) -> Self::Handle {
1544 SyncedGuard {
1545 lock: self.synced.lock(),
1546 }
1547 }
1548 }
1549
1550 impl task::Schedule for Arc<Handle> {
1551 fn release(&self, task: &Task) -> Option<Task> {
1552 self.shared.owned.remove(task)
1553 }
1554
1555 fn schedule(&self, task: Notified) {
1556 self.shared.schedule_task(task, false);
1557 }
1558
1559 fn yield_now(&self, task: Notified) {
1560 self.shared.schedule_task(task, true);
1561 }
1562 }
1563
1564 impl AsMut<Synced> for Synced {
1565 fn as_mut(&mut self) -> &mut Synced {
1566 self
1567 }
1568 }
1569
1570 pub(crate) struct SyncedGuard<'a> {
1571 lock: crate::loom::sync::MutexGuard<'a, Synced>,
1572 }
1573
1574 impl<'a> AsMut<inject::Synced> for SyncedGuard<'a> {
1575 fn as_mut(&mut self) -> &mut inject::Synced {
1576 &mut self.lock.inject
1577 }
1578 }
1579
1580 impl<'a> AsMut<Synced> for SyncedGuard<'a> {
1581 fn as_mut(&mut self) -> &mut Synced {
1582 &mut self.lock
1583 }
1584 }
1585
1586 #[track_caller]
1587 fn with_current<R>(f: impl FnOnce(Option<&Context>) -> R) -> R {
1588 use scheduler::Context::MultiThreadAlt;
1589
1590 context::with_scheduler(|ctx| match ctx {
1591 Some(MultiThreadAlt(ctx)) => f(Some(ctx)),
1592 _ => f(None),
1593 })
1594 }
1595
1596 // `u32::abs_diff` is not available on Tokio's MSRV.
1597 fn abs_diff(a: u32, b: u32) -> u32 {
1598 if a > b {
1599 a - b
1600 } else {
1601 b - a
1602 }
1603 }