Skip to main content

tokio/runtime/scheduler/multi_thread/
worker.rs

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
59use crate::loom::sync::{Arc, Mutex};
60use crate::runtime;
61use crate::runtime::scheduler::multi_thread::{
62    idle, park, queue, Counters, Handle, Idle, Overflow, Parker, Stats, TraceStatus, Unparker,
63};
64use crate::runtime::scheduler::{inject::InjectQueue, Defer};
65use crate::runtime::task::OwnedTasks;
66use crate::runtime::{
67    blocking, driver, scheduler, task, Config, SchedulerMetrics, TimerFlavor, WorkerMetrics,
68};
69use crate::runtime::{context, TaskHooks};
70use crate::task::coop;
71use crate::util::atomic_cell::AtomicCell;
72use crate::util::cacheline::CachePadded;
73use crate::util::rand::{FastRand, RngSeedGenerator};
74
75use std::cell::RefCell;
76use std::ops::ControlFlow;
77use std::task::Waker;
78use std::thread;
79use std::time::{Duration, Instant};
80
81mod metrics;
82
83cfg_taskdump! {
84    mod taskdump;
85}
86
87cfg_not_taskdump! {
88    mod taskdump_mock;
89}
90
91#[cfg(all(tokio_unstable, feature = "time"))]
92use crate::loom::sync::atomic::AtomicBool;
93
94#[cfg(all(tokio_unstable, feature = "time"))]
95use crate::runtime::time_alt;
96
97use crate::runtime::metrics::ScheduleLatencyInstant;
98#[cfg(all(tokio_unstable, feature = "time"))]
99use crate::runtime::scheduler::util;
100
101/// A scheduler worker
102pub(super) struct Worker {
103    /// Reference to scheduler's handle
104    handle: Arc<Handle>,
105
106    /// Index holding this worker's remote state
107    index: usize,
108
109    /// Used to hand-off a worker's core to another thread.
110    core: AtomicCell<Core>,
111}
112
113/// Core data
114struct Core {
115    /// Used to schedule bookkeeping tasks every so often.
116    tick: u32,
117
118    /// When a task is scheduled from a worker, it is stored in this slot. The
119    /// worker will check this slot for a task **before** checking the run
120    /// queue. This effectively results in the **last** scheduled task to be run
121    /// next (LIFO). This is an optimization for improving locality which
122    /// benefits message passing patterns and helps to reduce latency.
123    lifo_slot: Option<Notified>,
124
125    /// When `true`, locally scheduled tasks go to the LIFO slot. When `false`,
126    /// they go to the back of the `run_queue`.
127    lifo_enabled: bool,
128
129    /// The worker-local run queue.
130    run_queue: queue::Local<Arc<Handle>>,
131
132    #[cfg(all(tokio_unstable, feature = "time"))]
133    time_context: time_alt::LocalContext,
134
135    /// True if the worker is currently searching for more work. Searching
136    /// involves attempting to steal from other workers.
137    is_searching: bool,
138
139    /// True if the scheduler is being shutdown
140    is_shutdown: bool,
141
142    /// True if the scheduler is being traced
143    is_traced: bool,
144
145    /// Whether or not the worker has just returned from a park in which we
146    /// parked on the I/O driver.
147    had_driver: park::HadDriver,
148
149    /// If `true`, the worker should eagerly notify another worker when polling
150    /// the first task after returning from a park in which it parked on the I/O
151    /// or time driver.
152    enable_eager_driver_handoff: bool,
153
154    /// Parker
155    ///
156    /// Stored in an `Option` as the parker is added / removed to make the
157    /// borrow checker happy.
158    park: Option<Parker>,
159
160    /// Per-worker runtime stats
161    stats: Stats,
162
163    /// How often to check the global queue
164    global_queue_interval: u32,
165
166    /// Fast random number generator.
167    rand: FastRand,
168}
169
170/// State shared across all workers
171pub(crate) struct Shared {
172    /// Per-worker remote state. All other workers have access to this and is
173    /// how they communicate between each other.
174    remotes: Box<[Remote]>,
175
176    /// Global task queue used for:
177    ///  1. Submit work to the scheduler while **not** currently on a worker thread.
178    ///  2. Submit work to the scheduler when a worker run queue is saturated
179    pub(super) inject: CachePadded<InjectQueue<Arc<Handle>>>,
180
181    /// Coordinates idle workers
182    idle: CachePadded<Idle>,
183
184    /// Collection of all active tasks spawned onto this executor.
185    pub(crate) owned: OwnedTasks<Arc<Handle>>,
186
187    /// Data synchronized by the scheduler mutex
188    pub(super) synced: Mutex<Synced>,
189
190    /// Cores that have observed the shutdown signal
191    ///
192    /// The core is **not** placed back in the worker to avoid it from being
193    /// stolen by a thread that was spawned as part of `block_in_place`.
194    #[allow(clippy::vec_box)] // we're moving an already-boxed value
195    shutdown_cores: Mutex<Vec<Box<Core>>>,
196
197    /// The number of cores that have observed the trace signal.
198    pub(super) trace_status: TraceStatus,
199
200    /// Scheduler configuration options
201    config: Config,
202
203    /// Collects metrics from the runtime.
204    pub(super) scheduler_metrics: SchedulerMetrics,
205
206    pub(super) worker_metrics: Box<[WorkerMetrics]>,
207
208    /// Startup time of this scheduler.
209    ///
210    /// This instant is used as the basis of task `scheduled_at` measurements.
211    schedule_latency_start: Option<Instant>,
212
213    /// Only held to trigger some code on drop. This is used to get internal
214    /// runtime metrics that can be useful when doing performance
215    /// investigations. This does nothing (empty struct, no drop impl) unless
216    /// the `tokio_internal_mt_counters` `cfg` flag is set.
217    _counters: Counters,
218}
219
220/// Data synchronized by the scheduler mutex
221pub(crate) struct Synced {
222    /// Synchronized state for `Idle`.
223    pub(super) idle: idle::Synced,
224
225    #[cfg(all(tokio_unstable, feature = "time"))]
226    /// Timers pending to be registered.
227    /// This is used to register a timer but the [`Core`]
228    /// is not available in the current thread.
229    ///
230    /// This must stay under the same mutex as `idle`: a parking worker drains
231    /// it (via `try_lock`) only after publishing its parked state under this
232    /// lock, and `notify_if_work_pending` does not check for pending timers,
233    /// so sharing the lock with the parking transition is what prevents a
234    /// timer push from being stranded while every worker sleeps.
235    inject_timers: Vec<time_alt::EntryHandle>,
236}
237
238/// Used to communicate with a worker from other threads.
239struct Remote {
240    /// Steals tasks from this worker.
241    pub(super) steal: queue::Steal<Arc<Handle>>,
242
243    /// Unparks the associated worker thread
244    unpark: Unparker,
245}
246
247/// Thread-local context
248pub(crate) struct Context {
249    /// Worker
250    worker: Arc<Worker>,
251
252    /// Core data
253    core: RefCell<Option<Box<Core>>>,
254
255    /// Tasks to wake after resource drivers are polled. This is mostly to
256    /// handle yielded tasks.
257    pub(crate) defer: Defer,
258}
259
260/// Starts the workers
261pub(crate) struct Launch(Vec<Arc<Worker>>);
262
263/// A notified task handle
264type Notified = task::Notified<Arc<Handle>>;
265
266/// Value picked out of thin-air. Running the LIFO slot a handful of times
267/// seems sufficient to benefit from locality. More than 3 times probably is
268/// over-weighting. The value can be tuned in the future with data that shows
269/// improvements.
270const MAX_LIFO_POLLS_PER_TICK: usize = 3;
271
272#[allow(clippy::too_many_arguments)]
273pub(super) fn create(
274    size: usize,
275    park: Parker,
276    driver_handle: driver::Handle,
277    blocking_spawner: blocking::Spawner,
278    seed_generator: RngSeedGenerator,
279    config: Config,
280    timer_flavor: TimerFlavor,
281    name: Option<String>,
282) -> (Arc<Handle>, Launch) {
283    let mut cores = Vec::with_capacity(size);
284    let mut remotes = Vec::with_capacity(size);
285    let mut worker_metrics = Vec::with_capacity(size);
286
287    // Create the local queues
288    for _ in 0..size {
289        let (steal, run_queue) = queue::local();
290
291        let park = park.clone();
292        let unpark = park.unpark();
293        let metrics = WorkerMetrics::from_config(&config);
294        let stats = Stats::new(&metrics);
295
296        cores.push(Box::new(Core {
297            tick: 0,
298            lifo_slot: None,
299            lifo_enabled: !config.disable_lifo_slot,
300            run_queue,
301            #[cfg(all(tokio_unstable, feature = "time"))]
302            time_context: time_alt::LocalContext::new(),
303            is_searching: false,
304            is_shutdown: false,
305            is_traced: false,
306            enable_eager_driver_handoff: config.enable_eager_driver_handoff,
307            had_driver: park::HadDriver::No,
308            park: Some(park),
309            global_queue_interval: stats.tuned_global_queue_interval(&config),
310            stats,
311            rand: FastRand::from_seed(config.seed_generator.next_seed()),
312        }));
313
314        remotes.push(Remote { steal, unpark });
315        worker_metrics.push(metrics);
316    }
317
318    let (idle, idle_synced) = Idle::new(size);
319    let schedule_latency_start = config.track_task_schedule_latency.then(Instant::now);
320
321    let remotes_len = remotes.len();
322    let handle = Arc::new(Handle {
323        name,
324        task_hooks: TaskHooks::from_config(&config),
325        shared: Shared {
326            remotes: remotes.into_boxed_slice(),
327            inject: CachePadded::new(InjectQueue::new()),
328            idle: CachePadded::new(idle),
329            owned: OwnedTasks::new(size),
330            synced: Mutex::new(Synced {
331                idle: idle_synced,
332                #[cfg(all(tokio_unstable, feature = "time"))]
333                inject_timers: Vec::new(),
334            }),
335            shutdown_cores: Mutex::new(vec![]),
336            trace_status: TraceStatus::new(remotes_len),
337            config,
338            scheduler_metrics: SchedulerMetrics::new(),
339            worker_metrics: worker_metrics.into_boxed_slice(),
340            schedule_latency_start,
341            _counters: Counters,
342        },
343        driver: driver_handle,
344        blocking_spawner,
345        seed_generator,
346        timer_flavor,
347        #[cfg(all(tokio_unstable, feature = "time"))]
348        is_shutdown: AtomicBool::new(false),
349    });
350
351    let mut launch = Launch(vec![]);
352
353    for (index, core) in cores.drain(..).enumerate() {
354        launch.0.push(Arc::new(Worker {
355            handle: handle.clone(),
356            index,
357            core: AtomicCell::new(Some(core)),
358        }));
359    }
360
361    (handle, launch)
362}
363
364#[track_caller]
365pub(crate) fn block_in_place<F, R>(f: F) -> R
366where
367    F: FnOnce() -> R,
368{
369    // Try to steal the worker core back
370    struct Reset {
371        take_core: bool,
372        budget: coop::Budget,
373    }
374
375    impl Drop for Reset {
376        fn drop(&mut self) {
377            with_current(|maybe_cx| {
378                if let Some(cx) = maybe_cx {
379                    if self.take_core {
380                        let core = cx.worker.core.take();
381
382                        if core.is_some() {
383                            cx.worker.handle.shared.worker_metrics[cx.worker.index]
384                                .set_thread_id(thread::current().id());
385                        }
386
387                        let mut cx_core = cx.core.borrow_mut();
388                        assert!(cx_core.is_none());
389                        *cx_core = core;
390                    }
391
392                    // Reset the task budget as we are re-entering the
393                    // runtime.
394                    coop::set(self.budget);
395                }
396            });
397        }
398    }
399
400    // Move the runtime to another thread, if there is one to move.
401    // Do this in a non-generic function that doesn't depend on `F` or `R`.
402    let (had_entered, take_core) = match maybe_move_runtime() {
403        Ok(r) => r,
404        Err(panic_message) => panic!("{}", panic_message),
405    };
406
407    if had_entered {
408        // Unset the current task's budget. Blocking sections are not
409        // constrained by task budgets.
410        let _reset = Reset {
411            take_core,
412            budget: coop::stop(),
413        };
414
415        crate::runtime::context::exit_runtime(f)
416    } else {
417        f()
418    }
419}
420
421fn maybe_move_runtime() -> Result<(bool, bool), &'static str> {
422    let mut had_entered = false;
423    let mut take_core = false;
424
425    with_current(|maybe_cx| {
426        match (
427            crate::runtime::context::current_enter_context(),
428            maybe_cx.is_some(),
429        ) {
430            (context::EnterRuntime::Entered { .. }, true) => {
431                // We are on a thread pool runtime thread, so we just need to
432                // set up blocking.
433                had_entered = true;
434            }
435            (
436                context::EnterRuntime::Entered {
437                    allow_block_in_place,
438                },
439                false,
440            ) => {
441                // We are on an executor, but _not_ on the thread pool.  That is
442                // _only_ okay if we are in a thread pool runtime's block_on
443                // method:
444                if allow_block_in_place {
445                    had_entered = true;
446                    return Ok(());
447                } else {
448                    // This probably means we are on the current_thread runtime or in a
449                    // LocalSet, where it is _not_ okay to block.
450                    return Err(
451                        "can call blocking only when running on the multi-threaded runtime",
452                    );
453                }
454            }
455            (context::EnterRuntime::NotEntered, true) => {
456                // This is a nested call to block_in_place (we already exited).
457                // All the necessary setup has already been done.
458                return Ok(());
459            }
460            (context::EnterRuntime::NotEntered, false) => {
461                // We are outside of the tokio runtime, so blocking is fine.
462                // We can also skip all of the thread pool blocking setup steps.
463                return Ok(());
464            }
465        }
466
467        let cx = maybe_cx.expect("no .is_some() == false cases above should lead here");
468
469        // Since deferred tasks don't stay on `core`, make sure to wake them
470        // before blocking.
471        cx.defer.wake();
472
473        // Get the worker core. If none is set, then blocking is fine!
474        let mut core = match cx.core.borrow_mut().take() {
475            Some(core) => core,
476            None => return Ok(()),
477        };
478
479        // If we heavily call `spawn_blocking`, there might be no available thread to
480        // run this core. Except for the task in the lifo_slot, all tasks can be
481        // stolen, so we move the task out of the lifo_slot to the run_queue.
482        if let Some(task) = core.lifo_slot.take() {
483            core.run_queue
484                .push_back_or_overflow(task, &*cx.worker.handle, &mut core.stats);
485        }
486
487        // We are taking the core from the context and sending it to another
488        // thread.
489        take_core = true;
490
491        // The parker should be set here
492        assert!(core.park.is_some());
493
494        // In order to block, the core must be sent to another thread for
495        // execution.
496        //
497        // First, move the core back into the worker's shared core slot.
498        cx.worker.core.set(core);
499
500        // Next, clone the worker handle and send it to a new thread for
501        // processing.
502        //
503        // Once the blocking task is done executing, we will attempt to
504        // steal the core back.
505        let worker = cx.worker.clone();
506        runtime::spawn_blocking(move || run(worker));
507        Ok(())
508    })?;
509    Ok((had_entered, take_core))
510}
511
512impl Launch {
513    pub(crate) fn launch(mut self) {
514        for worker in self.0.drain(..) {
515            runtime::spawn_blocking(move || run(worker));
516        }
517    }
518}
519
520fn run(worker: Arc<Worker>) {
521    #[allow(dead_code)]
522    struct AbortOnPanic;
523
524    impl Drop for AbortOnPanic {
525        fn drop(&mut self) {
526            if std::thread::panicking() {
527                eprintln!("worker thread panicking; aborting process");
528                std::process::abort();
529            }
530        }
531    }
532
533    // Catching panics on worker threads in tests is quite tricky. Instead, when
534    // debug assertions are enabled, we just abort the process.
535    #[cfg(debug_assertions)]
536    let _abort_on_panic = AbortOnPanic;
537
538    // Acquire a core. If this fails, then another thread is running this
539    // worker and there is nothing further to do.
540    let core = match worker.core.take() {
541        Some(core) => core,
542        None => return,
543    };
544
545    worker.handle.shared.worker_metrics[worker.index].set_thread_id(thread::current().id());
546
547    let handle = scheduler::Handle::MultiThread(worker.handle.clone());
548
549    crate::runtime::context::enter_runtime(&handle, true, |_| {
550        // Set the worker context.
551        let cx = scheduler::Context::MultiThread(Context {
552            worker,
553            core: RefCell::new(None),
554            defer: Defer::new(),
555        });
556
557        context::set_scheduler(&cx, || {
558            let cx = cx.expect_multi_thread();
559
560            cx.run(core);
561
562            // Check if there are any deferred tasks to notify. This can happen when
563            // the worker core is lost due to `block_in_place()` being called from
564            // within the task.
565            cx.defer.wake();
566        });
567    });
568}
569
570impl Context {
571    fn run(&self, mut core: Box<Core>) {
572        // Reset `lifo_enabled` here in case the core was previously stolen from
573        // a task that had the LIFO slot disabled.
574        self.reset_lifo_enabled(&mut core);
575
576        // Start as "processing" tasks as polling tasks from the local queue
577        // will be one of the first things we do.
578        core.stats.start_processing_scheduled_tasks();
579
580        while !core.is_shutdown {
581            self.assert_lifo_enabled_is_correct(&core);
582
583            if core.is_traced {
584                core = self.worker.handle.trace_core(core);
585            }
586
587            // Increment the tick
588            core.tick();
589
590            // Run maintenance, if needed
591            core = self.maintenance(core);
592
593            // First, check work available to the current worker.
594            if let Some(task) = core.next_task(&self.worker) {
595                core = match self.run_task(task, core) {
596                    ControlFlow::Continue(core) => core,
597                    ControlFlow::Break(()) => return,
598                };
599                continue;
600            }
601
602            // We consumed all work in the queues and will start searching for work.
603            core.stats.end_processing_scheduled_tasks();
604
605            // There is no more **local** work to process, try to steal work
606            // from other workers.
607            if let Some(task) = core.steal_work(&self.worker) {
608                // Found work, switch back to processing
609                core.stats.start_processing_scheduled_tasks();
610                core = match self.run_task(task, core) {
611                    ControlFlow::Continue(core) => core,
612                    ControlFlow::Break(()) => return,
613                };
614            } else {
615                // Wait for work
616                core = if !self.defer.is_empty() {
617                    self.park_yield(core)
618                } else {
619                    self.park(core)
620                };
621                core.stats.start_processing_scheduled_tasks();
622            }
623        }
624
625        #[cfg(all(tokio_unstable, feature = "time"))]
626        {
627            match self.worker.handle.timer_flavor {
628                TimerFlavor::Traditional => {}
629                TimerFlavor::Alternative => {
630                    util::time_alt::shutdown_local_timers(
631                        &mut core.time_context.wheel,
632                        &mut core.time_context.canc_rx,
633                        self.worker.handle.take_remote_timers(),
634                        &self.worker.handle.driver,
635                    );
636                }
637            }
638        }
639
640        core.pre_shutdown(&self.worker);
641        // Signal shutdown
642        self.worker.handle.shutdown_core(core);
643    }
644
645    /// Running a task may consume the core. If the core is still available when
646    /// running the task completes, it is returned. Otherwise, the worker will need
647    /// to stop processing.
648    fn run_task(&self, task: Notified, mut core: Box<Core>) -> ControlFlow<(), Box<Core>> {
649        let task = self.worker.handle.shared.owned.assert_owner(task);
650
651        // Make sure the worker is not in the **searching** state. This enables
652        // another idle worker to try to steal work.
653        let notified_parked_worker = core.transition_from_searching(&self.worker);
654
655        // If the setting to wake eagerly when releasing the I/O driver is
656        // enabled, and this worker had the driver, wake a parked worker to come
657        // grab it from us.
658        //
659        // Note that this is only done when we are *actually* about to poll a
660        // task, rather than whenever the worker has unparked. When the worker
661        // has been unparked, it may not actually have any tasks to poll, and if
662        // it's still holding the I/O driver, it should just go back to polling
663        // the driver again, rather than trying to wake someone else spuriously.
664        //
665        // Note that this explicitly checks `cfg!(tokio_unstable)` in addition,
666        // as that should result in this whole expression being eliminated at
667        // compile-time when unstable features are disabled.
668        if cfg!(tokio_unstable)
669            && core.enable_eager_driver_handoff
670            && core.had_driver == park::HadDriver::Yes
671            && !notified_parked_worker
672        // don't do it a second time
673        {
674            core.had_driver = park::HadDriver::No;
675            self.worker.handle.notify_parked_local();
676        }
677
678        self.assert_lifo_enabled_is_correct(&core);
679
680        // Measure the poll start time. Note that we may end up polling other
681        // tasks under this poll-time measurement. Tasks from the LIFO slot
682        // inherit the "parent"'s limits, but their schedule latency is recorded
683        // separately when each task is polled.
684        let schedule_latency_context = task
685            .get_scheduled_at()
686            .prepare(self.worker.handle.shared.schedule_latency_start);
687        let _task_schedule_latency = core.stats.start_poll(schedule_latency_context);
688
689        #[cfg(tokio_unstable)]
690        let task_meta = task.task_meta(_task_schedule_latency);
691
692        // Make the core available to the runtime context
693        *self.core.borrow_mut() = Some(core);
694
695        // Run the task
696        coop::budget(|| {
697            // Unlike the poll time above, poll start callback is attached to the task id,
698            // so it is tightly associated with the actual poll invocation.
699            #[cfg(tokio_unstable)]
700            self.worker
701                .handle
702                .task_hooks
703                .poll_start_callback(&task_meta);
704
705            task.run();
706
707            #[cfg(tokio_unstable)]
708            self.worker.handle.task_hooks.poll_stop_callback(&task_meta);
709
710            let mut lifo_polls = 0;
711
712            // As long as there is budget remaining and a task exists in the
713            // `lifo_slot`, then keep running.
714            loop {
715                // Check if we still have the core. If not, the core was stolen
716                // by another worker.
717                let mut core = match self.core.borrow_mut().take() {
718                    Some(core) => core,
719                    None => {
720                        // In this case, we cannot call `reset_lifo_enabled()`
721                        // because the core was stolen. The stealer will handle
722                        // that at the top of `Context::run`
723                        return ControlFlow::Break(());
724                    }
725                };
726
727                // Check for a task in the LIFO slot
728                let task = match core.lifo_slot.take() {
729                    Some(task) => task,
730                    None => {
731                        self.reset_lifo_enabled(&mut core);
732                        core.stats.end_poll();
733                        return ControlFlow::Continue(core);
734                    }
735                };
736
737                if !coop::has_budget_remaining() {
738                    core.stats.end_poll();
739
740                    // Not enough budget left to run the LIFO task, push it to
741                    // the back of the queue and return.
742                    core.run_queue.push_back_or_overflow(
743                        task,
744                        &*self.worker.handle,
745                        &mut core.stats,
746                    );
747                    // If we hit this point, the LIFO slot should be enabled.
748                    // There is no need to reset it.
749                    debug_assert!(core.lifo_enabled);
750                    return ControlFlow::Continue(core);
751                }
752
753                // Track that we are about to run a task from the LIFO slot.
754                lifo_polls += 1;
755                super::counters::inc_lifo_schedules();
756
757                // Disable the LIFO slot if we reach our limit
758                //
759                // In ping-ping style workloads where task A notifies task B,
760                // which notifies task A again, continuously prioritizing the
761                // LIFO slot can cause starvation as these two tasks will
762                // repeatedly schedule the other. To mitigate this, we limit the
763                // number of times the LIFO slot is prioritized.
764                if lifo_polls >= MAX_LIFO_POLLS_PER_TICK {
765                    core.lifo_enabled = false;
766                    super::counters::inc_lifo_capped();
767                }
768
769                let task = self.worker.handle.shared.owned.assert_owner(task);
770
771                // Record the LIFO task's schedule latency independently from
772                // the outer task's poll-time sample. The returned value is the
773                // same sample that is passed to the histogram recorder.
774                let schedule_latency_context = task
775                    .get_scheduled_at()
776                    .prepare(self.worker.handle.shared.schedule_latency_start);
777                let _task_schedule_latency =
778                    core.stats.record_schedule_latency(schedule_latency_context);
779
780                *self.core.borrow_mut() = Some(core);
781
782                #[cfg(tokio_unstable)]
783                let task_meta = task.task_meta(_task_schedule_latency);
784
785                #[cfg(tokio_unstable)]
786                self.worker
787                    .handle
788                    .task_hooks
789                    .poll_start_callback(&task_meta);
790
791                task.run();
792
793                #[cfg(tokio_unstable)]
794                self.worker.handle.task_hooks.poll_stop_callback(&task_meta);
795            }
796        })
797    }
798
799    fn reset_lifo_enabled(&self, core: &mut Core) {
800        core.lifo_enabled = !self.worker.handle.shared.config.disable_lifo_slot;
801    }
802
803    fn assert_lifo_enabled_is_correct(&self, core: &Core) {
804        debug_assert_eq!(
805            core.lifo_enabled,
806            !self.worker.handle.shared.config.disable_lifo_slot
807        );
808    }
809
810    fn maintenance(&self, mut core: Box<Core>) -> Box<Core> {
811        if core.tick % self.worker.handle.shared.config.event_interval == 0 {
812            super::counters::inc_num_maintenance();
813
814            core.stats.end_processing_scheduled_tasks();
815
816            // Call `park` with a 0 timeout. This enables the I/O driver, timer, ...
817            // to run without actually putting the thread to sleep.
818            core = self.park_yield(core);
819
820            // Run regularly scheduled maintenance
821            core.maintenance(&self.worker);
822
823            core.stats.start_processing_scheduled_tasks();
824        }
825
826        core
827    }
828
829    /// Parks the worker thread while waiting for tasks to execute.
830    ///
831    /// This function checks if indeed there's no more work left to be done before parking.
832    /// Also important to notice that, before parking, the worker thread will try to take
833    /// ownership of the Driver (IO/Time) and dispatch any events that might have fired.
834    /// Whenever a worker thread executes the Driver loop, all waken tasks are scheduled
835    /// in its own local queue until the queue saturates (ntasks > `LOCAL_QUEUE_CAPACITY`).
836    /// When the local queue is saturated, the overflow tasks are added to the injection queue
837    /// from where other workers can pick them up.
838    /// Also, we rely on the workstealing algorithm to spread the tasks amongst workers
839    /// after all the IOs get dispatched
840    fn park(&self, mut core: Box<Core>) -> Box<Core> {
841        if let Some(f) = &self.worker.handle.shared.config.before_park {
842            f();
843        }
844
845        if core.transition_to_parked(&self.worker) {
846            while !core.is_shutdown && !core.is_traced {
847                core.stats.about_to_park();
848                core.stats
849                    .submit(&self.worker.handle.shared.worker_metrics[self.worker.index]);
850
851                core = self.park_internal(core, None);
852
853                core.stats.unparked();
854
855                // Run regularly scheduled maintenance
856                core.maintenance(&self.worker);
857
858                if core.transition_from_parked(&self.worker) {
859                    break;
860                }
861            }
862        }
863
864        if let Some(f) = &self.worker.handle.shared.config.after_unpark {
865            f();
866        }
867        core
868    }
869
870    fn park_yield(&self, core: Box<Core>) -> Box<Core> {
871        self.park_internal(core, Some(Duration::from_millis(0)))
872    }
873
874    fn park_internal(&self, mut core: Box<Core>, duration: Option<Duration>) -> Box<Core> {
875        self.assert_lifo_enabled_is_correct(&core);
876
877        // Take the parker out of core
878        let mut park = core.park.take().expect("park missing");
879        // Store `core` in context
880        *self.core.borrow_mut() = Some(core);
881
882        #[cfg(feature = "time")]
883        let (duration, auto_advance_duration) = match self.worker.handle.timer_flavor {
884            TimerFlavor::Traditional => (duration, None::<Duration>),
885            #[cfg(tokio_unstable)]
886            TimerFlavor::Alternative => {
887                // Must happens after taking out the parker, as the `Handle::schedule_local`
888                // will delay the notify if the parker taken out.
889                //
890                // See comments in `Handle::schedule_local` for more details.
891                let MaintainLocalTimer {
892                    park_duration: duration,
893                    auto_advance_duration,
894                } = self.maintain_local_timers_before_parking(duration);
895                (duration, auto_advance_duration)
896            }
897        };
898
899        // Park thread
900        let had_driver = if let Some(timeout) = duration {
901            park.park_timeout(&self.worker.handle.driver, timeout)
902        } else {
903            park.park(&self.worker.handle.driver)
904        };
905
906        self.defer.wake();
907
908        #[cfg(feature = "time")]
909        match self.worker.handle.timer_flavor {
910            TimerFlavor::Traditional => {
911                // suppress unused variable warning
912                let _ = auto_advance_duration;
913            }
914            #[cfg(tokio_unstable)]
915            TimerFlavor::Alternative => {
916                // Must happens before placing back the parker, as the `Handle::schedule_local`
917                // will delay the notify if the parker is still in `core`.
918                //
919                // See comments in `Handle::schedule_local` for more details.
920                self.maintain_local_timers_after_parking(auto_advance_duration);
921            }
922        }
923
924        // Remove `core` from context
925        core = self.core.borrow_mut().take().expect("core missing");
926
927        // Place `park` back in `core`
928        core.park = Some(park);
929        core.had_driver = had_driver;
930
931        if core.should_notify_others() {
932            self.worker.handle.notify_parked_local();
933        }
934        core
935    }
936
937    pub(crate) fn defer(&self, waker: &Waker) {
938        if self.core.borrow().is_none() {
939            // If there is no core, then the worker is currently in a block_in_place. In this case,
940            // we cannot use the defer queue as we aren't really in the current runtime.
941            waker.wake_by_ref();
942        } else {
943            self.defer.defer(waker);
944        }
945    }
946
947    #[cfg(all(tokio_unstable, feature = "time"))]
948    /// Maintain local timers before parking the resource driver.
949    ///
950    /// * Remove cancelled timers from the local timer wheel.
951    /// * Register remote timers to the local timer wheel.
952    /// * Adjust the park duration based on
953    ///   * the next timer expiration time.
954    ///   * whether auto-advancing is required (feature = "test-util").
955    ///
956    /// # Returns
957    ///
958    /// `(Box<Core>, park_duration, auto_advance_duration)`
959    fn maintain_local_timers_before_parking(
960        &self,
961        park_duration: Option<Duration>,
962    ) -> MaintainLocalTimer {
963        let handle = &self.worker.handle;
964        let mut wake_queue = time_alt::WakeQueue::new();
965
966        let (should_yield, next_timer) = with_current(|maybe_cx| {
967            let cx = maybe_cx.expect("function should be called when core is present");
968            assert_eq!(
969                Arc::as_ptr(&cx.worker.handle),
970                Arc::as_ptr(&self.worker.handle),
971                "function should be called on the exact same worker"
972            );
973
974            let mut maybe_core = cx.core.borrow_mut();
975            let core = maybe_core.as_mut().expect("core missing");
976            let time_cx = &mut core.time_context;
977
978            util::time_alt::process_registration_queue(
979                &mut time_cx.registration_queue,
980                &mut time_cx.wheel,
981                &time_cx.canc_tx,
982                &mut wake_queue,
983            );
984            util::time_alt::insert_inject_timers(
985                &mut time_cx.wheel,
986                &time_cx.canc_tx,
987                handle.take_remote_timers(),
988                &mut wake_queue,
989            );
990            util::time_alt::remove_cancelled_timers(&mut time_cx.wheel, &mut time_cx.canc_rx);
991            let should_yield = !wake_queue.is_empty();
992
993            let next_timer = util::time_alt::next_expiration_time(&time_cx.wheel, &handle.driver);
994
995            (should_yield, next_timer)
996        });
997
998        wake_queue.wake_all();
999
1000        if should_yield {
1001            MaintainLocalTimer {
1002                park_duration: Some(Duration::from_millis(0)),
1003                auto_advance_duration: None,
1004            }
1005        } else {
1006            // get the minimum duration
1007            let dur = util::time_alt::min_duration(park_duration, next_timer);
1008            if util::time_alt::pre_auto_advance(&handle.driver, dur) {
1009                MaintainLocalTimer {
1010                    park_duration: Some(Duration::ZERO),
1011                    auto_advance_duration: dur,
1012                }
1013            } else {
1014                MaintainLocalTimer {
1015                    park_duration: dur,
1016                    auto_advance_duration: None,
1017                }
1018            }
1019        }
1020    }
1021
1022    #[cfg(all(tokio_unstable, feature = "time"))]
1023    /// Maintain local timers after unparking the resource driver.
1024    ///
1025    /// * Auto-advance time, if required (feature = "test-util").
1026    /// * Process expired timers.
1027    fn maintain_local_timers_after_parking(&self, auto_advance_duration: Option<Duration>) {
1028        let handle = &self.worker.handle;
1029        let mut wake_queue = time_alt::WakeQueue::new();
1030
1031        with_current(|maybe_cx| {
1032            let cx = maybe_cx.expect("function should be called when core is present");
1033            assert_eq!(
1034                Arc::as_ptr(&cx.worker.handle),
1035                Arc::as_ptr(&self.worker.handle),
1036                "function should be called on the exact same worker"
1037            );
1038
1039            let mut maybe_core = cx.core.borrow_mut();
1040            let core = maybe_core.as_mut().expect("core missing");
1041            let time_cx = &mut core.time_context;
1042
1043            util::time_alt::post_auto_advance(&handle.driver, auto_advance_duration);
1044            util::time_alt::process_expired_timers(
1045                &mut time_cx.wheel,
1046                &handle.driver,
1047                &mut wake_queue,
1048            );
1049        });
1050
1051        wake_queue.wake_all();
1052    }
1053
1054    #[cfg(all(tokio_unstable, feature = "time"))]
1055    fn with_core<F, R>(&self, f: F) -> R
1056    where
1057        F: FnOnce(Option<&mut Core>) -> R,
1058    {
1059        match self.core.borrow_mut().as_mut() {
1060            Some(core) => f(Some(core)),
1061            None => f(None),
1062        }
1063    }
1064
1065    #[cfg(all(tokio_unstable, feature = "time"))]
1066    pub(crate) fn with_time_temp_local_context<F, R>(&self, f: F) -> R
1067    where
1068        F: FnOnce(Option<time_alt::TempLocalContext<'_>>) -> R,
1069    {
1070        self.with_core(|maybe_core| match maybe_core {
1071            Some(core) if core.is_shutdown => f(Some(time_alt::TempLocalContext::new_shutdown())),
1072            Some(core) => f(Some(time_alt::TempLocalContext::new_running(
1073                &mut core.time_context,
1074            ))),
1075            None => f(None),
1076        })
1077    }
1078
1079    pub(crate) fn worker_index(&self) -> usize {
1080        self.worker.index
1081    }
1082}
1083
1084impl Core {
1085    /// Increment the tick
1086    fn tick(&mut self) {
1087        self.tick = self.tick.wrapping_add(1);
1088    }
1089
1090    /// Return the next notified task available to this worker.
1091    fn next_task(&mut self, worker: &Worker) -> Option<Notified> {
1092        if self.tick % self.global_queue_interval == 0 {
1093            // Update the global queue interval, if needed
1094            self.tune_global_queue_interval(worker);
1095
1096            worker
1097                .handle
1098                .next_remote_task()
1099                .or_else(|| self.next_local_task())
1100        } else {
1101            let maybe_task = self.next_local_task();
1102
1103            if maybe_task.is_some() {
1104                return maybe_task;
1105            }
1106
1107            if worker.inject().is_empty() {
1108                return None;
1109            }
1110
1111            let cap = usize::min(
1112                // Other threads can only **remove** tasks from the current
1113                // worker's `run_queue`. So, we can be confident that by the
1114                // time we call `run_queue.push_back` below, there will be *at
1115                // least* `cap` available slots in the queue.
1116                //
1117                // Note that even though `next_local_task()` just returned
1118                // `None`, this may be different from `max_capacity()` if
1119                // another worker is currently stealing tasks from us.
1120                self.run_queue.remaining_slots(),
1121                // We want to make sure that all of the tasks we take end up in
1122                // the first half of the local queue. This ensures that the
1123                // tasks do not get pushed to the inject queue again if overflow
1124                // occurs, as overflow only affects tasks in the second half of
1125                // the local queue.
1126                //
1127                // Note that even if there are concurrent stealers, we do not
1128                // need to consider the value of `remaining_slots()` because a
1129                // future call to `push_overflow()` can only succeed once that
1130                // concurrent stealer has finished stealing, so at that point
1131                // the tasks we are adding now will be in the first half.
1132                self.run_queue.max_capacity() / 2,
1133            );
1134
1135            // The worker is currently idle, pull a batch of work from the
1136            // injection queue. We don't want to pull *all* the work so other
1137            // workers can also get some.
1138            let n = usize::min(
1139                worker.inject().len() / worker.handle.shared.remotes.len() + 1,
1140                cap,
1141            );
1142
1143            // Take at least one task since the first task is returned directly
1144            // and not pushed onto the local queue.
1145            let n = usize::max(1, n);
1146
1147            worker.inject().pop_n(n, |mut tasks| {
1148                // Pop the first task to return immediately
1149                let ret = tasks.next();
1150
1151                // Push the rest of the on the run queue
1152                self.run_queue.push_back(tasks);
1153
1154                ret
1155            })
1156        }
1157    }
1158
1159    fn next_local_task(&mut self) -> Option<Notified> {
1160        self.lifo_slot.take().or_else(|| self.run_queue.pop())
1161    }
1162
1163    /// Function responsible for stealing tasks from another worker
1164    ///
1165    /// Note: Only if less than half the workers are searching for tasks to steal
1166    /// a new worker will actually try to steal. The idea is to make sure not all
1167    /// workers will be trying to steal at the same time.
1168    fn steal_work(&mut self, worker: &Worker) -> Option<Notified> {
1169        if !self.transition_to_searching(worker) {
1170            return None;
1171        }
1172
1173        let num = worker.handle.shared.remotes.len();
1174        // Start from a random worker
1175        let start = self.rand.fastrand_n(num as u32) as usize;
1176
1177        for i in 0..num {
1178            let i = (start + i) % num;
1179
1180            // Don't steal from ourself! We know we don't have work.
1181            if i == worker.index {
1182                continue;
1183            }
1184
1185            let target = &worker.handle.shared.remotes[i];
1186            if let Some(task) = target
1187                .steal
1188                .steal_into(&mut self.run_queue, &mut self.stats)
1189            {
1190                return Some(task);
1191            }
1192        }
1193
1194        // Fallback on checking the global queue
1195        worker.handle.next_remote_task()
1196    }
1197
1198    fn transition_to_searching(&mut self, worker: &Worker) -> bool {
1199        if !self.is_searching {
1200            self.is_searching = worker.handle.shared.idle.transition_worker_to_searching();
1201        }
1202
1203        self.is_searching
1204    }
1205
1206    fn transition_from_searching(&mut self, worker: &Worker) -> bool {
1207        if !self.is_searching {
1208            return false;
1209        }
1210
1211        self.is_searching = false;
1212        worker.handle.transition_worker_from_searching()
1213    }
1214
1215    fn has_tasks(&self) -> bool {
1216        self.lifo_slot.is_some() || self.run_queue.has_tasks()
1217    }
1218
1219    fn should_notify_others(&self) -> bool {
1220        // If there are tasks available to steal, but this worker is not
1221        // looking for tasks to steal, notify another worker.
1222        if self.is_searching {
1223            return false;
1224        }
1225        self.lifo_slot.is_some() as usize + self.run_queue.len() > 1
1226    }
1227
1228    /// Prepares the worker state for parking.
1229    ///
1230    /// Returns true if the transition happened, false if there is work to do first.
1231    fn transition_to_parked(&mut self, worker: &Worker) -> bool {
1232        // Workers should not park if they have work to do or are about to be traced
1233        if self.has_tasks() || self.is_traced {
1234            return false;
1235        }
1236
1237        // When the final worker transitions **out** of searching to parked, it
1238        // must check all the queues one last time in case work materialized
1239        // between the last work scan and transitioning out of searching.
1240        let is_last_searcher = worker.handle.shared.idle.transition_worker_to_parked(
1241            &worker.handle.shared,
1242            worker.index,
1243            self.is_searching,
1244        );
1245
1246        // The worker is no longer searching. Setting this is the local cache
1247        // only.
1248        self.is_searching = false;
1249
1250        if is_last_searcher {
1251            worker.handle.notify_if_work_pending();
1252        }
1253
1254        true
1255    }
1256
1257    /// Returns `true` if the transition happened.
1258    fn transition_from_parked(&mut self, worker: &Worker) -> bool {
1259        // If a task is in the lifo slot/run queue, then we must unpark regardless of
1260        // being notified. Same when woken to be traced: a dump unparks worker
1261        // threads without going through `Idle`, so the worker does it here.
1262        if self.has_tasks() || self.is_traced {
1263            // When a worker wakes, it should only transition to the "searching"
1264            // state when the wake originates from another worker *or* a new task
1265            // is pushed. We do *not* want the worker to transition to "searching"
1266            // when it wakes when the I/O driver receives new events.
1267            self.is_searching = !worker
1268                .handle
1269                .shared
1270                .idle
1271                .unpark_worker_by_id(&worker.handle.shared, worker.index);
1272            return true;
1273        }
1274
1275        if worker
1276            .handle
1277            .shared
1278            .idle
1279            .is_parked(&worker.handle.shared, worker.index)
1280        {
1281            return false;
1282        }
1283
1284        // When unparked, the worker is in the searching state.
1285        self.is_searching = true;
1286        true
1287    }
1288
1289    /// Runs maintenance work such as checking the pool's state.
1290    fn maintenance(&mut self, worker: &Worker) {
1291        self.stats
1292            .submit(&worker.handle.shared.worker_metrics[worker.index]);
1293
1294        if !self.is_shutdown {
1295            // Check if the scheduler has been shutdown
1296            self.is_shutdown = worker.inject().is_closed();
1297        }
1298
1299        if !self.is_traced {
1300            // Check if the worker should be tracing.
1301            self.is_traced = worker.handle.shared.trace_status.trace_requested();
1302        }
1303    }
1304
1305    /// Signals all tasks to shut down, and waits for them to complete. Must run
1306    /// before we enter the single-threaded phase of shutdown processing.
1307    fn pre_shutdown(&mut self, worker: &Worker) {
1308        // Start from a random inner list
1309        let start = self
1310            .rand
1311            .fastrand_n(worker.handle.shared.owned.get_shard_size() as u32);
1312        // Signal to all tasks to shut down.
1313        worker
1314            .handle
1315            .shared
1316            .owned
1317            .close_and_shutdown_all(start as usize);
1318
1319        self.stats
1320            .submit(&worker.handle.shared.worker_metrics[worker.index]);
1321    }
1322
1323    /// Shuts down the core.
1324    fn shutdown(&mut self, handle: &Handle) {
1325        // Take the core
1326        let mut park = self.park.take().expect("park missing");
1327
1328        // Drain the queue
1329        while self.next_local_task().is_some() {}
1330
1331        park.shutdown(&handle.driver);
1332    }
1333
1334    fn tune_global_queue_interval(&mut self, worker: &Worker) {
1335        let next = self
1336            .stats
1337            .tuned_global_queue_interval(&worker.handle.shared.config);
1338
1339        // Smooth out jitter
1340        if u32::abs_diff(self.global_queue_interval, next) > 2 {
1341            self.global_queue_interval = next;
1342        }
1343    }
1344}
1345
1346impl Worker {
1347    /// Returns a reference to the scheduler's injection queue.
1348    fn inject(&self) -> &InjectQueue<Arc<Handle>> {
1349        &self.handle.shared.inject
1350    }
1351}
1352
1353impl Handle {
1354    pub(super) fn schedule_task(&self, task: Notified, is_yield: bool) {
1355        if self.shared.schedule_latency_start.is_some() {
1356            task.set_scheduled_at(ScheduleLatencyInstant::new(
1357                self.shared.schedule_latency_start,
1358            ));
1359        }
1360
1361        with_current(|maybe_cx| {
1362            if let Some(cx) = maybe_cx {
1363                // Make sure the task is part of the **current** scheduler.
1364                if self.ptr_eq(&cx.worker.handle) {
1365                    // And the current thread still holds a core
1366                    if let Some(core) = cx.core.borrow_mut().as_mut() {
1367                        self.schedule_local(core, task, is_yield);
1368                        return;
1369                    }
1370                }
1371            }
1372
1373            // Otherwise, use the inject queue.
1374            self.push_remote_task(task);
1375            self.notify_parked_remote();
1376        });
1377    }
1378
1379    // Separated case to reduce LLVM codegen in `Handle::bind_new_task`.
1380    pub(super) fn schedule_option_task_without_yield(&self, task: Option<Notified>) {
1381        if let Some(task) = task {
1382            self.schedule_task(task, false);
1383        }
1384    }
1385
1386    fn schedule_local(&self, core: &mut Core, task: Notified, is_yield: bool) {
1387        core.stats.inc_local_schedule_count();
1388
1389        // Spawning from the worker thread. If scheduling a "yield" then the
1390        // task must always be pushed to the back of the queue, enabling other
1391        // tasks to be executed. If **not** a yield, then there is more
1392        // flexibility and the task may go to the front of the queue.
1393        let should_notify = if is_yield || !core.lifo_enabled {
1394            core.run_queue
1395                .push_back_or_overflow(task, self, &mut core.stats);
1396            true
1397        } else {
1398            // Push to the LIFO slot
1399            let prev = core.lifo_slot.take();
1400            let ret = prev.is_some();
1401
1402            if let Some(prev) = prev {
1403                core.run_queue
1404                    .push_back_or_overflow(prev, self, &mut core.stats);
1405            }
1406
1407            core.lifo_slot = Some(task);
1408
1409            ret
1410        };
1411
1412        // Only notify if not currently parked. If `park` is `None`, then the
1413        // scheduling is from a resource driver. As notifications often come in
1414        // batches, the notification is delayed until the park is complete.
1415        if should_notify && core.park.is_some() {
1416            self.notify_parked_local();
1417        }
1418    }
1419
1420    fn next_remote_task(&self) -> Option<Notified> {
1421        self.shared.inject.pop()
1422    }
1423
1424    fn push_remote_task(&self, task: Notified) {
1425        self.shared.scheduler_metrics.inc_remote_schedule_count();
1426
1427        self.shared.inject.push(task);
1428    }
1429
1430    #[cfg(all(tokio_unstable, feature = "time"))]
1431    pub(crate) fn push_remote_timer(&self, hdl: time_alt::EntryHandle) {
1432        assert_eq!(self.timer_flavor, TimerFlavor::Alternative);
1433        {
1434            let mut synced = self.shared.synced.lock();
1435            synced.inject_timers.push(hdl);
1436        }
1437        self.notify_parked_remote();
1438    }
1439
1440    #[cfg(all(tokio_unstable, feature = "time"))]
1441    pub(crate) fn take_remote_timers(&self) -> Vec<time_alt::EntryHandle> {
1442        assert_eq!(self.timer_flavor, TimerFlavor::Alternative);
1443        // It's ok to lost the race, as another worker is
1444        // draining the inject_timers.
1445        match self.shared.synced.try_lock() {
1446            Some(mut synced) => std::mem::take(&mut synced.inject_timers),
1447            None => Vec::new(),
1448        }
1449    }
1450
1451    pub(super) fn close(&self) {
1452        if self.shared.inject.close() {
1453            self.notify_all();
1454        }
1455    }
1456
1457    /// Notify a parked worker.
1458    ///
1459    /// Returns `true` if a worker was notified, `false` otherwise.
1460    fn notify_parked_local(&self) -> bool {
1461        super::counters::inc_num_inc_notify_local();
1462
1463        if let Some(index) = self.shared.idle.worker_to_notify(&self.shared) {
1464            super::counters::inc_num_unparks_local();
1465            self.shared.remotes[index].unpark.unpark(&self.driver);
1466            true
1467        } else {
1468            false
1469        }
1470    }
1471
1472    fn notify_parked_remote(&self) {
1473        if let Some(index) = self.shared.idle.worker_to_notify(&self.shared) {
1474            self.shared.remotes[index].unpark.unpark(&self.driver);
1475        }
1476    }
1477
1478    pub(super) fn notify_all(&self) {
1479        for remote in &self.shared.remotes[..] {
1480            remote.unpark.unpark(&self.driver);
1481        }
1482    }
1483
1484    fn notify_if_work_pending(&self) {
1485        for remote in &self.shared.remotes[..] {
1486            if !remote.steal.is_empty() {
1487                self.notify_parked_local();
1488                return;
1489            }
1490        }
1491
1492        if !self.shared.inject.is_empty() {
1493            self.notify_parked_local();
1494        }
1495    }
1496
1497    /// Returns `true` if another parked worker was notified, `false` otherwise.
1498    fn transition_worker_from_searching(&self) -> bool {
1499        if self.shared.idle.transition_worker_from_searching() {
1500            // We are the final searching worker. Because work was found, we
1501            // need to notify another worker.
1502            self.notify_parked_local()
1503        } else {
1504            false
1505        }
1506    }
1507
1508    /// Signals that a worker has observed the shutdown signal and has replaced
1509    /// its core back into its handle.
1510    ///
1511    /// If all workers have reached this point, the final cleanup is performed.
1512    fn shutdown_core(&self, core: Box<Core>) {
1513        let mut cores = self.shared.shutdown_cores.lock();
1514        cores.push(core);
1515
1516        if cores.len() != self.shared.remotes.len() {
1517            return;
1518        }
1519
1520        debug_assert!(self.shared.owned.is_empty());
1521
1522        for mut core in cores.drain(..) {
1523            core.shutdown(self);
1524        }
1525
1526        // Drain the injection queue
1527        //
1528        // We already shut down every task, so we can simply drop the tasks.
1529        while let Some(task) = self.next_remote_task() {
1530            drop(task);
1531        }
1532    }
1533
1534    fn ptr_eq(&self, other: &Handle) -> bool {
1535        std::ptr::eq(self, other)
1536    }
1537}
1538
1539impl Overflow<Arc<Handle>> for Handle {
1540    fn push(&self, task: task::Notified<Arc<Handle>>) {
1541        self.push_remote_task(task);
1542    }
1543
1544    fn push_batch<I>(&self, iter: I)
1545    where
1546        I: Iterator<Item = task::Notified<Arc<Handle>>>,
1547    {
1548        self.shared.inject.push_batch(iter);
1549    }
1550}
1551
1552#[cfg(all(tokio_unstable, feature = "time"))]
1553/// Returned by [`Context::maintain_local_timers_before_parking`].
1554struct MaintainLocalTimer {
1555    park_duration: Option<Duration>,
1556    auto_advance_duration: Option<Duration>,
1557}
1558
1559#[track_caller]
1560fn with_current<R>(f: impl FnOnce(Option<&Context>) -> R) -> R {
1561    use scheduler::Context::MultiThread;
1562
1563    context::with_scheduler(|ctx| match ctx {
1564        Some(MultiThread(ctx)) => f(Some(ctx)),
1565        _ => f(None),
1566    })
1567}