Debian Codegraph @

third_party/rust/tokio/src/task/local.rs

raw
1 //! Runs `!Send` futures on the current thread.
2 use crate::loom::cell::UnsafeCell;
3 use crate::loom::sync::{Arc, Mutex};
4 #[cfg(tokio_unstable)]
5 use crate::runtime;
6 use crate::runtime::task::{self, JoinHandle, LocalOwnedTasks, Task};
7 use crate::runtime::{context, ThreadId, BOX_FUTURE_THRESHOLD};
8 use crate::sync::AtomicWaker;
9 use crate::util::RcCell;
10
11 use std::cell::Cell;
12 use std::collections::VecDeque;
13 use std::fmt;
14 use std::future::Future;
15 use std::marker::PhantomData;
16 use std::pin::Pin;
17 use std::rc::Rc;
18 use std::task::Poll;
19
20 use pin_project_lite::pin_project;
21
22 cfg_rt! {
23 /// A set of tasks which are executed on the same thread.
24 ///
25 /// In some cases, it is necessary to run one or more futures that do not
26 /// implement [`Send`] and thus are unsafe to send between threads. In these
27 /// cases, a [local task set] may be used to schedule one or more `!Send`
28 /// futures to run together on the same thread.
29 ///
30 /// For example, the following code will not compile:
31 ///
32 /// ```rust,compile_fail
33 /// use std::rc::Rc;
34 ///
35 /// #[tokio::main]
36 /// async fn main() {
37 /// // `Rc` does not implement `Send`, and thus may not be sent between
38 /// // threads safely.
39 /// let nonsend_data = Rc::new("my nonsend data...");
40 ///
41 /// let nonsend_data = nonsend_data.clone();
42 /// // Because the `async` block here moves `nonsend_data`, the future is `!Send`.
43 /// // Since `tokio::spawn` requires the spawned future to implement `Send`, this
44 /// // will not compile.
45 /// tokio::spawn(async move {
46 /// println!("{}", nonsend_data);
47 /// // ...
48 /// }).await.unwrap();
49 /// }
50 /// ```
51 ///
52 /// # Use with `run_until`
53 ///
54 /// To spawn `!Send` futures, we can use a local task set to schedule them
55 /// on the thread calling [`Runtime::block_on`]. When running inside of the
56 /// local task set, we can use [`task::spawn_local`], which can spawn
57 /// `!Send` futures. For example:
58 ///
59 /// ```rust
60 /// use std::rc::Rc;
61 /// use tokio::task;
62 ///
63 /// #[tokio::main]
64 /// async fn main() {
65 /// let nonsend_data = Rc::new("my nonsend data...");
66 ///
67 /// // Construct a local task set that can run `!Send` futures.
68 /// let local = task::LocalSet::new();
69 ///
70 /// // Run the local task set.
71 /// local.run_until(async move {
72 /// let nonsend_data = nonsend_data.clone();
73 /// // `spawn_local` ensures that the future is spawned on the local
74 /// // task set.
75 /// task::spawn_local(async move {
76 /// println!("{}", nonsend_data);
77 /// // ...
78 /// }).await.unwrap();
79 /// }).await;
80 /// }
81 /// ```
82 /// **Note:** The `run_until` method can only be used in `#[tokio::main]`,
83 /// `#[tokio::test]` or directly inside a call to [`Runtime::block_on`]. It
84 /// cannot be used inside a task spawned with `tokio::spawn`.
85 ///
86 /// ## Awaiting a `LocalSet`
87 ///
88 /// Additionally, a `LocalSet` itself implements `Future`, completing when
89 /// *all* tasks spawned on the `LocalSet` complete. This can be used to run
90 /// several futures on a `LocalSet` and drive the whole set until they
91 /// complete. For example,
92 ///
93 /// ```rust
94 /// use tokio::{task, time};
95 /// use std::rc::Rc;
96 ///
97 /// #[tokio::main]
98 /// async fn main() {
99 /// let nonsend_data = Rc::new("world");
100 /// let local = task::LocalSet::new();
101 ///
102 /// let nonsend_data2 = nonsend_data.clone();
103 /// local.spawn_local(async move {
104 /// // ...
105 /// println!("hello {}", nonsend_data2)
106 /// });
107 ///
108 /// local.spawn_local(async move {
109 /// time::sleep(time::Duration::from_millis(100)).await;
110 /// println!("goodbye {}", nonsend_data)
111 /// });
112 ///
113 /// // ...
114 ///
115 /// local.await;
116 /// }
117 /// ```
118 /// **Note:** Awaiting a `LocalSet` can only be done inside
119 /// `#[tokio::main]`, `#[tokio::test]` or directly inside a call to
120 /// [`Runtime::block_on`]. It cannot be used inside a task spawned with
121 /// `tokio::spawn`.
122 ///
123 /// ## Use inside `tokio::spawn`
124 ///
125 /// The two methods mentioned above cannot be used inside `tokio::spawn`, so
126 /// to spawn `!Send` futures from inside `tokio::spawn`, we need to do
127 /// something else. The solution is to create the `LocalSet` somewhere else,
128 /// and communicate with it using an [`mpsc`] channel.
129 ///
130 /// The following example puts the `LocalSet` inside a new thread.
131 /// ```
132 /// use tokio::runtime::Builder;
133 /// use tokio::sync::{mpsc, oneshot};
134 /// use tokio::task::LocalSet;
135 ///
136 /// // This struct describes the task you want to spawn. Here we include
137 /// // some simple examples. The oneshot channel allows sending a response
138 /// // to the spawner.
139 /// #[derive(Debug)]
140 /// enum Task {
141 /// PrintNumber(u32),
142 /// AddOne(u32, oneshot::Sender<u32>),
143 /// }
144 ///
145 /// #[derive(Clone)]
146 /// struct LocalSpawner {
147 /// send: mpsc::UnboundedSender<Task>,
148 /// }
149 ///
150 /// impl LocalSpawner {
151 /// pub fn new() -> Self {
152 /// let (send, mut recv) = mpsc::unbounded_channel();
153 ///
154 /// let rt = Builder::new_current_thread()
155 /// .enable_all()
156 /// .build()
157 /// .unwrap();
158 ///
159 /// std::thread::spawn(move || {
160 /// let local = LocalSet::new();
161 ///
162 /// local.spawn_local(async move {
163 /// while let Some(new_task) = recv.recv().await {
164 /// tokio::task::spawn_local(run_task(new_task));
165 /// }
166 /// // If the while loop returns, then all the LocalSpawner
167 /// // objects have been dropped.
168 /// });
169 ///
170 /// // This will return once all senders are dropped and all
171 /// // spawned tasks have returned.
172 /// rt.block_on(local);
173 /// });
174 ///
175 /// Self {
176 /// send,
177 /// }
178 /// }
179 ///
180 /// pub fn spawn(&self, task: Task) {
181 /// self.send.send(task).expect("Thread with LocalSet has shut down.");
182 /// }
183 /// }
184 ///
185 /// // This task may do !Send stuff. We use printing a number as an example,
186 /// // but it could be anything.
187 /// //
188 /// // The Task struct is an enum to support spawning many different kinds
189 /// // of operations.
190 /// async fn run_task(task: Task) {
191 /// match task {
192 /// Task::PrintNumber(n) => {
193 /// println!("{}", n);
194 /// },
195 /// Task::AddOne(n, response) => {
196 /// // We ignore failures to send the response.
197 /// let _ = response.send(n + 1);
198 /// },
199 /// }
200 /// }
201 ///
202 /// #[tokio::main]
203 /// async fn main() {
204 /// let spawner = LocalSpawner::new();
205 ///
206 /// let (send, response) = oneshot::channel();
207 /// spawner.spawn(Task::AddOne(10, send));
208 /// let eleven = response.await.unwrap();
209 /// assert_eq!(eleven, 11);
210 /// }
211 /// ```
212 ///
213 /// [`Send`]: trait@std::marker::Send
214 /// [local task set]: struct@LocalSet
215 /// [`Runtime::block_on`]: method@crate::runtime::Runtime::block_on
216 /// [`task::spawn_local`]: fn@spawn_local
217 /// [`mpsc`]: mod@crate::sync::mpsc
218 pub struct LocalSet {
219 /// Current scheduler tick.
220 tick: Cell<u8>,
221
222 /// State available from thread-local.
223 context: Rc<Context>,
224
225 /// This type should not be Send.
226 _not_send: PhantomData<*const ()>,
227 }
228 }
229
230 /// State available from the thread-local.
231 struct Context {
232 /// State shared between threads.
233 shared: Arc<Shared>,
234
235 /// True if a task panicked without being handled and the local set is
236 /// configured to shutdown on unhandled panic.
237 unhandled_panic: Cell<bool>,
238 }
239
240 /// `LocalSet` state shared between threads.
241 struct Shared {
242 /// # Safety
243 ///
244 /// This field must *only* be accessed from the thread that owns the
245 /// `LocalSet` (i.e., `Thread::current().id() == owner`).
246 local_state: LocalState,
247
248 /// Remote run queue sender.
249 queue: Mutex<Option<VecDeque<task::Notified<Arc<Shared>>>>>,
250
251 /// Wake the `LocalSet` task.
252 waker: AtomicWaker,
253
254 /// How to respond to unhandled task panics.
255 #[cfg(tokio_unstable)]
256 pub(crate) unhandled_panic: crate::runtime::UnhandledPanic,
257 }
258
259 /// Tracks the `LocalSet` state that must only be accessed from the thread that
260 /// created the `LocalSet`.
261 struct LocalState {
262 /// The `ThreadId` of the thread that owns the `LocalSet`.
263 owner: ThreadId,
264
265 /// Local run queue sender and receiver.
266 local_queue: UnsafeCell<VecDeque<task::Notified<Arc<Shared>>>>,
267
268 /// Collection of all active tasks spawned onto this executor.
269 owned: LocalOwnedTasks<Arc<Shared>>,
270 }
271
272 pin_project! {
273 #[derive(Debug)]
274 struct RunUntil<'a, F> {
275 local_set: &'a LocalSet,
276 #[pin]
277 future: F,
278 }
279 }
280
281 tokio_thread_local!(static CURRENT: LocalData = const { LocalData {
282 ctx: RcCell::new(),
283 wake_on_schedule: Cell::new(false),
284 } });
285
286 struct LocalData {
287 ctx: RcCell<Context>,
288 wake_on_schedule: Cell<bool>,
289 }
290
291 impl LocalData {
292 /// Should be called except when we call `LocalSet::enter`.
293 /// Especially when we poll a `LocalSet`.
294 #[must_use = "dropping this guard will reset the entered state"]
295 fn enter(&self, ctx: Rc<Context>) -> LocalDataEnterGuard<'_> {
296 let ctx = self.ctx.replace(Some(ctx));
297 let wake_on_schedule = self.wake_on_schedule.replace(false);
298 LocalDataEnterGuard {
299 local_data_ref: self,
300 ctx,
301 wake_on_schedule,
302 }
303 }
304 }
305
306 /// A guard for `LocalData::enter()`
307 struct LocalDataEnterGuard<'a> {
308 local_data_ref: &'a LocalData,
309 ctx: Option<Rc<Context>>,
310 wake_on_schedule: bool,
311 }
312
313 impl<'a> Drop for LocalDataEnterGuard<'a> {
314 fn drop(&mut self) {
315 self.local_data_ref.ctx.set(self.ctx.take());
316 self.local_data_ref
317 .wake_on_schedule
318 .set(self.wake_on_schedule)
319 }
320 }
321
322 cfg_rt! {
323 /// Spawns a `!Send` future on the current [`LocalSet`].
324 ///
325 /// The spawned future will run on the same thread that called `spawn_local`.
326 ///
327 /// The provided future will start running in the background immediately
328 /// when `spawn_local` is called, even if you don't await the returned
329 /// `JoinHandle`.
330 ///
331 /// # Panics
332 ///
333 /// This function panics if called outside of a [`LocalSet`].
334 ///
335 /// Note that if [`tokio::spawn`] is used from within a `LocalSet`, the
336 /// resulting new task will _not_ be inside the `LocalSet`, so you must use
337 /// `spawn_local` if you want to stay within the `LocalSet`.
338 ///
339 /// # Examples
340 ///
341 /// ```rust
342 /// use std::rc::Rc;
343 /// use tokio::task;
344 ///
345 /// #[tokio::main]
346 /// async fn main() {
347 /// let nonsend_data = Rc::new("my nonsend data...");
348 ///
349 /// let local = task::LocalSet::new();
350 ///
351 /// // Run the local task set.
352 /// local.run_until(async move {
353 /// let nonsend_data = nonsend_data.clone();
354 /// task::spawn_local(async move {
355 /// println!("{}", nonsend_data);
356 /// // ...
357 /// }).await.unwrap();
358 /// }).await;
359 /// }
360 /// ```
361 ///
362 /// [`LocalSet`]: struct@crate::task::LocalSet
363 /// [`tokio::spawn`]: fn@crate::task::spawn
364 #[track_caller]
365 pub fn spawn_local<F>(future: F) -> JoinHandle<F::Output>
366 where
367 F: Future + 'static,
368 F::Output: 'static,
369 {
370 if cfg!(debug_assertions) && std::mem::size_of::<F>() > BOX_FUTURE_THRESHOLD {
371 spawn_local_inner(Box::pin(future), None)
372 } else {
373 spawn_local_inner(future, None)
374 }
375 }
376
377
378 #[track_caller]
379 pub(super) fn spawn_local_inner<F>(future: F, name: Option<&str>) -> JoinHandle<F::Output>
380 where F: Future + 'static,
381 F::Output: 'static
382 {
383 match CURRENT.with(|LocalData { ctx, .. }| ctx.get()) {
384 None => panic!("`spawn_local` called from outside of a `task::LocalSet`"),
385 Some(cx) => cx.spawn(future, name)
386 }
387 }
388 }
389
390 /// Initial queue capacity.
391 const INITIAL_CAPACITY: usize = 64;
392
393 /// Max number of tasks to poll per tick.
394 const MAX_TASKS_PER_TICK: usize = 61;
395
396 /// How often it check the remote queue first.
397 const REMOTE_FIRST_INTERVAL: u8 = 31;
398
399 /// Context guard for `LocalSet`
400 pub struct LocalEnterGuard {
401 ctx: Option<Rc<Context>>,
402
403 /// Distinguishes whether the context was entered or being polled.
404 /// When we enter it, the value `wake_on_schedule` is set. In this case
405 /// `spawn_local` refers the context, whereas it is not being polled now.
406 wake_on_schedule: bool,
407 }
408
409 impl Drop for LocalEnterGuard {
410 fn drop(&mut self) {
411 CURRENT.with(
412 |LocalData {
413 ctx,
414 wake_on_schedule,
415 }| {
416 ctx.set(self.ctx.take());
417 wake_on_schedule.set(self.wake_on_schedule);
418 },
419 );
420 }
421 }
422
423 impl fmt::Debug for LocalEnterGuard {
424 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
425 f.debug_struct("LocalEnterGuard").finish()
426 }
427 }
428
429 impl LocalSet {
430 /// Returns a new local task set.
431 pub fn new() -> LocalSet {
432 let owner = context::thread_id().expect("cannot create LocalSet during thread shutdown");
433
434 LocalSet {
435 tick: Cell::new(0),
436 context: Rc::new(Context {
437 shared: Arc::new(Shared {
438 local_state: LocalState {
439 owner,
440 owned: LocalOwnedTasks::new(),
441 local_queue: UnsafeCell::new(VecDeque::with_capacity(INITIAL_CAPACITY)),
442 },
443 queue: Mutex::new(Some(VecDeque::with_capacity(INITIAL_CAPACITY))),
444 waker: AtomicWaker::new(),
445 #[cfg(tokio_unstable)]
446 unhandled_panic: crate::runtime::UnhandledPanic::Ignore,
447 }),
448 unhandled_panic: Cell::new(false),
449 }),
450 _not_send: PhantomData,
451 }
452 }
453
454 /// Enters the context of this `LocalSet`.
455 ///
456 /// The [`spawn_local`] method will spawn tasks on the `LocalSet` whose
457 /// context you are inside.
458 ///
459 /// [`spawn_local`]: fn@crate::task::spawn_local
460 pub fn enter(&self) -> LocalEnterGuard {
461 CURRENT.with(
462 |LocalData {
463 ctx,
464 wake_on_schedule,
465 ..
466 }| {
467 let ctx = ctx.replace(Some(self.context.clone()));
468 let wake_on_schedule = wake_on_schedule.replace(true);
469 LocalEnterGuard {
470 ctx,
471 wake_on_schedule,
472 }
473 },
474 )
475 }
476
477 /// Spawns a `!Send` task onto the local task set.
478 ///
479 /// This task is guaranteed to be run on the current thread.
480 ///
481 /// Unlike the free function [`spawn_local`], this method may be used to
482 /// spawn local tasks when the `LocalSet` is _not_ running. The provided
483 /// future will start running once the `LocalSet` is next started, even if
484 /// you don't await the returned `JoinHandle`.
485 ///
486 /// # Examples
487 ///
488 /// ```rust
489 /// use tokio::task;
490 ///
491 /// #[tokio::main]
492 /// async fn main() {
493 /// let local = task::LocalSet::new();
494 ///
495 /// // Spawn a future on the local set. This future will be run when
496 /// // we call `run_until` to drive the task set.
497 /// local.spawn_local(async {
498 /// // ...
499 /// });
500 ///
501 /// // Run the local task set.
502 /// local.run_until(async move {
503 /// // ...
504 /// }).await;
505 ///
506 /// // When `run` finishes, we can spawn _more_ futures, which will
507 /// // run in subsequent calls to `run_until`.
508 /// local.spawn_local(async {
509 /// // ...
510 /// });
511 ///
512 /// local.run_until(async move {
513 /// // ...
514 /// }).await;
515 /// }
516 /// ```
517 /// [`spawn_local`]: fn@spawn_local
518 #[track_caller]
519 pub fn spawn_local<F>(&self, future: F) -> JoinHandle<F::Output>
520 where
521 F: Future + 'static,
522 F::Output: 'static,
523 {
524 self.spawn_named(future, None)
525 }
526
527 /// Runs a future to completion on the provided runtime, driving any local
528 /// futures spawned on this task set on the current thread.
529 ///
530 /// This runs the given future on the runtime, blocking until it is
531 /// complete, and yielding its resolved result. Any tasks or timers which
532 /// the future spawns internally will be executed on the runtime. The future
533 /// may also call [`spawn_local`] to `spawn_local` additional local futures on the
534 /// current thread.
535 ///
536 /// This method should not be called from an asynchronous context.
537 ///
538 /// # Panics
539 ///
540 /// This function panics if the executor is at capacity, if the provided
541 /// future panics, or if called within an asynchronous execution context.
542 ///
543 /// # Notes
544 ///
545 /// Since this function internally calls [`Runtime::block_on`], and drives
546 /// futures in the local task set inside that call to `block_on`, the local
547 /// futures may not use [in-place blocking]. If a blocking call needs to be
548 /// issued from a local task, the [`spawn_blocking`] API may be used instead.
549 ///
550 /// For example, this will panic:
551 /// ```should_panic
552 /// use tokio::runtime::Runtime;
553 /// use tokio::task;
554 ///
555 /// let rt = Runtime::new().unwrap();
556 /// let local = task::LocalSet::new();
557 /// local.block_on(&rt, async {
558 /// let join = task::spawn_local(async {
559 /// let blocking_result = task::block_in_place(|| {
560 /// // ...
561 /// });
562 /// // ...
563 /// });
564 /// join.await.unwrap();
565 /// })
566 /// ```
567 /// This, however, will not panic:
568 /// ```
569 /// use tokio::runtime::Runtime;
570 /// use tokio::task;
571 ///
572 /// let rt = Runtime::new().unwrap();
573 /// let local = task::LocalSet::new();
574 /// local.block_on(&rt, async {
575 /// let join = task::spawn_local(async {
576 /// let blocking_result = task::spawn_blocking(|| {
577 /// // ...
578 /// }).await;
579 /// // ...
580 /// });
581 /// join.await.unwrap();
582 /// })
583 /// ```
584 ///
585 /// [`spawn_local`]: fn@spawn_local
586 /// [`Runtime::block_on`]: method@crate::runtime::Runtime::block_on
587 /// [in-place blocking]: fn@crate::task::block_in_place
588 /// [`spawn_blocking`]: fn@crate::task::spawn_blocking
589 #[track_caller]
590 #[cfg(feature = "rt")]
591 #[cfg_attr(docsrs, doc(cfg(feature = "rt")))]
592 pub fn block_on<F>(&self, rt: &crate::runtime::Runtime, future: F) -> F::Output
593 where
594 F: Future,
595 {
596 rt.block_on(self.run_until(future))
597 }
598
599 /// Runs a future to completion on the local set, returning its output.
600 ///
601 /// This returns a future that runs the given future with a local set,
602 /// allowing it to call [`spawn_local`] to spawn additional `!Send` futures.
603 /// Any local futures spawned on the local set will be driven in the
604 /// background until the future passed to `run_until` completes. When the future
605 /// passed to `run_until` finishes, any local futures which have not completed
606 /// will remain on the local set, and will be driven on subsequent calls to
607 /// `run_until` or when [awaiting the local set] itself.
608 ///
609 /// # Cancel safety
610 ///
611 /// This method is cancel safe when `future` is cancel safe.
612 ///
613 /// # Examples
614 ///
615 /// ```rust
616 /// use tokio::task;
617 ///
618 /// #[tokio::main]
619 /// async fn main() {
620 /// task::LocalSet::new().run_until(async {
621 /// task::spawn_local(async move {
622 /// // ...
623 /// }).await.unwrap();
624 /// // ...
625 /// }).await;
626 /// }
627 /// ```
628 ///
629 /// [`spawn_local`]: fn@spawn_local
630 /// [awaiting the local set]: #awaiting-a-localset
631 pub async fn run_until<F>(&self, future: F) -> F::Output
632 where
633 F: Future,
634 {
635 let run_until = RunUntil {
636 future,
637 local_set: self,
638 };
639 run_until.await
640 }
641
642 #[track_caller]
643 pub(in crate::task) fn spawn_named<F>(
644 &self,
645 future: F,
646 name: Option<&str>,
647 ) -> JoinHandle<F::Output>
648 where
649 F: Future + 'static,
650 F::Output: 'static,
651 {
652 if cfg!(debug_assertions) && std::mem::size_of::<F>() > BOX_FUTURE_THRESHOLD {
653 self.spawn_named_inner(Box::pin(future), name)
654 } else {
655 self.spawn_named_inner(future, name)
656 }
657 }
658
659 #[track_caller]
660 fn spawn_named_inner<F>(&self, future: F, name: Option<&str>) -> JoinHandle<F::Output>
661 where
662 F: Future + 'static,
663 F::Output: 'static,
664 {
665 let handle = self.context.spawn(future, name);
666
667 // Because a task was spawned from *outside* the `LocalSet`, wake the
668 // `LocalSet` future to execute the new task, if it hasn't been woken.
669 //
670 // Spawning via the free fn `spawn` does not require this, as it can
671 // only be called from *within* a future executing on the `LocalSet` —
672 // in that case, the `LocalSet` must already be awake.
673 self.context.shared.waker.wake();
674 handle
675 }
676
677 /// Ticks the scheduler, returning whether the local future needs to be
678 /// notified again.
679 fn tick(&self) -> bool {
680 for _ in 0..MAX_TASKS_PER_TICK {
681 // Make sure we didn't hit an unhandled panic
682 assert!(!self.context.unhandled_panic.get(), "a spawned task panicked and the LocalSet is configured to shutdown on unhandled panic");
683
684 match self.next_task() {
685 // Run the task
686 //
687 // Safety: As spawned tasks are `!Send`, `run_unchecked` must be
688 // used. We are responsible for maintaining the invariant that
689 // `run_unchecked` is only called on threads that spawned the
690 // task initially. Because `LocalSet` itself is `!Send`, and
691 // `spawn_local` spawns into the `LocalSet` on the current
692 // thread, the invariant is maintained.
693 Some(task) => crate::runtime::coop::budget(|| task.run()),
694 // We have fully drained the queue of notified tasks, so the
695 // local future doesn't need to be notified again — it can wait
696 // until something else wakes a task in the local set.
697 None => return false,
698 }
699 }
700
701 true
702 }
703
704 fn next_task(&self) -> Option<task::LocalNotified<Arc<Shared>>> {
705 let tick = self.tick.get();
706 self.tick.set(tick.wrapping_add(1));
707
708 let task = if tick % REMOTE_FIRST_INTERVAL == 0 {
709 self.context
710 .shared
711 .queue
712 .lock()
713 .as_mut()
714 .and_then(|queue| queue.pop_front())
715 .or_else(|| self.pop_local())
716 } else {
717 self.pop_local().or_else(|| {
718 self.context
719 .shared
720 .queue
721 .lock()
722 .as_mut()
723 .and_then(VecDeque::pop_front)
724 })
725 };
726
727 task.map(|task| unsafe {
728 // Safety: because the `LocalSet` itself is `!Send`, we know we are
729 // on the same thread if we have access to the `LocalSet`, and can
730 // therefore access the local run queue.
731 self.context.shared.local_state.assert_owner(task)
732 })
733 }
734
735 fn pop_local(&self) -> Option<task::Notified<Arc<Shared>>> {
736 unsafe {
737 // Safety: because the `LocalSet` itself is `!Send`, we know we are
738 // on the same thread if we have access to the `LocalSet`, and can
739 // therefore access the local run queue.
740 self.context.shared.local_state.task_pop_front()
741 }
742 }
743
744 fn with<T>(&self, f: impl FnOnce() -> T) -> T {
745 CURRENT.with(|local_data| {
746 let _guard = local_data.enter(self.context.clone());
747 f()
748 })
749 }
750
751 /// This method is like `with`, but it just calls `f` without setting the thread-local if that
752 /// fails.
753 fn with_if_possible<T>(&self, f: impl FnOnce() -> T) -> T {
754 let mut f = Some(f);
755
756 let res = CURRENT.try_with(|local_data| {
757 let _guard = local_data.enter(self.context.clone());
758 (f.take().unwrap())()
759 });
760
761 match res {
762 Ok(res) => res,
763 Err(_access_error) => (f.take().unwrap())(),
764 }
765 }
766 }
767
768 cfg_unstable! {
769 impl LocalSet {
770 /// Configure how the `LocalSet` responds to an unhandled panic on a
771 /// spawned task.
772 ///
773 /// By default, an unhandled panic (i.e. a panic not caught by
774 /// [`std::panic::catch_unwind`]) has no impact on the `LocalSet`'s
775 /// execution. The panic is error value is forwarded to the task's
776 /// [`JoinHandle`] and all other spawned tasks continue running.
777 ///
778 /// The `unhandled_panic` option enables configuring this behavior.
779 ///
780 /// * `UnhandledPanic::Ignore` is the default behavior. Panics on
781 /// spawned tasks have no impact on the `LocalSet`'s execution.
782 /// * `UnhandledPanic::ShutdownRuntime` will force the `LocalSet` to
783 /// shutdown immediately when a spawned task panics even if that
784 /// task's `JoinHandle` has not been dropped. All other spawned tasks
785 /// will immediately terminate and further calls to
786 /// [`LocalSet::block_on`] and [`LocalSet::run_until`] will panic.
787 ///
788 /// # Panics
789 ///
790 /// This method panics if called after the `LocalSet` has started
791 /// running.
792 ///
793 /// # Unstable
794 ///
795 /// This option is currently unstable and its implementation is
796 /// incomplete. The API may change or be removed in the future. See
797 /// tokio-rs/tokio#4516 for more details.
798 ///
799 /// # Examples
800 ///
801 /// The following demonstrates a `LocalSet` configured to shutdown on
802 /// panic. The first spawned task panics and results in the `LocalSet`
803 /// shutting down. The second spawned task never has a chance to
804 /// execute. The call to `run_until` will panic due to the runtime being
805 /// forcibly shutdown.
806 ///
807 /// ```should_panic
808 /// use tokio::runtime::UnhandledPanic;
809 ///
810 /// # #[tokio::main]
811 /// # async fn main() {
812 /// tokio::task::LocalSet::new()
813 /// .unhandled_panic(UnhandledPanic::ShutdownRuntime)
814 /// .run_until(async {
815 /// tokio::task::spawn_local(async { panic!("boom"); });
816 /// tokio::task::spawn_local(async {
817 /// // This task never completes
818 /// });
819 ///
820 /// // Do some work, but `run_until` will panic before it completes
821 /// # loop { tokio::task::yield_now().await; }
822 /// })
823 /// .await;
824 /// # }
825 /// ```
826 ///
827 /// [`JoinHandle`]: struct@crate::task::JoinHandle
828 pub fn unhandled_panic(&mut self, behavior: crate::runtime::UnhandledPanic) -> &mut Self {
829 // TODO: This should be set as a builder
830 Rc::get_mut(&mut self.context)
831 .and_then(|ctx| Arc::get_mut(&mut ctx.shared))
832 .expect("Unhandled Panic behavior modified after starting LocalSet")
833 .unhandled_panic = behavior;
834 self
835 }
836
837 /// Returns the [`Id`] of the current `LocalSet` runtime.
838 ///
839 /// # Examples
840 ///
841 /// ```rust
842 /// use tokio::task;
843 ///
844 /// #[tokio::main]
845 /// async fn main() {
846 /// let local_set = task::LocalSet::new();
847 /// println!("Local set id: {}", local_set.id());
848 /// }
849 /// ```
850 ///
851 /// **Note**: This is an [unstable API][unstable]. The public API of this type
852 /// may break in 1.x releases. See [the documentation on unstable
853 /// features][unstable] for details.
854 ///
855 /// [unstable]: crate#unstable-features
856 /// [`Id`]: struct@crate::runtime::Id
857 pub fn id(&self) -> runtime::Id {
858 self.context.shared.local_state.owned.id.into()
859 }
860 }
861 }
862
863 impl fmt::Debug for LocalSet {
864 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
865 fmt.debug_struct("LocalSet").finish()
866 }
867 }
868
869 impl Future for LocalSet {
870 type Output = ();
871
872 fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
873 // Register the waker before starting to work
874 self.context.shared.waker.register_by_ref(cx.waker());
875
876 if self.with(|| self.tick()) {
877 // If `tick` returns true, we need to notify the local future again:
878 // there are still tasks remaining in the run queue.
879 cx.waker().wake_by_ref();
880 Poll::Pending
881
882 // Safety: called from the thread that owns `LocalSet`. Because
883 // `LocalSet` is `!Send`, this is safe.
884 } else if unsafe { self.context.shared.local_state.owned_is_empty() } {
885 // If the scheduler has no remaining futures, we're done!
886 Poll::Ready(())
887 } else {
888 // There are still futures in the local set, but we've polled all the
889 // futures in the run queue. Therefore, we can just return Pending
890 // since the remaining futures will be woken from somewhere else.
891 Poll::Pending
892 }
893 }
894 }
895
896 impl Default for LocalSet {
897 fn default() -> LocalSet {
898 LocalSet::new()
899 }
900 }
901
902 impl Drop for LocalSet {
903 fn drop(&mut self) {
904 self.with_if_possible(|| {
905 // Shut down all tasks in the LocalOwnedTasks and close it to
906 // prevent new tasks from ever being added.
907 unsafe {
908 // Safety: called from the thread that owns `LocalSet`
909 self.context.shared.local_state.close_and_shutdown_all();
910 }
911
912 // We already called shutdown on all tasks above, so there is no
913 // need to call shutdown.
914
915 // Safety: note that this *intentionally* bypasses the unsafe
916 // `Shared::local_queue()` method. This is in order to avoid the
917 // debug assertion that we are on the thread that owns the
918 // `LocalSet`, because on some systems (e.g. at least some macOS
919 // versions), attempting to get the current thread ID can panic due
920 // to the thread's local data that stores the thread ID being
921 // dropped *before* the `LocalSet`.
922 //
923 // Despite avoiding the assertion here, it is safe for us to access
924 // the local queue in `Drop`, because the `LocalSet` itself is
925 // `!Send`, so we can reasonably guarantee that it will not be
926 // `Drop`ped from another thread.
927 let local_queue = unsafe {
928 // Safety: called from the thread that owns `LocalSet`
929 self.context.shared.local_state.take_local_queue()
930 };
931 for task in local_queue {
932 drop(task);
933 }
934
935 // Take the queue from the Shared object to prevent pushing
936 // notifications to it in the future.
937 let queue = self.context.shared.queue.lock().take().unwrap();
938 for task in queue {
939 drop(task);
940 }
941
942 // Safety: called from the thread that owns `LocalSet`
943 assert!(unsafe { self.context.shared.local_state.owned_is_empty() });
944 });
945 }
946 }
947
948 // === impl Context ===
949
950 impl Context {
951 #[track_caller]
952 fn spawn<F>(&self, future: F, name: Option<&str>) -> JoinHandle<F::Output>
953 where
954 F: Future + 'static,
955 F::Output: 'static,
956 {
957 let id = crate::runtime::task::Id::next();
958 let future = crate::util::trace::task(future, "local", name, id.as_u64());
959
960 // Safety: called from the thread that owns the `LocalSet`
961 let (handle, notified) = {
962 self.shared.local_state.assert_called_from_owner_thread();
963 self.shared
964 .local_state
965 .owned
966 .bind(future, self.shared.clone(), id)
967 };
968
969 if let Some(notified) = notified {
970 self.shared.schedule(notified);
971 }
972
973 handle
974 }
975 }
976
977 // === impl LocalFuture ===
978
979 impl<T: Future> Future for RunUntil<'_, T> {
980 type Output = T::Output;
981
982 fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
983 let me = self.project();
984
985 me.local_set.with(|| {
986 me.local_set
987 .context
988 .shared
989 .waker
990 .register_by_ref(cx.waker());
991
992 let _no_blocking = crate::runtime::context::disallow_block_in_place();
993 let f = me.future;
994
995 if let Poll::Ready(output) = f.poll(cx) {
996 return Poll::Ready(output);
997 }
998
999 if me.local_set.tick() {
1000 // If `tick` returns `true`, we need to notify the local future again:
1001 // there are still tasks remaining in the run queue.
1002 cx.waker().wake_by_ref();
1003 }
1004
1005 Poll::Pending
1006 })
1007 }
1008 }
1009
1010 impl Shared {
1011 /// Schedule the provided task on the scheduler.
1012 fn schedule(&self, task: task::Notified<Arc<Self>>) {
1013 CURRENT.with(|localdata| {
1014 match localdata.ctx.get() {
1015 // If the current `LocalSet` is being polled, we don't need to wake it.
1016 // When we `enter` it, then the value `wake_on_schedule` is set to be true.
1017 // In this case it is not being polled, so we need to wake it.
1018 Some(cx) if cx.shared.ptr_eq(self) && !localdata.wake_on_schedule.get() => unsafe {
1019 // Safety: if the current `LocalSet` context points to this
1020 // `LocalSet`, then we are on the thread that owns it.
1021 cx.shared.local_state.task_push_back(task);
1022 },
1023
1024 // We are on the thread that owns the `LocalSet`, so we can
1025 // wake to the local queue.
1026 _ if context::thread_id().ok() == Some(self.local_state.owner) => {
1027 unsafe {
1028 // Safety: we just checked that the thread ID matches
1029 // the localset's owner, so this is safe.
1030 self.local_state.task_push_back(task);
1031 }
1032 // We still have to wake the `LocalSet`, because it isn't
1033 // currently being polled.
1034 self.waker.wake();
1035 }
1036
1037 // We are *not* on the thread that owns the `LocalSet`, so we
1038 // have to wake to the remote queue.
1039 _ => {
1040 // First, check whether the queue is still there (if not, the
1041 // LocalSet is dropped). Then push to it if so, and if not,
1042 // do nothing.
1043 let mut lock = self.queue.lock();
1044
1045 if let Some(queue) = lock.as_mut() {
1046 queue.push_back(task);
1047 drop(lock);
1048 self.waker.wake();
1049 }
1050 }
1051 }
1052 });
1053 }
1054
1055 fn ptr_eq(&self, other: &Shared) -> bool {
1056 std::ptr::eq(self, other)
1057 }
1058 }
1059
1060 // This is safe because (and only because) we *pinky pwomise* to never touch the
1061 // local run queue except from the thread that owns the `LocalSet`.
1062 unsafe impl Sync for Shared {}
1063
1064 impl task::Schedule for Arc<Shared> {
1065 fn release(&self, task: &Task<Self>) -> Option<Task<Self>> {
1066 // Safety, this is always called from the thread that owns `LocalSet`
1067 unsafe { self.local_state.task_remove(task) }
1068 }
1069
1070 fn schedule(&self, task: task::Notified<Self>) {
1071 Shared::schedule(self, task);
1072 }
1073
1074 cfg_unstable! {
1075 fn unhandled_panic(&self) {
1076 use crate::runtime::UnhandledPanic;
1077
1078 match self.unhandled_panic {
1079 UnhandledPanic::Ignore => {
1080 // Do nothing
1081 }
1082 UnhandledPanic::ShutdownRuntime => {
1083 // This hook is only called from within the runtime, so
1084 // `CURRENT` should match with `&self`, i.e. there is no
1085 // opportunity for a nested scheduler to be called.
1086 CURRENT.with(|LocalData { ctx, .. }| match ctx.get() {
1087 Some(cx) if Arc::ptr_eq(self, &cx.shared) => {
1088 cx.unhandled_panic.set(true);
1089 // Safety: this is always called from the thread that owns `LocalSet`
1090 unsafe { cx.shared.local_state.close_and_shutdown_all(); }
1091 }
1092 _ => unreachable!("runtime core not set in CURRENT thread-local"),
1093 })
1094 }
1095 }
1096 }
1097 }
1098 }
1099
1100 impl LocalState {
1101 unsafe fn task_pop_front(&self) -> Option<task::Notified<Arc<Shared>>> {
1102 // The caller ensures it is called from the same thread that owns
1103 // the LocalSet.
1104 self.assert_called_from_owner_thread();
1105
1106 self.local_queue.with_mut(|ptr| (*ptr).pop_front())
1107 }
1108
1109 unsafe fn task_push_back(&self, task: task::Notified<Arc<Shared>>) {
1110 // The caller ensures it is called from the same thread that owns
1111 // the LocalSet.
1112 self.assert_called_from_owner_thread();
1113
1114 self.local_queue.with_mut(|ptr| (*ptr).push_back(task));
1115 }
1116
1117 unsafe fn take_local_queue(&self) -> VecDeque<task::Notified<Arc<Shared>>> {
1118 // The caller ensures it is called from the same thread that owns
1119 // the LocalSet.
1120 self.assert_called_from_owner_thread();
1121
1122 self.local_queue.with_mut(|ptr| std::mem::take(&mut (*ptr)))
1123 }
1124
1125 unsafe fn task_remove(&self, task: &Task<Arc<Shared>>) -> Option<Task<Arc<Shared>>> {
1126 // The caller ensures it is called from the same thread that owns
1127 // the LocalSet.
1128 self.assert_called_from_owner_thread();
1129
1130 self.owned.remove(task)
1131 }
1132
1133 /// Returns true if the `LocalSet` does not have any spawned tasks
1134 unsafe fn owned_is_empty(&self) -> bool {
1135 // The caller ensures it is called from the same thread that owns
1136 // the LocalSet.
1137 self.assert_called_from_owner_thread();
1138
1139 self.owned.is_empty()
1140 }
1141
1142 unsafe fn assert_owner(
1143 &self,
1144 task: task::Notified<Arc<Shared>>,
1145 ) -> task::LocalNotified<Arc<Shared>> {
1146 // The caller ensures it is called from the same thread that owns
1147 // the LocalSet.
1148 self.assert_called_from_owner_thread();
1149
1150 self.owned.assert_owner(task)
1151 }
1152
1153 unsafe fn close_and_shutdown_all(&self) {
1154 // The caller ensures it is called from the same thread that owns
1155 // the LocalSet.
1156 self.assert_called_from_owner_thread();
1157
1158 self.owned.close_and_shutdown_all();
1159 }
1160
1161 #[track_caller]
1162 fn assert_called_from_owner_thread(&self) {
1163 // FreeBSD has some weirdness around thread-local destruction.
1164 // TODO: remove this hack when thread id is cleaned up
1165 #[cfg(not(any(target_os = "openbsd", target_os = "freebsd")))]
1166 debug_assert!(
1167 // if we couldn't get the thread ID because we're dropping the local
1168 // data, skip the assertion --- the `Drop` impl is not going to be
1169 // called from another thread, because `LocalSet` is `!Send`
1170 context::thread_id()
1171 .map(|id| id == self.owner)
1172 .unwrap_or(true),
1173 "`LocalSet`'s local run queue must not be accessed by another thread!"
1174 );
1175 }
1176 }
1177
1178 // This is `Send` because it is stored in `Shared`. It is up to the caller to
1179 // ensure they are on the same thread that owns the `LocalSet`.
1180 unsafe impl Send for LocalState {}
1181
1182 #[cfg(all(test, not(loom)))]
1183 mod tests {
1184 use super::*;
1185
1186 // Does a `LocalSet` running on a current-thread runtime...basically work?
1187 //
1188 // This duplicates a test in `tests/task_local_set.rs`, but because this is
1189 // a lib test, it will run under Miri, so this is necessary to catch stacked
1190 // borrows violations in the `LocalSet` implementation.
1191 #[test]
1192 fn local_current_thread_scheduler() {
1193 let f = async {
1194 LocalSet::new()
1195 .run_until(async {
1196 spawn_local(async {}).await.unwrap();
1197 })
1198 .await;
1199 };
1200 crate::runtime::Builder::new_current_thread()
1201 .build()
1202 .expect("rt")
1203 .block_on(f)
1204 }
1205
1206 // Tests that when a task on a `LocalSet` is woken by an io driver on the
1207 // same thread, the task is woken to the localset's local queue rather than
1208 // its remote queue.
1209 //
1210 // This test has to be defined in the `local.rs` file as a lib test, rather
1211 // than in `tests/`, because it makes assertions about the local set's
1212 // internal state.
1213 #[test]
1214 fn wakes_to_local_queue() {
1215 use super::*;
1216 use crate::sync::Notify;
1217 let rt = crate::runtime::Builder::new_current_thread()
1218 .build()
1219 .expect("rt");
1220 rt.block_on(async {
1221 let local = LocalSet::new();
1222 let notify = Arc::new(Notify::new());
1223 let task = local.spawn_local({
1224 let notify = notify.clone();
1225 async move {
1226 notify.notified().await;
1227 }
1228 });
1229 let mut run_until = Box::pin(local.run_until(async move {
1230 task.await.unwrap();
1231 }));
1232
1233 // poll the run until future once
1234 crate::future::poll_fn(|cx| {
1235 let _ = run_until.as_mut().poll(cx);
1236 Poll::Ready(())
1237 })
1238 .await;
1239
1240 notify.notify_one();
1241 let task = unsafe { local.context.shared.local_state.task_pop_front() };
1242 // TODO(eliza): it would be nice to be able to assert that this is
1243 // the local task.
1244 assert!(
1245 task.is_some(),
1246 "task should have been notified to the LocalSet's local queue"
1247 );
1248 })
1249 }
1250 }