Skip to main content

tokio/task/
local.rs

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