Debian Codegraph @

third_party/rust/tokio/src/runtime/scheduler/multi_thread/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, Mutex};
60 use crate::runtime;
61 use crate::runtime::context;
62 use crate::runtime::scheduler::multi_thread::{
63 idle, queue, Counters, Handle, Idle, Overflow, Parker, Stats, TraceStatus, Unparker,
64 };
65 use crate::runtime::scheduler::{inject, Defer, Lock};
66 use crate::runtime::task::OwnedTasks;
67 use crate::runtime::{
68 blocking, coop, driver, scheduler, task, Config, SchedulerMetrics, WorkerMetrics,
69 };
70 use crate::util::atomic_cell::AtomicCell;
71 use crate::util::rand::{FastRand, RngSeedGenerator};
72
73 use std::cell::RefCell;
74 use std::task::Waker;
75 use std::thread;
76 use std::time::Duration;
77
78 cfg_unstable_metrics! {
79 mod metrics;
80 }
81
82 cfg_taskdump! {
83 mod taskdump;
84 }
85
86 cfg_not_taskdump! {
87 mod taskdump_mock;
88 }
89
90 /// A scheduler worker
91 pub(super) struct Worker {
92 /// Reference to scheduler's handle
93 handle: Arc<Handle>,
94
95 /// Index holding this worker's remote state
96 index: usize,
97
98 /// Used to hand-off a worker's core to another thread.
99 core: AtomicCell<Core>,
100 }
101
102 /// Core data
103 struct Core {
104 /// Used to schedule bookkeeping tasks every so often.
105 tick: u32,
106
107 /// When a task is scheduled from a worker, it is stored in this slot. The
108 /// worker will check this slot for a task **before** checking the run
109 /// queue. This effectively results in the **last** scheduled task to be run
110 /// next (LIFO). This is an optimization for improving locality which
111 /// benefits message passing patterns and helps to reduce latency.
112 lifo_slot: Option<Notified>,
113
114 /// When `true`, locally scheduled tasks go to the LIFO slot. When `false`,
115 /// they go to the back of the `run_queue`.
116 lifo_enabled: bool,
117
118 /// The worker-local run queue.
119 run_queue: queue::Local<Arc<Handle>>,
120
121 /// True if the worker is currently searching for more work. Searching
122 /// involves attempting to steal from other workers.
123 is_searching: bool,
124
125 /// True if the scheduler is being shutdown
126 is_shutdown: bool,
127
128 /// True if the scheduler is being traced
129 is_traced: bool,
130
131 /// Parker
132 ///
133 /// Stored in an `Option` as the parker is added / removed to make the
134 /// borrow checker happy.
135 park: Option<Parker>,
136
137 /// Per-worker runtime stats
138 stats: Stats,
139
140 /// How often to check the global queue
141 global_queue_interval: u32,
142
143 /// Fast random number generator.
144 rand: FastRand,
145 }
146
147 /// State shared across all workers
148 pub(crate) struct Shared {
149 /// Per-worker remote state. All other workers have access to this and is
150 /// how they communicate between each other.
151 remotes: Box<[Remote]>,
152
153 /// Global task queue used for:
154 /// 1. Submit work to the scheduler while **not** currently on a worker thread.
155 /// 2. Submit work to the scheduler when a worker run queue is saturated
156 pub(super) inject: inject::Shared<Arc<Handle>>,
157
158 /// Coordinates idle workers
159 idle: Idle,
160
161 /// Collection of all active tasks spawned onto this executor.
162 pub(crate) owned: OwnedTasks<Arc<Handle>>,
163
164 /// Data synchronized by the scheduler mutex
165 pub(super) synced: Mutex<Synced>,
166
167 /// Cores that have observed the shutdown signal
168 ///
169 /// The core is **not** placed back in the worker to avoid it from being
170 /// stolen by a thread that was spawned as part of `block_in_place`.
171 #[allow(clippy::vec_box)] // we're moving an already-boxed value
172 shutdown_cores: Mutex<Vec<Box<Core>>>,
173
174 /// The number of cores that have observed the trace signal.
175 pub(super) trace_status: TraceStatus,
176
177 /// Scheduler configuration options
178 config: Config,
179
180 /// Collects metrics from the runtime.
181 pub(super) scheduler_metrics: SchedulerMetrics,
182
183 pub(super) worker_metrics: Box<[WorkerMetrics]>,
184
185 /// Only held to trigger some code on drop. This is used to get internal
186 /// runtime metrics that can be useful when doing performance
187 /// investigations. This does nothing (empty struct, no drop impl) unless
188 /// the `tokio_internal_mt_counters` `cfg` flag is set.
189 _counters: Counters,
190 }
191
192 /// Data synchronized by the scheduler mutex
193 pub(crate) struct Synced {
194 /// Synchronized state for `Idle`.
195 pub(super) idle: idle::Synced,
196
197 /// Synchronized state for `Inject`.
198 pub(crate) inject: inject::Synced,
199 }
200
201 /// Used to communicate with a worker from other threads.
202 struct Remote {
203 /// Steals tasks from this worker.
204 pub(super) steal: queue::Steal<Arc<Handle>>,
205
206 /// Unparks the associated worker thread
207 unpark: Unparker,
208 }
209
210 /// Thread-local context
211 pub(crate) struct Context {
212 /// Worker
213 worker: Arc<Worker>,
214
215 /// Core data
216 core: RefCell<Option<Box<Core>>>,
217
218 /// Tasks to wake after resource drivers are polled. This is mostly to
219 /// handle yielded tasks.
220 pub(crate) defer: Defer,
221 }
222
223 /// Starts the workers
224 pub(crate) struct Launch(Vec<Arc<Worker>>);
225
226 /// Running a task may consume the core. If the core is still available when
227 /// running the task completes, it is returned. Otherwise, the worker will need
228 /// to stop processing.
229 type RunResult = Result<Box<Core>, ()>;
230
231 /// A task handle
232 type Task = task::Task<Arc<Handle>>;
233
234 /// A notified task handle
235 type Notified = task::Notified<Arc<Handle>>;
236
237 /// Value picked out of thin-air. Running the LIFO slot a handful of times
238 /// seems sufficient to benefit from locality. More than 3 times probably is
239 /// overweighing. The value can be tuned in the future with data that shows
240 /// improvements.
241 const MAX_LIFO_POLLS_PER_TICK: usize = 3;
242
243 pub(super) fn create(
244 size: usize,
245 park: Parker,
246 driver_handle: driver::Handle,
247 blocking_spawner: blocking::Spawner,
248 seed_generator: RngSeedGenerator,
249 config: Config,
250 ) -> (Arc<Handle>, Launch) {
251 let mut cores = Vec::with_capacity(size);
252 let mut remotes = Vec::with_capacity(size);
253 let mut worker_metrics = Vec::with_capacity(size);
254
255 // Create the local queues
256 for _ in 0..size {
257 let (steal, run_queue) = queue::local();
258
259 let park = park.clone();
260 let unpark = park.unpark();
261 let metrics = WorkerMetrics::from_config(&config);
262 let stats = Stats::new(&metrics);
263
264 cores.push(Box::new(Core {
265 tick: 0,
266 lifo_slot: None,
267 lifo_enabled: !config.disable_lifo_slot,
268 run_queue,
269 is_searching: false,
270 is_shutdown: false,
271 is_traced: false,
272 park: Some(park),
273 global_queue_interval: stats.tuned_global_queue_interval(&config),
274 stats,
275 rand: FastRand::from_seed(config.seed_generator.next_seed()),
276 }));
277
278 remotes.push(Remote { steal, unpark });
279 worker_metrics.push(metrics);
280 }
281
282 let (idle, idle_synced) = Idle::new(size);
283 let (inject, inject_synced) = inject::Shared::new();
284
285 let remotes_len = remotes.len();
286 let handle = Arc::new(Handle {
287 shared: Shared {
288 remotes: remotes.into_boxed_slice(),
289 inject,
290 idle,
291 owned: OwnedTasks::new(size),
292 synced: Mutex::new(Synced {
293 idle: idle_synced,
294 inject: inject_synced,
295 }),
296 shutdown_cores: Mutex::new(vec![]),
297 trace_status: TraceStatus::new(remotes_len),
298 config,
299 scheduler_metrics: SchedulerMetrics::new(),
300 worker_metrics: worker_metrics.into_boxed_slice(),
301 _counters: Counters,
302 },
303 driver: driver_handle,
304 blocking_spawner,
305 seed_generator,
306 });
307
308 let mut launch = Launch(vec![]);
309
310 for (index, core) in cores.drain(..).enumerate() {
311 launch.0.push(Arc::new(Worker {
312 handle: handle.clone(),
313 index,
314 core: AtomicCell::new(Some(core)),
315 }));
316 }
317
318 (handle, launch)
319 }
320
321 #[track_caller]
322 pub(crate) fn block_in_place<F, R>(f: F) -> R
323 where
324 F: FnOnce() -> R,
325 {
326 // Try to steal the worker core back
327 struct Reset {
328 take_core: bool,
329 budget: coop::Budget,
330 }
331
332 impl Drop for Reset {
333 fn drop(&mut self) {
334 with_current(|maybe_cx| {
335 if let Some(cx) = maybe_cx {
336 if self.take_core {
337 let core = cx.worker.core.take();
338
339 if core.is_some() {
340 cx.worker.handle.shared.worker_metrics[cx.worker.index]
341 .set_thread_id(thread::current().id());
342 }
343
344 let mut cx_core = cx.core.borrow_mut();
345 assert!(cx_core.is_none());
346 *cx_core = core;
347 }
348
349 // Reset the task budget as we are re-entering the
350 // runtime.
351 coop::set(self.budget);
352 }
353 });
354 }
355 }
356
357 let mut had_entered = false;
358 let mut take_core = false;
359
360 let setup_result = with_current(|maybe_cx| {
361 match (
362 crate::runtime::context::current_enter_context(),
363 maybe_cx.is_some(),
364 ) {
365 (context::EnterRuntime::Entered { .. }, true) => {
366 // We are on a thread pool runtime thread, so we just need to
367 // set up blocking.
368 had_entered = true;
369 }
370 (
371 context::EnterRuntime::Entered {
372 allow_block_in_place,
373 },
374 false,
375 ) => {
376 // We are on an executor, but _not_ on the thread pool. That is
377 // _only_ okay if we are in a thread pool runtime's block_on
378 // method:
379 if allow_block_in_place {
380 had_entered = true;
381 return Ok(());
382 } else {
383 // This probably means we are on the current_thread runtime or in a
384 // LocalSet, where it is _not_ okay to block.
385 return Err(
386 "can call blocking only when running on the multi-threaded runtime",
387 );
388 }
389 }
390 (context::EnterRuntime::NotEntered, true) => {
391 // This is a nested call to block_in_place (we already exited).
392 // All the necessary setup has already been done.
393 return Ok(());
394 }
395 (context::EnterRuntime::NotEntered, false) => {
396 // We are outside of the tokio runtime, so blocking is fine.
397 // We can also skip all of the thread pool blocking setup steps.
398 return Ok(());
399 }
400 }
401
402 let cx = maybe_cx.expect("no .is_some() == false cases above should lead here");
403
404 // Get the worker core. If none is set, then blocking is fine!
405 let mut core = match cx.core.borrow_mut().take() {
406 Some(core) => core,
407 None => return Ok(()),
408 };
409
410 // If we heavily call `spawn_blocking`, there might be no available thread to
411 // run this core. Except for the task in the lifo_slot, all tasks can be
412 // stolen, so we move the task out of the lifo_slot to the run_queue.
413 if let Some(task) = core.lifo_slot.take() {
414 core.run_queue
415 .push_back_or_overflow(task, &*cx.worker.handle, &mut core.stats);
416 }
417
418 // We are taking the core from the context and sending it to another
419 // thread.
420 take_core = true;
421
422 // The parker should be set here
423 assert!(core.park.is_some());
424
425 // In order to block, the core must be sent to another thread for
426 // execution.
427 //
428 // First, move the core back into the worker's shared core slot.
429 cx.worker.core.set(core);
430
431 // Next, clone the worker handle and send it to a new thread for
432 // processing.
433 //
434 // Once the blocking task is done executing, we will attempt to
435 // steal the core back.
436 let worker = cx.worker.clone();
437 runtime::spawn_blocking(move || run(worker));
438 Ok(())
439 });
440
441 if let Err(panic_message) = setup_result {
442 panic!("{}", panic_message);
443 }
444
445 if had_entered {
446 // Unset the current task's budget. Blocking sections are not
447 // constrained by task budgets.
448 let _reset = Reset {
449 take_core,
450 budget: coop::stop(),
451 };
452
453 crate::runtime::context::exit_runtime(f)
454 } else {
455 f()
456 }
457 }
458
459 impl Launch {
460 pub(crate) fn launch(mut self) {
461 for worker in self.0.drain(..) {
462 runtime::spawn_blocking(move || run(worker));
463 }
464 }
465 }
466
467 fn run(worker: Arc<Worker>) {
468 #[allow(dead_code)]
469 struct AbortOnPanic;
470
471 impl Drop for AbortOnPanic {
472 fn drop(&mut self) {
473 if std::thread::panicking() {
474 eprintln!("worker thread panicking; aborting process");
475 std::process::abort();
476 }
477 }
478 }
479
480 // Catching panics on worker threads in tests is quite tricky. Instead, when
481 // debug assertions are enabled, we just abort the process.
482 #[cfg(debug_assertions)]
483 let _abort_on_panic = AbortOnPanic;
484
485 // Acquire a core. If this fails, then another thread is running this
486 // worker and there is nothing further to do.
487 let core = match worker.core.take() {
488 Some(core) => core,
489 None => return,
490 };
491
492 worker.handle.shared.worker_metrics[worker.index].set_thread_id(thread::current().id());
493
494 let handle = scheduler::Handle::MultiThread(worker.handle.clone());
495
496 crate::runtime::context::enter_runtime(&handle, true, |_| {
497 // Set the worker context.
498 let cx = scheduler::Context::MultiThread(Context {
499 worker,
500 core: RefCell::new(None),
501 defer: Defer::new(),
502 });
503
504 context::set_scheduler(&cx, || {
505 let cx = cx.expect_multi_thread();
506
507 // This should always be an error. It only returns a `Result` to support
508 // using `?` to short circuit.
509 assert!(cx.run(core).is_err());
510
511 // Check if there are any deferred tasks to notify. This can happen when
512 // the worker core is lost due to `block_in_place()` being called from
513 // within the task.
514 cx.defer.wake();
515 });
516 });
517 }
518
519 impl Context {
520 fn run(&self, mut core: Box<Core>) -> RunResult {
521 // Reset `lifo_enabled` here in case the core was previously stolen from
522 // a task that had the LIFO slot disabled.
523 self.reset_lifo_enabled(&mut core);
524
525 // Start as "processing" tasks as polling tasks from the local queue
526 // will be one of the first things we do.
527 core.stats.start_processing_scheduled_tasks();
528
529 while !core.is_shutdown {
530 self.assert_lifo_enabled_is_correct(&core);
531
532 if core.is_traced {
533 core = self.worker.handle.trace_core(core);
534 }
535
536 // Increment the tick
537 core.tick();
538
539 // Run maintenance, if needed
540 core = self.maintenance(core);
541
542 // First, check work available to the current worker.
543 if let Some(task) = core.next_task(&self.worker) {
544 core = self.run_task(task, core)?;
545 continue;
546 }
547
548 // We consumed all work in the queues and will start searching for work.
549 core.stats.end_processing_scheduled_tasks();
550
551 // There is no more **local** work to process, try to steal work
552 // from other workers.
553 if let Some(task) = core.steal_work(&self.worker) {
554 // Found work, switch back to processing
555 core.stats.start_processing_scheduled_tasks();
556 core = self.run_task(task, core)?;
557 } else {
558 // Wait for work
559 core = if !self.defer.is_empty() {
560 self.park_timeout(core, Some(Duration::from_millis(0)))
561 } else {
562 self.park(core)
563 };
564 core.stats.start_processing_scheduled_tasks();
565 }
566 }
567
568 core.pre_shutdown(&self.worker);
569 // Signal shutdown
570 self.worker.handle.shutdown_core(core);
571 Err(())
572 }
573
574 fn run_task(&self, task: Notified, mut core: Box<Core>) -> RunResult {
575 let task = self.worker.handle.shared.owned.assert_owner(task);
576
577 // Make sure the worker is not in the **searching** state. This enables
578 // another idle worker to try to steal work.
579 core.transition_from_searching(&self.worker);
580
581 self.assert_lifo_enabled_is_correct(&core);
582
583 // Measure the poll start time. Note that we may end up polling other
584 // tasks under this measurement. In this case, the tasks came from the
585 // LIFO slot and are considered part of the current task for scheduling
586 // purposes. These tasks inherent the "parent"'s limits.
587 core.stats.start_poll();
588
589 // Make the core available to the runtime context
590 *self.core.borrow_mut() = Some(core);
591
592 // Run the task
593 coop::budget(|| {
594 task.run();
595 let mut lifo_polls = 0;
596
597 // As long as there is budget remaining and a task exists in the
598 // `lifo_slot`, then keep running.
599 loop {
600 // Check if we still have the core. If not, the core was stolen
601 // by another worker.
602 let mut core = match self.core.borrow_mut().take() {
603 Some(core) => core,
604 None => {
605 // In this case, we cannot call `reset_lifo_enabled()`
606 // because the core was stolen. The stealer will handle
607 // that at the top of `Context::run`
608 return Err(());
609 }
610 };
611
612 // Check for a task in the LIFO slot
613 let task = match core.lifo_slot.take() {
614 Some(task) => task,
615 None => {
616 self.reset_lifo_enabled(&mut core);
617 core.stats.end_poll();
618 return Ok(core);
619 }
620 };
621
622 if !coop::has_budget_remaining() {
623 core.stats.end_poll();
624
625 // Not enough budget left to run the LIFO task, push it to
626 // the back of the queue and return.
627 core.run_queue.push_back_or_overflow(
628 task,
629 &*self.worker.handle,
630 &mut core.stats,
631 );
632 // If we hit this point, the LIFO slot should be enabled.
633 // There is no need to reset it.
634 debug_assert!(core.lifo_enabled);
635 return Ok(core);
636 }
637
638 // Track that we are about to run a task from the LIFO slot.
639 lifo_polls += 1;
640 super::counters::inc_lifo_schedules();
641
642 // Disable the LIFO slot if we reach our limit
643 //
644 // In ping-ping style workloads where task A notifies task B,
645 // which notifies task A again, continuously prioritizing the
646 // LIFO slot can cause starvation as these two tasks will
647 // repeatedly schedule the other. To mitigate this, we limit the
648 // number of times the LIFO slot is prioritized.
649 if lifo_polls >= MAX_LIFO_POLLS_PER_TICK {
650 core.lifo_enabled = false;
651 super::counters::inc_lifo_capped();
652 }
653
654 // Run the LIFO task, then loop
655 *self.core.borrow_mut() = Some(core);
656 let task = self.worker.handle.shared.owned.assert_owner(task);
657 task.run();
658 }
659 })
660 }
661
662 fn reset_lifo_enabled(&self, core: &mut Core) {
663 core.lifo_enabled = !self.worker.handle.shared.config.disable_lifo_slot;
664 }
665
666 fn assert_lifo_enabled_is_correct(&self, core: &Core) {
667 debug_assert_eq!(
668 core.lifo_enabled,
669 !self.worker.handle.shared.config.disable_lifo_slot
670 );
671 }
672
673 fn maintenance(&self, mut core: Box<Core>) -> Box<Core> {
674 if core.tick % self.worker.handle.shared.config.event_interval == 0 {
675 super::counters::inc_num_maintenance();
676
677 core.stats.end_processing_scheduled_tasks();
678
679 // Call `park` with a 0 timeout. This enables the I/O driver, timer, ...
680 // to run without actually putting the thread to sleep.
681 core = self.park_timeout(core, Some(Duration::from_millis(0)));
682
683 // Run regularly scheduled maintenance
684 core.maintenance(&self.worker);
685
686 core.stats.start_processing_scheduled_tasks();
687 }
688
689 core
690 }
691
692 /// Parks the worker thread while waiting for tasks to execute.
693 ///
694 /// This function checks if indeed there's no more work left to be done before parking.
695 /// Also important to notice that, before parking, the worker thread will try to take
696 /// ownership of the Driver (IO/Time) and dispatch any events that might have fired.
697 /// Whenever a worker thread executes the Driver loop, all waken tasks are scheduled
698 /// in its own local queue until the queue saturates (ntasks > `LOCAL_QUEUE_CAPACITY`).
699 /// When the local queue is saturated, the overflow tasks are added to the injection queue
700 /// from where other workers can pick them up.
701 /// Also, we rely on the workstealing algorithm to spread the tasks amongst workers
702 /// after all the IOs get dispatched
703 fn park(&self, mut core: Box<Core>) -> Box<Core> {
704 if let Some(f) = &self.worker.handle.shared.config.before_park {
705 f();
706 }
707
708 if core.transition_to_parked(&self.worker) {
709 while !core.is_shutdown && !core.is_traced {
710 core.stats.about_to_park();
711 core.stats
712 .submit(&self.worker.handle.shared.worker_metrics[self.worker.index]);
713
714 core = self.park_timeout(core, None);
715
716 core.stats.unparked();
717
718 // Run regularly scheduled maintenance
719 core.maintenance(&self.worker);
720
721 if core.transition_from_parked(&self.worker) {
722 break;
723 }
724 }
725 }
726
727 if let Some(f) = &self.worker.handle.shared.config.after_unpark {
728 f();
729 }
730 core
731 }
732
733 fn park_timeout(&self, mut core: Box<Core>, duration: Option<Duration>) -> Box<Core> {
734 self.assert_lifo_enabled_is_correct(&core);
735
736 // Take the parker out of core
737 let mut park = core.park.take().expect("park missing");
738
739 // Store `core` in context
740 *self.core.borrow_mut() = Some(core);
741
742 // Park thread
743 if let Some(timeout) = duration {
744 park.park_timeout(&self.worker.handle.driver, timeout);
745 } else {
746 park.park(&self.worker.handle.driver);
747 }
748
749 self.defer.wake();
750
751 // Remove `core` from context
752 core = self.core.borrow_mut().take().expect("core missing");
753
754 // Place `park` back in `core`
755 core.park = Some(park);
756
757 if core.should_notify_others() {
758 self.worker.handle.notify_parked_local();
759 }
760
761 core
762 }
763
764 pub(crate) fn defer(&self, waker: &Waker) {
765 self.defer.defer(waker);
766 }
767
768 #[allow(dead_code)]
769 pub(crate) fn get_worker_index(&self) -> usize {
770 self.worker.index
771 }
772 }
773
774 impl Core {
775 /// Increment the tick
776 fn tick(&mut self) {
777 self.tick = self.tick.wrapping_add(1);
778 }
779
780 /// Return the next notified task available to this worker.
781 fn next_task(&mut self, worker: &Worker) -> Option<Notified> {
782 if self.tick % self.global_queue_interval == 0 {
783 // Update the global queue interval, if needed
784 self.tune_global_queue_interval(worker);
785
786 worker
787 .handle
788 .next_remote_task()
789 .or_else(|| self.next_local_task())
790 } else {
791 let maybe_task = self.next_local_task();
792
793 if maybe_task.is_some() {
794 return maybe_task;
795 }
796
797 if worker.inject().is_empty() {
798 return None;
799 }
800
801 // Other threads can only **remove** tasks from the current worker's
802 // `run_queue`. So, we can be confident that by the time we call
803 // `run_queue.push_back` below, there will be *at least* `cap`
804 // available slots in the queue.
805 let cap = usize::min(
806 self.run_queue.remaining_slots(),
807 self.run_queue.max_capacity() / 2,
808 );
809
810 // The worker is currently idle, pull a batch of work from the
811 // injection queue. We don't want to pull *all* the work so other
812 // workers can also get some.
813 let n = usize::min(
814 worker.inject().len() / worker.handle.shared.remotes.len() + 1,
815 cap,
816 );
817
818 // Take at least one task since the first task is returned directly
819 // and not pushed onto the local queue.
820 let n = usize::max(1, n);
821
822 let mut synced = worker.handle.shared.synced.lock();
823 // safety: passing in the correct `inject::Synced`.
824 let mut tasks = unsafe { worker.inject().pop_n(&mut synced.inject, n) };
825
826 // Pop the first task to return immediately
827 let ret = tasks.next();
828
829 // Push the rest of the on the run queue
830 self.run_queue.push_back(tasks);
831
832 ret
833 }
834 }
835
836 fn next_local_task(&mut self) -> Option<Notified> {
837 self.lifo_slot.take().or_else(|| self.run_queue.pop())
838 }
839
840 /// Function responsible for stealing tasks from another worker
841 ///
842 /// Note: Only if less than half the workers are searching for tasks to steal
843 /// a new worker will actually try to steal. The idea is to make sure not all
844 /// workers will be trying to steal at the same time.
845 fn steal_work(&mut self, worker: &Worker) -> Option<Notified> {
846 if !self.transition_to_searching(worker) {
847 return None;
848 }
849
850 let num = worker.handle.shared.remotes.len();
851 // Start from a random worker
852 let start = self.rand.fastrand_n(num as u32) as usize;
853
854 for i in 0..num {
855 let i = (start + i) % num;
856
857 // Don't steal from ourself! We know we don't have work.
858 if i == worker.index {
859 continue;
860 }
861
862 let target = &worker.handle.shared.remotes[i];
863 if let Some(task) = target
864 .steal
865 .steal_into(&mut self.run_queue, &mut self.stats)
866 {
867 return Some(task);
868 }
869 }
870
871 // Fallback on checking the global queue
872 worker.handle.next_remote_task()
873 }
874
875 fn transition_to_searching(&mut self, worker: &Worker) -> bool {
876 if !self.is_searching {
877 self.is_searching = worker.handle.shared.idle.transition_worker_to_searching();
878 }
879
880 self.is_searching
881 }
882
883 fn transition_from_searching(&mut self, worker: &Worker) {
884 if !self.is_searching {
885 return;
886 }
887
888 self.is_searching = false;
889 worker.handle.transition_worker_from_searching();
890 }
891
892 fn has_tasks(&self) -> bool {
893 self.lifo_slot.is_some() || self.run_queue.has_tasks()
894 }
895
896 fn should_notify_others(&self) -> bool {
897 // If there are tasks available to steal, but this worker is not
898 // looking for tasks to steal, notify another worker.
899 if self.is_searching {
900 return false;
901 }
902 self.lifo_slot.is_some() as usize + self.run_queue.len() > 1
903 }
904
905 /// Prepares the worker state for parking.
906 ///
907 /// Returns true if the transition happened, false if there is work to do first.
908 fn transition_to_parked(&mut self, worker: &Worker) -> bool {
909 // Workers should not park if they have work to do
910 if self.has_tasks() || self.is_traced {
911 return false;
912 }
913
914 // When the final worker transitions **out** of searching to parked, it
915 // must check all the queues one last time in case work materialized
916 // between the last work scan and transitioning out of searching.
917 let is_last_searcher = worker.handle.shared.idle.transition_worker_to_parked(
918 &worker.handle.shared,
919 worker.index,
920 self.is_searching,
921 );
922
923 // The worker is no longer searching. Setting this is the local cache
924 // only.
925 self.is_searching = false;
926
927 if is_last_searcher {
928 worker.handle.notify_if_work_pending();
929 }
930
931 true
932 }
933
934 /// Returns `true` if the transition happened.
935 fn transition_from_parked(&mut self, worker: &Worker) -> bool {
936 // If a task is in the lifo slot/run queue, then we must unpark regardless of
937 // being notified
938 if self.has_tasks() {
939 // When a worker wakes, it should only transition to the "searching"
940 // state when the wake originates from another worker *or* a new task
941 // is pushed. We do *not* want the worker to transition to "searching"
942 // when it wakes when the I/O driver receives new events.
943 self.is_searching = !worker
944 .handle
945 .shared
946 .idle
947 .unpark_worker_by_id(&worker.handle.shared, worker.index);
948 return true;
949 }
950
951 if worker
952 .handle
953 .shared
954 .idle
955 .is_parked(&worker.handle.shared, worker.index)
956 {
957 return false;
958 }
959
960 // When unparked, the worker is in the searching state.
961 self.is_searching = true;
962 true
963 }
964
965 /// Runs maintenance work such as checking the pool's state.
966 fn maintenance(&mut self, worker: &Worker) {
967 self.stats
968 .submit(&worker.handle.shared.worker_metrics[worker.index]);
969
970 if !self.is_shutdown {
971 // Check if the scheduler has been shutdown
972 let synced = worker.handle.shared.synced.lock();
973 self.is_shutdown = worker.inject().is_closed(&synced.inject);
974 }
975
976 if !self.is_traced {
977 // Check if the worker should be tracing.
978 self.is_traced = worker.handle.shared.trace_status.trace_requested();
979 }
980 }
981
982 /// Signals all tasks to shut down, and waits for them to complete. Must run
983 /// before we enter the single-threaded phase of shutdown processing.
984 fn pre_shutdown(&mut self, worker: &Worker) {
985 // Start from a random inner list
986 let start = self
987 .rand
988 .fastrand_n(worker.handle.shared.owned.get_shard_size() as u32);
989 // Signal to all tasks to shut down.
990 worker
991 .handle
992 .shared
993 .owned
994 .close_and_shutdown_all(start as usize);
995
996 self.stats
997 .submit(&worker.handle.shared.worker_metrics[worker.index]);
998 }
999
1000 /// Shuts down the core.
1001 fn shutdown(&mut self, handle: &Handle) {
1002 // Take the core
1003 let mut park = self.park.take().expect("park missing");
1004
1005 // Drain the queue
1006 while self.next_local_task().is_some() {}
1007
1008 park.shutdown(&handle.driver);
1009 }
1010
1011 fn tune_global_queue_interval(&mut self, worker: &Worker) {
1012 let next = self
1013 .stats
1014 .tuned_global_queue_interval(&worker.handle.shared.config);
1015
1016 // Smooth out jitter
1017 if abs_diff(self.global_queue_interval, next) > 2 {
1018 self.global_queue_interval = next;
1019 }
1020 }
1021 }
1022
1023 impl Worker {
1024 /// Returns a reference to the scheduler's injection queue.
1025 fn inject(&self) -> &inject::Shared<Arc<Handle>> {
1026 &self.handle.shared.inject
1027 }
1028 }
1029
1030 // TODO: Move `Handle` impls into handle.rs
1031 impl task::Schedule for Arc<Handle> {
1032 fn release(&self, task: &Task) -> Option<Task> {
1033 self.shared.owned.remove(task)
1034 }
1035
1036 fn schedule(&self, task: Notified) {
1037 self.schedule_task(task, false);
1038 }
1039
1040 fn yield_now(&self, task: Notified) {
1041 self.schedule_task(task, true);
1042 }
1043 }
1044
1045 impl Handle {
1046 pub(super) fn schedule_task(&self, task: Notified, is_yield: bool) {
1047 with_current(|maybe_cx| {
1048 if let Some(cx) = maybe_cx {
1049 // Make sure the task is part of the **current** scheduler.
1050 if self.ptr_eq(&cx.worker.handle) {
1051 // And the current thread still holds a core
1052 if let Some(core) = cx.core.borrow_mut().as_mut() {
1053 self.schedule_local(core, task, is_yield);
1054 return;
1055 }
1056 }
1057 }
1058
1059 // Otherwise, use the inject queue.
1060 self.push_remote_task(task);
1061 self.notify_parked_remote();
1062 });
1063 }
1064
1065 pub(super) fn schedule_option_task_without_yield(&self, task: Option<Notified>) {
1066 if let Some(task) = task {
1067 self.schedule_task(task, false);
1068 }
1069 }
1070
1071 fn schedule_local(&self, core: &mut Core, task: Notified, is_yield: bool) {
1072 core.stats.inc_local_schedule_count();
1073
1074 // Spawning from the worker thread. If scheduling a "yield" then the
1075 // task must always be pushed to the back of the queue, enabling other
1076 // tasks to be executed. If **not** a yield, then there is more
1077 // flexibility and the task may go to the front of the queue.
1078 let should_notify = if is_yield || !core.lifo_enabled {
1079 core.run_queue
1080 .push_back_or_overflow(task, self, &mut core.stats);
1081 true
1082 } else {
1083 // Push to the LIFO slot
1084 let prev = core.lifo_slot.take();
1085 let ret = prev.is_some();
1086
1087 if let Some(prev) = prev {
1088 core.run_queue
1089 .push_back_or_overflow(prev, self, &mut core.stats);
1090 }
1091
1092 core.lifo_slot = Some(task);
1093
1094 ret
1095 };
1096
1097 // Only notify if not currently parked. If `park` is `None`, then the
1098 // scheduling is from a resource driver. As notifications often come in
1099 // batches, the notification is delayed until the park is complete.
1100 if should_notify && core.park.is_some() {
1101 self.notify_parked_local();
1102 }
1103 }
1104
1105 fn next_remote_task(&self) -> Option<Notified> {
1106 if self.shared.inject.is_empty() {
1107 return None;
1108 }
1109
1110 let mut synced = self.shared.synced.lock();
1111 // safety: passing in correct `idle::Synced`
1112 unsafe { self.shared.inject.pop(&mut synced.inject) }
1113 }
1114
1115 fn push_remote_task(&self, task: Notified) {
1116 self.shared.scheduler_metrics.inc_remote_schedule_count();
1117
1118 let mut synced = self.shared.synced.lock();
1119 // safety: passing in correct `idle::Synced`
1120 unsafe {
1121 self.shared.inject.push(&mut synced.inject, task);
1122 }
1123 }
1124
1125 pub(super) fn close(&self) {
1126 if self
1127 .shared
1128 .inject
1129 .close(&mut self.shared.synced.lock().inject)
1130 {
1131 self.notify_all();
1132 }
1133 }
1134
1135 fn notify_parked_local(&self) {
1136 super::counters::inc_num_inc_notify_local();
1137
1138 if let Some(index) = self.shared.idle.worker_to_notify(&self.shared) {
1139 super::counters::inc_num_unparks_local();
1140 self.shared.remotes[index].unpark.unpark(&self.driver);
1141 }
1142 }
1143
1144 fn notify_parked_remote(&self) {
1145 if let Some(index) = self.shared.idle.worker_to_notify(&self.shared) {
1146 self.shared.remotes[index].unpark.unpark(&self.driver);
1147 }
1148 }
1149
1150 pub(super) fn notify_all(&self) {
1151 for remote in &self.shared.remotes[..] {
1152 remote.unpark.unpark(&self.driver);
1153 }
1154 }
1155
1156 fn notify_if_work_pending(&self) {
1157 for remote in &self.shared.remotes[..] {
1158 if !remote.steal.is_empty() {
1159 self.notify_parked_local();
1160 return;
1161 }
1162 }
1163
1164 if !self.shared.inject.is_empty() {
1165 self.notify_parked_local();
1166 }
1167 }
1168
1169 fn transition_worker_from_searching(&self) {
1170 if self.shared.idle.transition_worker_from_searching() {
1171 // We are the final searching worker. Because work was found, we
1172 // need to notify another worker.
1173 self.notify_parked_local();
1174 }
1175 }
1176
1177 /// Signals that a worker has observed the shutdown signal and has replaced
1178 /// its core back into its handle.
1179 ///
1180 /// If all workers have reached this point, the final cleanup is performed.
1181 fn shutdown_core(&self, core: Box<Core>) {
1182 let mut cores = self.shared.shutdown_cores.lock();
1183 cores.push(core);
1184
1185 if cores.len() != self.shared.remotes.len() {
1186 return;
1187 }
1188
1189 debug_assert!(self.shared.owned.is_empty());
1190
1191 for mut core in cores.drain(..) {
1192 core.shutdown(self);
1193 }
1194
1195 // Drain the injection queue
1196 //
1197 // We already shut down every task, so we can simply drop the tasks.
1198 while let Some(task) = self.next_remote_task() {
1199 drop(task);
1200 }
1201 }
1202
1203 fn ptr_eq(&self, other: &Handle) -> bool {
1204 std::ptr::eq(self, other)
1205 }
1206 }
1207
1208 impl Overflow<Arc<Handle>> for Handle {
1209 fn push(&self, task: task::Notified<Arc<Handle>>) {
1210 self.push_remote_task(task);
1211 }
1212
1213 fn push_batch<I>(&self, iter: I)
1214 where
1215 I: Iterator<Item = task::Notified<Arc<Handle>>>,
1216 {
1217 unsafe {
1218 self.shared.inject.push_batch(self, iter);
1219 }
1220 }
1221 }
1222
1223 pub(crate) struct InjectGuard<'a> {
1224 lock: crate::loom::sync::MutexGuard<'a, Synced>,
1225 }
1226
1227 impl<'a> AsMut<inject::Synced> for InjectGuard<'a> {
1228 fn as_mut(&mut self) -> &mut inject::Synced {
1229 &mut self.lock.inject
1230 }
1231 }
1232
1233 impl<'a> Lock<inject::Synced> for &'a Handle {
1234 type Handle = InjectGuard<'a>;
1235
1236 fn lock(self) -> Self::Handle {
1237 InjectGuard {
1238 lock: self.shared.synced.lock(),
1239 }
1240 }
1241 }
1242
1243 #[track_caller]
1244 fn with_current<R>(f: impl FnOnce(Option<&Context>) -> R) -> R {
1245 use scheduler::Context::MultiThread;
1246
1247 context::with_scheduler(|ctx| match ctx {
1248 Some(MultiThread(ctx)) => f(Some(ctx)),
1249 _ => f(None),
1250 })
1251 }
1252
1253 // `u32::abs_diff` is not available on Tokio's MSRV.
1254 fn abs_diff(a: u32, b: u32) -> u32 {
1255 if a > b {
1256 a - b
1257 } else {
1258 b - a
1259 }
1260 }