Debian Codegraph @

third_party/rust/tokio/src/runtime/scheduler/current_thread/mod.rs

raw
1 use crate::future::poll_fn;
2 use crate::loom::sync::atomic::AtomicBool;
3 use crate::loom::sync::Arc;
4 use crate::runtime::driver::{self, Driver};
5 use crate::runtime::scheduler::{self, Defer, Inject};
6 use crate::runtime::task::{self, JoinHandle, OwnedTasks, Schedule, Task};
7 use crate::runtime::{blocking, context, Config, MetricsBatch, SchedulerMetrics, WorkerMetrics};
8 use crate::sync::notify::Notify;
9 use crate::util::atomic_cell::AtomicCell;
10 use crate::util::{waker_ref, RngSeedGenerator, Wake, WakerRef};
11
12 use std::cell::RefCell;
13 use std::collections::VecDeque;
14 use std::future::Future;
15 use std::sync::atomic::Ordering::{AcqRel, Release};
16 use std::task::Poll::{Pending, Ready};
17 use std::task::Waker;
18 use std::time::Duration;
19 use std::{fmt, thread};
20
21 /// Executes tasks on the current thread
22 pub(crate) struct CurrentThread {
23 /// Core scheduler data is acquired by a thread entering `block_on`.
24 core: AtomicCell<Core>,
25
26 /// Notifier for waking up other threads to steal the
27 /// driver.
28 notify: Notify,
29 }
30
31 /// Handle to the current thread scheduler
32 pub(crate) struct Handle {
33 /// Scheduler state shared across threads
34 shared: Shared,
35
36 /// Resource driver handles
37 pub(crate) driver: driver::Handle,
38
39 /// Blocking pool spawner
40 pub(crate) blocking_spawner: blocking::Spawner,
41
42 /// Current random number generator seed
43 pub(crate) seed_generator: RngSeedGenerator,
44 }
45
46 /// Data required for executing the scheduler. The struct is passed around to
47 /// a function that will perform the scheduling work and acts as a capability token.
48 struct Core {
49 /// Scheduler run queue
50 tasks: VecDeque<Notified>,
51
52 /// Current tick
53 tick: u32,
54
55 /// Runtime driver
56 ///
57 /// The driver is removed before starting to park the thread
58 driver: Option<Driver>,
59
60 /// Metrics batch
61 metrics: MetricsBatch,
62
63 /// How often to check the global queue
64 global_queue_interval: u32,
65
66 /// True if a task panicked without being handled and the runtime is
67 /// configured to shutdown on unhandled panic.
68 unhandled_panic: bool,
69 }
70
71 /// Scheduler state shared between threads.
72 struct Shared {
73 /// Remote run queue
74 inject: Inject<Arc<Handle>>,
75
76 /// Collection of all active tasks spawned onto this executor.
77 owned: OwnedTasks<Arc<Handle>>,
78
79 /// Indicates whether the blocked on thread was woken.
80 woken: AtomicBool,
81
82 /// Scheduler configuration options
83 config: Config,
84
85 /// Keeps track of various runtime metrics.
86 scheduler_metrics: SchedulerMetrics,
87
88 /// This scheduler only has one worker.
89 worker_metrics: WorkerMetrics,
90 }
91
92 /// Thread-local context.
93 ///
94 /// pub(crate) to store in `runtime::context`.
95 pub(crate) struct Context {
96 /// Scheduler handle
97 handle: Arc<Handle>,
98
99 /// Scheduler core, enabling the holder of `Context` to execute the
100 /// scheduler.
101 core: RefCell<Option<Box<Core>>>,
102
103 /// Deferred tasks, usually ones that called `task::yield_now()`.
104 pub(crate) defer: Defer,
105 }
106
107 type Notified = task::Notified<Arc<Handle>>;
108
109 /// Initial queue capacity.
110 const INITIAL_CAPACITY: usize = 64;
111
112 /// Used if none is specified. This is a temporary constant and will be removed
113 /// as we unify tuning logic between the multi-thread and current-thread
114 /// schedulers.
115 const DEFAULT_GLOBAL_QUEUE_INTERVAL: u32 = 31;
116
117 impl CurrentThread {
118 pub(crate) fn new(
119 driver: Driver,
120 driver_handle: driver::Handle,
121 blocking_spawner: blocking::Spawner,
122 seed_generator: RngSeedGenerator,
123 config: Config,
124 ) -> (CurrentThread, Arc<Handle>) {
125 let worker_metrics = WorkerMetrics::from_config(&config);
126 worker_metrics.set_thread_id(thread::current().id());
127
128 // Get the configured global queue interval, or use the default.
129 let global_queue_interval = config
130 .global_queue_interval
131 .unwrap_or(DEFAULT_GLOBAL_QUEUE_INTERVAL);
132
133 let handle = Arc::new(Handle {
134 shared: Shared {
135 inject: Inject::new(),
136 owned: OwnedTasks::new(1),
137 woken: AtomicBool::new(false),
138 config,
139 scheduler_metrics: SchedulerMetrics::new(),
140 worker_metrics,
141 },
142 driver: driver_handle,
143 blocking_spawner,
144 seed_generator,
145 });
146
147 let core = AtomicCell::new(Some(Box::new(Core {
148 tasks: VecDeque::with_capacity(INITIAL_CAPACITY),
149 tick: 0,
150 driver: Some(driver),
151 metrics: MetricsBatch::new(&handle.shared.worker_metrics),
152 global_queue_interval,
153 unhandled_panic: false,
154 })));
155
156 let scheduler = CurrentThread {
157 core,
158 notify: Notify::new(),
159 };
160
161 (scheduler, handle)
162 }
163
164 #[track_caller]
165 pub(crate) fn block_on<F: Future>(&self, handle: &scheduler::Handle, future: F) -> F::Output {
166 pin!(future);
167
168 crate::runtime::context::enter_runtime(handle, false, |blocking| {
169 let handle = handle.as_current_thread();
170
171 // Attempt to steal the scheduler core and block_on the future if we can
172 // there, otherwise, lets select on a notification that the core is
173 // available or the future is complete.
174 loop {
175 if let Some(core) = self.take_core(handle) {
176 handle
177 .shared
178 .worker_metrics
179 .set_thread_id(thread::current().id());
180 return core.block_on(future);
181 } else {
182 let notified = self.notify.notified();
183 pin!(notified);
184
185 if let Some(out) = blocking
186 .block_on(poll_fn(|cx| {
187 if notified.as_mut().poll(cx).is_ready() {
188 return Ready(None);
189 }
190
191 if let Ready(out) = future.as_mut().poll(cx) {
192 return Ready(Some(out));
193 }
194
195 Pending
196 }))
197 .expect("Failed to `Enter::block_on`")
198 {
199 return out;
200 }
201 }
202 }
203 })
204 }
205
206 fn take_core(&self, handle: &Arc<Handle>) -> Option<CoreGuard<'_>> {
207 let core = self.core.take()?;
208
209 Some(CoreGuard {
210 context: scheduler::Context::CurrentThread(Context {
211 handle: handle.clone(),
212 core: RefCell::new(Some(core)),
213 defer: Defer::new(),
214 }),
215 scheduler: self,
216 })
217 }
218
219 pub(crate) fn shutdown(&mut self, handle: &scheduler::Handle) {
220 let handle = handle.as_current_thread();
221
222 // Avoid a double panic if we are currently panicking and
223 // the lock may be poisoned.
224
225 let core = match self.take_core(handle) {
226 Some(core) => core,
227 None if std::thread::panicking() => return,
228 None => panic!("Oh no! We never placed the Core back, this is a bug!"),
229 };
230
231 // Check that the thread-local is not being destroyed
232 let tls_available = context::with_current(|_| ()).is_ok();
233
234 if tls_available {
235 core.enter(|core, _context| {
236 let core = shutdown2(core, handle);
237 (core, ())
238 });
239 } else {
240 // Shutdown without setting the context. `tokio::spawn` calls will
241 // fail, but those will fail either way because the thread-local is
242 // not available anymore.
243 let context = core.context.expect_current_thread();
244 let core = context.core.borrow_mut().take().unwrap();
245
246 let core = shutdown2(core, handle);
247 *context.core.borrow_mut() = Some(core);
248 }
249 }
250 }
251
252 fn shutdown2(mut core: Box<Core>, handle: &Handle) -> Box<Core> {
253 // Drain the OwnedTasks collection. This call also closes the
254 // collection, ensuring that no tasks are ever pushed after this
255 // call returns.
256 handle.shared.owned.close_and_shutdown_all(0);
257
258 // Drain local queue
259 // We already shut down every task, so we just need to drop the task.
260 while let Some(task) = core.next_local_task(handle) {
261 drop(task);
262 }
263
264 // Close the injection queue
265 handle.shared.inject.close();
266
267 // Drain remote queue
268 while let Some(task) = handle.shared.inject.pop() {
269 drop(task);
270 }
271
272 assert!(handle.shared.owned.is_empty());
273
274 // Submit metrics
275 core.submit_metrics(handle);
276
277 // Shutdown the resource drivers
278 if let Some(driver) = core.driver.as_mut() {
279 driver.shutdown(&handle.driver);
280 }
281
282 core
283 }
284
285 impl fmt::Debug for CurrentThread {
286 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
287 fmt.debug_struct("CurrentThread").finish()
288 }
289 }
290
291 // ===== impl Core =====
292
293 impl Core {
294 /// Get and increment the current tick
295 fn tick(&mut self) {
296 self.tick = self.tick.wrapping_add(1);
297 }
298
299 fn next_task(&mut self, handle: &Handle) -> Option<Notified> {
300 if self.tick % self.global_queue_interval == 0 {
301 handle
302 .next_remote_task()
303 .or_else(|| self.next_local_task(handle))
304 } else {
305 self.next_local_task(handle)
306 .or_else(|| handle.next_remote_task())
307 }
308 }
309
310 fn next_local_task(&mut self, handle: &Handle) -> Option<Notified> {
311 let ret = self.tasks.pop_front();
312 handle
313 .shared
314 .worker_metrics
315 .set_queue_depth(self.tasks.len());
316 ret
317 }
318
319 fn push_task(&mut self, handle: &Handle, task: Notified) {
320 self.tasks.push_back(task);
321 self.metrics.inc_local_schedule_count();
322 handle
323 .shared
324 .worker_metrics
325 .set_queue_depth(self.tasks.len());
326 }
327
328 fn submit_metrics(&mut self, handle: &Handle) {
329 self.metrics.submit(&handle.shared.worker_metrics, 0);
330 }
331 }
332
333 #[cfg(tokio_taskdump)]
334 fn wake_deferred_tasks_and_free(context: &Context) {
335 let wakers = context.defer.take_deferred();
336 for waker in wakers {
337 waker.wake();
338 }
339 }
340
341 // ===== impl Context =====
342
343 impl Context {
344 /// Execute the closure with the given scheduler core stored in the
345 /// thread-local context.
346 fn run_task<R>(&self, mut core: Box<Core>, f: impl FnOnce() -> R) -> (Box<Core>, R) {
347 core.metrics.start_poll();
348 let mut ret = self.enter(core, || crate::runtime::coop::budget(f));
349 ret.0.metrics.end_poll();
350 ret
351 }
352
353 /// Blocks the current thread until an event is received by the driver,
354 /// including I/O events, timer events, ...
355 fn park(&self, mut core: Box<Core>, handle: &Handle) -> Box<Core> {
356 let mut driver = core.driver.take().expect("driver missing");
357
358 if let Some(f) = &handle.shared.config.before_park {
359 let (c, ()) = self.enter(core, || f());
360 core = c;
361 }
362
363 // This check will fail if `before_park` spawns a task for us to run
364 // instead of parking the thread
365 if core.tasks.is_empty() {
366 // Park until the thread is signaled
367 core.metrics.about_to_park();
368 core.submit_metrics(handle);
369
370 let (c, ()) = self.enter(core, || {
371 driver.park(&handle.driver);
372 self.defer.wake();
373 });
374
375 core = c;
376
377 core.metrics.unparked();
378 core.submit_metrics(handle);
379 }
380
381 if let Some(f) = &handle.shared.config.after_unpark {
382 let (c, ()) = self.enter(core, || f());
383 core = c;
384 }
385
386 core.driver = Some(driver);
387 core
388 }
389
390 /// Checks the driver for new events without blocking the thread.
391 fn park_yield(&self, mut core: Box<Core>, handle: &Handle) -> Box<Core> {
392 let mut driver = core.driver.take().expect("driver missing");
393
394 core.submit_metrics(handle);
395
396 let (mut core, ()) = self.enter(core, || {
397 driver.park_timeout(&handle.driver, Duration::from_millis(0));
398 self.defer.wake();
399 });
400
401 core.driver = Some(driver);
402 core
403 }
404
405 fn enter<R>(&self, core: Box<Core>, f: impl FnOnce() -> R) -> (Box<Core>, R) {
406 // Store the scheduler core in the thread-local context
407 //
408 // A drop-guard is employed at a higher level.
409 *self.core.borrow_mut() = Some(core);
410
411 // Execute the closure while tracking the execution budget
412 let ret = f();
413
414 // Take the scheduler core back
415 let core = self.core.borrow_mut().take().expect("core missing");
416 (core, ret)
417 }
418
419 pub(crate) fn defer(&self, waker: &Waker) {
420 self.defer.defer(waker);
421 }
422 }
423
424 // ===== impl Handle =====
425
426 impl Handle {
427 /// Spawns a future onto the `CurrentThread` scheduler
428 pub(crate) fn spawn<F>(
429 me: &Arc<Self>,
430 future: F,
431 id: crate::runtime::task::Id,
432 ) -> JoinHandle<F::Output>
433 where
434 F: crate::future::Future + Send + 'static,
435 F::Output: Send + 'static,
436 {
437 let (handle, notified) = me.shared.owned.bind(future, me.clone(), id);
438
439 if let Some(notified) = notified {
440 me.schedule(notified);
441 }
442
443 handle
444 }
445
446 /// Capture a snapshot of this runtime's state.
447 #[cfg(all(
448 tokio_unstable,
449 tokio_taskdump,
450 target_os = "linux",
451 any(target_arch = "aarch64", target_arch = "x86", target_arch = "x86_64")
452 ))]
453 pub(crate) fn dump(&self) -> crate::runtime::Dump {
454 use crate::runtime::dump;
455 use task::trace::trace_current_thread;
456
457 let mut traces = vec![];
458
459 // todo: how to make this work outside of a runtime context?
460 context::with_scheduler(|maybe_context| {
461 // drain the local queue
462 let context = if let Some(context) = maybe_context {
463 context.expect_current_thread()
464 } else {
465 return;
466 };
467 let mut maybe_core = context.core.borrow_mut();
468 let core = if let Some(core) = maybe_core.as_mut() {
469 core
470 } else {
471 return;
472 };
473 let local = &mut core.tasks;
474
475 if self.shared.inject.is_closed() {
476 return;
477 }
478
479 traces = trace_current_thread(&self.shared.owned, local, &self.shared.inject)
480 .into_iter()
481 .map(|(id, trace)| dump::Task::new(id, trace))
482 .collect();
483
484 // Avoid double borrow panic
485 drop(maybe_core);
486
487 // Taking a taskdump could wakes every task, but we probably don't want
488 // the `yield_now` vector to be that large under normal circumstances.
489 // Therefore, we free its allocation.
490 wake_deferred_tasks_and_free(context);
491 });
492
493 dump::Dump::new(traces)
494 }
495
496 fn next_remote_task(&self) -> Option<Notified> {
497 self.shared.inject.pop()
498 }
499
500 fn waker_ref(me: &Arc<Self>) -> WakerRef<'_> {
501 // Set woken to true when enter block_on, ensure outer future
502 // be polled for the first time when enter loop
503 me.shared.woken.store(true, Release);
504 waker_ref(me)
505 }
506
507 // reset woken to false and return original value
508 pub(crate) fn reset_woken(&self) -> bool {
509 self.shared.woken.swap(false, AcqRel)
510 }
511
512 pub(crate) fn num_alive_tasks(&self) -> usize {
513 self.shared.owned.num_alive_tasks()
514 }
515 }
516
517 cfg_unstable_metrics! {
518 impl Handle {
519 pub(crate) fn scheduler_metrics(&self) -> &SchedulerMetrics {
520 &self.shared.scheduler_metrics
521 }
522
523 pub(crate) fn injection_queue_depth(&self) -> usize {
524 self.shared.inject.len()
525 }
526
527 pub(crate) fn worker_metrics(&self, worker: usize) -> &WorkerMetrics {
528 assert_eq!(0, worker);
529 &self.shared.worker_metrics
530 }
531
532 pub(crate) fn worker_local_queue_depth(&self, worker: usize) -> usize {
533 self.worker_metrics(worker).queue_depth()
534 }
535
536 pub(crate) fn num_blocking_threads(&self) -> usize {
537 self.blocking_spawner.num_threads()
538 }
539
540 pub(crate) fn num_idle_blocking_threads(&self) -> usize {
541 self.blocking_spawner.num_idle_threads()
542 }
543
544 pub(crate) fn blocking_queue_depth(&self) -> usize {
545 self.blocking_spawner.queue_depth()
546 }
547
548 cfg_64bit_metrics! {
549 pub(crate) fn spawned_tasks_count(&self) -> u64 {
550 self.shared.owned.spawned_tasks_count()
551 }
552 }
553 }
554 }
555
556 cfg_unstable! {
557 use std::num::NonZeroU64;
558
559 impl Handle {
560 pub(crate) fn owned_id(&self) -> NonZeroU64 {
561 self.shared.owned.id
562 }
563 }
564 }
565
566 impl fmt::Debug for Handle {
567 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
568 fmt.debug_struct("current_thread::Handle { ... }").finish()
569 }
570 }
571
572 // ===== impl Shared =====
573
574 impl Schedule for Arc<Handle> {
575 fn release(&self, task: &Task<Self>) -> Option<Task<Self>> {
576 self.shared.owned.remove(task)
577 }
578
579 fn schedule(&self, task: task::Notified<Self>) {
580 use scheduler::Context::CurrentThread;
581
582 context::with_scheduler(|maybe_cx| match maybe_cx {
583 Some(CurrentThread(cx)) if Arc::ptr_eq(self, &cx.handle) => {
584 let mut core = cx.core.borrow_mut();
585
586 // If `None`, the runtime is shutting down, so there is no need
587 // to schedule the task.
588 if let Some(core) = core.as_mut() {
589 core.push_task(self, task);
590 }
591 }
592 _ => {
593 // Track that a task was scheduled from **outside** of the runtime.
594 self.shared.scheduler_metrics.inc_remote_schedule_count();
595
596 // Schedule the task
597 self.shared.inject.push(task);
598 self.driver.unpark();
599 }
600 });
601 }
602
603 cfg_unstable! {
604 fn unhandled_panic(&self) {
605 use crate::runtime::UnhandledPanic;
606
607 match self.shared.config.unhandled_panic {
608 UnhandledPanic::Ignore => {
609 // Do nothing
610 }
611 UnhandledPanic::ShutdownRuntime => {
612 use scheduler::Context::CurrentThread;
613
614 // This hook is only called from within the runtime, so
615 // `context::with_scheduler` should match with `&self`, i.e.
616 // there is no opportunity for a nested scheduler to be
617 // called.
618 context::with_scheduler(|maybe_cx| match maybe_cx {
619 Some(CurrentThread(cx)) if Arc::ptr_eq(self, &cx.handle) => {
620 let mut core = cx.core.borrow_mut();
621
622 // If `None`, the runtime is shutting down, so there is no need to signal shutdown
623 if let Some(core) = core.as_mut() {
624 core.unhandled_panic = true;
625 self.shared.owned.close_and_shutdown_all(0);
626 }
627 }
628 _ => unreachable!("runtime core not set in CURRENT thread-local"),
629 })
630 }
631 }
632 }
633 }
634 }
635
636 impl Wake for Handle {
637 fn wake(arc_self: Arc<Self>) {
638 Wake::wake_by_ref(&arc_self);
639 }
640
641 /// Wake by reference
642 fn wake_by_ref(arc_self: &Arc<Self>) {
643 arc_self.shared.woken.store(true, Release);
644 arc_self.driver.unpark();
645 }
646 }
647
648 // ===== CoreGuard =====
649
650 /// Used to ensure we always place the `Core` value back into its slot in
651 /// `CurrentThread`, even if the future panics.
652 struct CoreGuard<'a> {
653 context: scheduler::Context,
654 scheduler: &'a CurrentThread,
655 }
656
657 impl CoreGuard<'_> {
658 #[track_caller]
659 fn block_on<F: Future>(self, future: F) -> F::Output {
660 let ret = self.enter(|mut core, context| {
661 let waker = Handle::waker_ref(&context.handle);
662 let mut cx = std::task::Context::from_waker(&waker);
663
664 pin!(future);
665
666 core.metrics.start_processing_scheduled_tasks();
667
668 'outer: loop {
669 let handle = &context.handle;
670
671 if handle.reset_woken() {
672 let (c, res) = context.enter(core, || {
673 crate::runtime::coop::budget(|| future.as_mut().poll(&mut cx))
674 });
675
676 core = c;
677
678 if let Ready(v) = res {
679 return (core, Some(v));
680 }
681 }
682
683 for _ in 0..handle.shared.config.event_interval {
684 // Make sure we didn't hit an unhandled_panic
685 if core.unhandled_panic {
686 return (core, None);
687 }
688
689 core.tick();
690
691 let entry = core.next_task(handle);
692
693 let task = match entry {
694 Some(entry) => entry,
695 None => {
696 core.metrics.end_processing_scheduled_tasks();
697
698 core = if !context.defer.is_empty() {
699 context.park_yield(core, handle)
700 } else {
701 context.park(core, handle)
702 };
703
704 core.metrics.start_processing_scheduled_tasks();
705
706 // Try polling the `block_on` future next
707 continue 'outer;
708 }
709 };
710
711 let task = context.handle.shared.owned.assert_owner(task);
712
713 let (c, ()) = context.run_task(core, || {
714 task.run();
715 });
716
717 core = c;
718 }
719
720 core.metrics.end_processing_scheduled_tasks();
721
722 // Yield to the driver, this drives the timer and pulls any
723 // pending I/O events.
724 core = context.park_yield(core, handle);
725
726 core.metrics.start_processing_scheduled_tasks();
727 }
728 });
729
730 match ret {
731 Some(ret) => ret,
732 None => {
733 // `block_on` panicked.
734 panic!("a spawned task panicked and the runtime is configured to shut down on unhandled panic");
735 }
736 }
737 }
738
739 /// Enters the scheduler context. This sets the queue and other necessary
740 /// scheduler state in the thread-local.
741 fn enter<F, R>(self, f: F) -> R
742 where
743 F: FnOnce(Box<Core>, &Context) -> (Box<Core>, R),
744 {
745 let context = self.context.expect_current_thread();
746
747 // Remove `core` from `context` to pass into the closure.
748 let core = context.core.borrow_mut().take().expect("core missing");
749
750 // Call the closure and place `core` back
751 let (core, ret) = context::set_scheduler(&self.context, || f(core, context));
752
753 *context.core.borrow_mut() = Some(core);
754
755 ret
756 }
757 }
758
759 impl Drop for CoreGuard<'_> {
760 fn drop(&mut self) {
761 let context = self.context.expect_current_thread();
762
763 if let Some(core) = context.core.borrow_mut().take() {
764 // Replace old scheduler back into the state to allow
765 // other threads to pick it up and drive it.
766 self.scheduler.core.set(core);
767
768 // Wake up other possible threads that could steal the driver.
769 self.scheduler.notify.notify_one();
770 }
771 }
772 }