tokio/runtime/task/mod.rs
1//! The task module.
2//!
3//! The task module contains the code that manages spawned tasks and provides a
4//! safe API for the rest of the runtime to use. Each task in a runtime is
5//! stored in an `OwnedTasks` or `LocalOwnedTasks` object.
6//!
7//! # Task reference types
8//!
9//! A task is usually referenced by multiple handles, and there are several
10//! types of handles.
11//!
12//! * `OwnedTask` - tasks stored in an `OwnedTasks` or `LocalOwnedTasks` are of this
13//! reference type.
14//!
15//! * `JoinHandle` - each task has a `JoinHandle` that allows access to the output
16//! of the task.
17//!
18//! * `Waker` - every waker for a task has this reference type. There can be any
19//! number of waker references.
20//!
21//! * `Notified` - tracks whether the task is notified.
22//!
23//! * `Unowned` - this task reference type is used for tasks not stored in any
24//! runtime. Mainly used for blocking tasks, but also in tests.
25//!
26//! The task uses a reference count to keep track of how many active references
27//! exist. The `Unowned` reference type takes up two ref-counts. All other
28//! reference types take up a single ref-count.
29//!
30//! Besides the waker type, each task has at most one of each reference type.
31//!
32//! # State
33//!
34//! The task stores its state in an atomic `usize` with various bitfields for the
35//! necessary information. The state has the following bitfields:
36//!
37//! * `RUNNING` - Tracks whether the task is currently being polled or cancelled.
38//! This bit functions as a lock around the task.
39//!
40//! * `COMPLETE` - Is one once the future has fully completed and has been
41//! dropped. Never unset once set. Never set together with RUNNING.
42//!
43//! * `NOTIFIED` - Tracks whether a Notified object currently exists.
44//!
45//! * `CANCELLED` - Is set to one for tasks that should be cancelled as soon as
46//! possible. May take any value for completed tasks.
47//!
48//! * `JOIN_INTEREST` - Is set to one if there exists a `JoinHandle`.
49//!
50//! * `JOIN_WAKER` - Acts as an access control bit for the join handle waker. The
51//! protocol for its usage is described below.
52//!
53//! The rest of the bits are used for the ref-count.
54//!
55//! # Fields in the task
56//!
57//! The task has various fields. This section describes how and when it is safe
58//! to access a field.
59//!
60//! * The state field is accessed with atomic instructions.
61//!
62//! * The `OwnedTask` reference has exclusive access to the `owned` field.
63//!
64//! * The Notified reference has exclusive access to the `queue_next` field.
65//!
66//! * The `owner_id` field can be set as part of construction of the task, but
67//! is otherwise immutable and anyone can access the field immutably without
68//! synchronization.
69//!
70//! * If COMPLETE is one, then the `JoinHandle` has exclusive access to the
71//! stage field. If COMPLETE is zero, then the RUNNING bitfield functions as
72//! a lock for the stage field, and it can be accessed only by the thread
73//! that set RUNNING to one.
74//!
75//! * The waker field may be concurrently accessed by different threads: in one
76//! thread the runtime may complete a task and *read* the waker field to
77//! invoke the waker, and in another thread the task's `JoinHandle` may be
78//! polled, and if the task hasn't yet completed, the `JoinHandle` may *write*
79//! a waker to the waker field. The `JOIN_WAKER` bit ensures safe access by
80//! multiple threads to the waker field using the following rules:
81//!
82//! 1. `JOIN_WAKER` is initialized to zero.
83//!
84//! 2. If `JOIN_WAKER` is zero, then the `JoinHandle` has exclusive (mutable)
85//! access to the waker field.
86//!
87//! 3. If `JOIN_WAKER` is one, then the `JoinHandle` has shared (read-only)
88//! access to the waker field.
89//!
90//! 4. If `JOIN_WAKER` is one and COMPLETE is one, then the runtime has shared
91//! (read-only) access to the waker field.
92//!
93//! 5. If the `JoinHandle` needs to write to the waker field, then the
94//! `JoinHandle` needs to (i) successfully set `JOIN_WAKER` to zero if it is
95//! not already zero to gain exclusive access to the waker field per rule
96//! 2, (ii) write a waker, and (iii) successfully set `JOIN_WAKER` to one.
97//! If the `JoinHandle` unsets `JOIN_WAKER` in the process of being dropped
98//! to clear the waker field, only steps (i) and (ii) are relevant.
99//!
100//! 6. The `JoinHandle` can change `JOIN_WAKER` only if COMPLETE is zero (i.e.
101//! the task hasn't yet completed). The runtime can change `JOIN_WAKER` only
102//! if COMPLETE is one.
103//!
104//! 7. If `JOIN_INTEREST` is zero and COMPLETE is one, then the runtime has
105//! exclusive (mutable) access to the waker field. This might happen if the
106//! `JoinHandle` gets dropped right after the task completes and the runtime
107//! sets the `COMPLETE` bit. In this case the runtime needs the mutable access
108//! to the waker field to drop it.
109//!
110//! Rule 6 implies that the steps (i) or (iii) of rule 5 may fail due to a
111//! race. If step (i) fails, then the attempt to write a waker is aborted. If
112//! step (iii) fails because COMPLETE is set to one by another thread after
113//! step (i), then the waker field is cleared. Once COMPLETE is one (i.e.
114//! task has completed), the `JoinHandle` will not modify `JOIN_WAKER`. After the
115//! runtime sets COMPLETE to one, it invokes the waker if there is one so in this
116//! case when a task completes the `JOIN_WAKER` bit implicates to the runtime
117//! whether it should invoke the waker or not. After the runtime is done with
118//! using the waker during task completion, it unsets the `JOIN_WAKER` bit to give
119//! the `JoinHandle` exclusive access again so that it is able to drop the waker
120//! at a later point.
121//!
122//! All other fields are immutable and can be accessed immutably without
123//! synchronization by anyone.
124//!
125//! # Safety
126//!
127//! This section goes through various situations and explains why the API is
128//! safe in that situation.
129//!
130//! ## Polling or dropping the future
131//!
132//! Any mutable access to the future happens after obtaining a lock by modifying
133//! the RUNNING field, so exclusive access is ensured.
134//!
135//! When the task completes, exclusive access to the output is transferred to
136//! the `JoinHandle`. If the `JoinHandle` is already dropped when the transition to
137//! complete happens, the thread performing that transition retains exclusive
138//! access to the output and should immediately drop it.
139//!
140//! ## Non-Send futures
141//!
142//! If a future is not Send, then it is bound to a `LocalOwnedTasks`. The future
143//! will only ever be polled or dropped given a `LocalNotified` or inside a call
144//! to `LocalOwnedTasks::shutdown_all`. In either case, it is guaranteed that the
145//! future is on the right thread.
146//!
147//! If the task is never removed from the `LocalOwnedTasks`, then it is leaked, so
148//! there is no risk that the task is dropped on some other thread when the last
149//! ref-count drops.
150//!
151//! ## Non-Send output
152//!
153//! When a task completes, the output is placed in the stage of the task. Then,
154//! a transition that sets COMPLETE to true is performed, and the value of
155//! `JOIN_INTEREST` when this transition happens is read.
156//!
157//! If `JOIN_INTEREST` is zero when the transition to COMPLETE happens, then the
158//! output is immediately dropped.
159//!
160//! If `JOIN_INTEREST` is one when the transition to COMPLETE happens, then the
161//! `JoinHandle` is responsible for cleaning up the output. If the output is not
162//! Send, then this happens:
163//!
164//! 1. The output is created on the thread that the future was polled on. Since
165//! only non-Send futures can have non-Send output, the future was polled on
166//! the thread that the future was spawned from.
167//! 2. Since `JoinHandle<Output>` is not Send if Output is not Send, the
168//! `JoinHandle` is also on the thread that the future was spawned from.
169//! 3. Thus, the `JoinHandle` will not move the output across threads when it
170//! takes or drops the output.
171//!
172//! ## Recursive poll/shutdown
173//!
174//! Calling poll from inside a shutdown call or vice-versa is not prevented by
175//! the API exposed by the task module, so this has to be safe. In either case,
176//! the lock in the RUNNING bitfield makes the inner call return immediately. If
177//! the inner call is a `shutdown` call, then the CANCELLED bit is set, and the
178//! poll call will notice it when the poll finishes, and the task is cancelled
179//! at that point.
180
181mod core;
182use self::core::Cell;
183use self::core::Header;
184
185mod error;
186pub use self::error::JoinError;
187
188mod harness;
189use self::harness::Harness;
190
191mod id;
192pub use id::{id, try_id, Id};
193
194#[cfg(feature = "rt")]
195mod abort;
196mod join;
197
198#[cfg(feature = "rt")]
199pub use self::abort::AbortHandle;
200
201pub use self::join::JoinHandle;
202
203mod list;
204pub(crate) use self::list::{LocalOwnedTasks, OwnedTasks};
205
206mod raw;
207pub(crate) use self::raw::RawTask;
208
209mod state;
210use self::state::State;
211
212mod waker;
213
214pub(crate) use self::spawn_location::SpawnLocation;
215
216cfg_taskdump! {
217 pub(crate) mod trace;
218}
219
220use crate::future::Future;
221use crate::util::linked_list;
222use crate::util::sharded_list;
223
224use crate::runtime::metrics::ScheduleLatencyInstant;
225use crate::runtime::TaskCallback;
226use std::marker::PhantomData;
227use std::panic::Location;
228use std::ptr::NonNull;
229use std::{fmt, mem};
230
231/// An owned handle to the task, tracked by ref count.
232#[repr(transparent)]
233pub(crate) struct Task<S: 'static> {
234 raw: RawTask,
235 _p: PhantomData<S>,
236}
237
238unsafe impl<S> Send for Task<S> {}
239unsafe impl<S> Sync for Task<S> {}
240
241/// A task was notified.
242#[repr(transparent)]
243pub(crate) struct Notified<S: 'static>(Task<S>);
244
245impl<S> Notified<S> {
246 #[cfg(all(tokio_unstable, feature = "rt-multi-thread"))]
247 #[inline]
248 pub(crate) fn task_meta<'meta>(&self) -> crate::runtime::TaskMeta<'meta> {
249 self.0.task_meta()
250 }
251
252 pub(crate) fn set_scheduled_at(&self, scheduled_at: ScheduleLatencyInstant) {
253 // SAFETY: There are no concurrent writes because there is only ever one `Notified`
254 // reference per task. There are no concurrent reads because this field is only read
255 // when polling the task, which can only happen after it's scheduled.
256 unsafe {
257 self.0.header().set_scheduled_at(scheduled_at);
258 }
259 }
260}
261
262// safety: This type cannot be used to touch the task without first verifying
263// that the value is on a thread where it is safe to poll the task.
264unsafe impl<S: Schedule> Send for Notified<S> {}
265unsafe impl<S: Schedule> Sync for Notified<S> {}
266
267/// A non-Send variant of Notified with the invariant that it is on a thread
268/// where it is safe to poll it.
269#[repr(transparent)]
270pub(crate) struct LocalNotified<S: 'static> {
271 task: Task<S>,
272 _not_send: PhantomData<*const ()>,
273}
274
275impl<S> LocalNotified<S> {
276 #[cfg(tokio_unstable)]
277 #[inline]
278 pub(crate) fn task_meta<'meta>(&self) -> crate::runtime::TaskMeta<'meta> {
279 self.task.task_meta()
280 }
281
282 pub(crate) fn get_scheduled_at(&self) -> ScheduleLatencyInstant {
283 self.task.header().get_scheduled_at()
284 }
285}
286
287/// A task that is not owned by any `OwnedTasks`. Used for blocking tasks.
288/// This type holds two ref-counts.
289pub(crate) struct UnownedTask<S: 'static> {
290 raw: RawTask,
291 _p: PhantomData<S>,
292}
293
294// safety: This type can only be created given a Send task.
295unsafe impl<S> Send for UnownedTask<S> {}
296unsafe impl<S> Sync for UnownedTask<S> {}
297
298/// Task result sent back.
299pub(crate) type Result<T> = std::result::Result<T, JoinError>;
300
301/// Hooks for scheduling tasks which are needed in the task harness.
302#[derive(Clone)]
303pub(crate) struct TaskHarnessScheduleHooks {
304 pub(crate) task_terminate_callback: Option<TaskCallback>,
305}
306
307pub(crate) trait Schedule: Sync + Sized + 'static {
308 /// The task has completed work and is ready to be released. The scheduler
309 /// should release it immediately and return it. The task module will batch
310 /// the ref-dec with setting other options.
311 ///
312 /// If the scheduler has already released the task, then None is returned.
313 fn release(&self, task: &Task<Self>) -> Option<Task<Self>>;
314
315 /// Schedule the task
316 fn schedule(&self, task: Notified<Self>);
317
318 fn hooks(&self) -> TaskHarnessScheduleHooks;
319
320 /// Schedule the task to run in the near future, yielding the thread to
321 /// other tasks.
322 fn yield_now(&self, task: Notified<Self>) {
323 self.schedule(task);
324 }
325
326 /// Polling the task resulted in a panic. Should the runtime shutdown?
327 fn unhandled_panic(&self) {
328 // By default, do nothing. This maintains the 1.0 behavior.
329 }
330}
331
332cfg_rt! {
333 /// This is the constructor for a new task. Three references to the task are
334 /// created. The first task reference is usually put into an `OwnedTasks`
335 /// immediately. The Notified is sent to the scheduler as an ordinary
336 /// notification.
337 fn new_task<T, S>(
338 task: T,
339 scheduler: S,
340 id: Id,
341 spawned_at: SpawnLocation,
342 ) -> (Task<S>, Notified<S>, JoinHandle<T::Output>)
343 where
344 S: Schedule,
345 T: Future + 'static,
346 T::Output: 'static,
347 {
348 let raw = RawTask::new::<T, S>(
349 task,
350 scheduler,
351 id,
352 spawned_at,
353 );
354 let task = Task {
355 raw,
356 _p: PhantomData,
357 };
358 let notified = Notified(Task {
359 raw,
360 _p: PhantomData,
361 });
362 let join = JoinHandle::new(raw);
363
364 (task, notified, join)
365 }
366
367 /// Creates a new task with an associated join handle. This method is used
368 /// only when the task is not going to be stored in an `OwnedTasks` list.
369 ///
370 /// Currently only blocking tasks use this method.
371 pub(crate) fn unowned<T, S>(
372 task: T,
373 scheduler: S,
374 id: Id,
375 spawned_at: SpawnLocation,
376 ) -> (UnownedTask<S>, JoinHandle<T::Output>)
377 where
378 S: Schedule,
379 T: Send + Future + 'static,
380 T::Output: Send + 'static,
381 {
382 let (task, notified, join) = new_task(
383 task,
384 scheduler,
385 id,
386 spawned_at,
387 );
388
389 // This transfers the ref-count of task and notified into an UnownedTask.
390 // This is valid because an UnownedTask holds two ref-counts.
391 let unowned = UnownedTask {
392 raw: task.raw,
393 _p: PhantomData,
394 };
395 std::mem::forget(task);
396 std::mem::forget(notified);
397
398 (unowned, join)
399 }
400}
401
402impl<S: 'static> Task<S> {
403 unsafe fn new(raw: RawTask) -> Task<S> {
404 Task {
405 raw,
406 _p: PhantomData,
407 }
408 }
409
410 /// # Safety
411 ///
412 /// `ptr` must be a valid pointer to a [`Header`].
413 unsafe fn from_raw(ptr: NonNull<Header>) -> Task<S> {
414 unsafe { Task::new(RawTask::from_raw(ptr)) }
415 }
416
417 cfg_taskdump! {
418 pub(super) fn as_raw(&self) -> RawTask {
419 self.raw
420 }
421 }
422
423 fn header(&self) -> &Header {
424 self.raw.header()
425 }
426
427 fn header_ptr(&self) -> NonNull<Header> {
428 self.raw.header_ptr()
429 }
430
431 /// Returns a [task ID] that uniquely identifies this task relative to other
432 /// currently spawned tasks.
433 ///
434 /// [task ID]: crate::task::Id
435 #[cfg(tokio_unstable)]
436 pub(crate) fn id(&self) -> crate::task::Id {
437 // Safety: The header pointer is valid.
438 unsafe { Header::get_id(self.raw.header_ptr()) }
439 }
440
441 #[cfg(tokio_unstable)]
442 pub(crate) fn spawned_at(&self) -> &'static Location<'static> {
443 // Safety: The header pointer is valid.
444 unsafe { Header::get_spawn_location(self.raw.header_ptr()) }
445 }
446
447 // Explicit `'task` and `'meta` lifetimes are necessary here, as otherwise,
448 // the compiler infers the lifetimes to be the same, and considers the task
449 // to be borrowed for the lifetime of the returned `TaskMeta`.
450 #[cfg(tokio_unstable)]
451 pub(crate) fn task_meta<'meta>(&self) -> crate::runtime::TaskMeta<'meta> {
452 crate::runtime::TaskMeta {
453 id: self.id(),
454 spawned_at: self.spawned_at().into(),
455 _phantom: PhantomData,
456 }
457 }
458
459 cfg_taskdump! {
460 /// Notify the task for task dumping.
461 ///
462 /// Returns `None` if the task has already been notified.
463 pub(super) fn notify_for_tracing(&self) -> Option<Notified<S>> {
464 if self.as_raw().state().transition_to_notified_for_tracing() {
465 // SAFETY: `transition_to_notified_for_tracing` increments the
466 // refcount.
467 Some(unsafe { Notified(Task::new(self.raw)) })
468 } else {
469 None
470 }
471 }
472
473 }
474}
475
476impl<S: 'static> Notified<S> {
477 fn header(&self) -> &Header {
478 self.0.header()
479 }
480
481 #[cfg(tokio_unstable)]
482 #[allow(dead_code)]
483 pub(crate) fn task_id(&self) -> crate::task::Id {
484 self.0.id()
485 }
486}
487
488impl<S: 'static> Notified<S> {
489 /// # Safety
490 ///
491 /// [`RawTask::ptr`] must be a valid pointer to a [`Header`].
492 pub(crate) unsafe fn from_raw(ptr: RawTask) -> Notified<S> {
493 Notified(unsafe { Task::new(ptr) })
494 }
495}
496
497impl<S: 'static> Notified<S> {
498 pub(crate) fn into_raw(self) -> RawTask {
499 let raw = self.0.raw;
500 mem::forget(self);
501 raw
502 }
503}
504
505impl<S: Schedule> Task<S> {
506 /// Preemptively cancels the task as part of the shutdown process.
507 pub(crate) fn shutdown(self) {
508 let raw = self.raw;
509 mem::forget(self);
510 raw.shutdown();
511 }
512}
513
514impl<S: Schedule> LocalNotified<S> {
515 /// Runs the task.
516 pub(crate) fn run(self) {
517 let raw = self.task.raw;
518 mem::forget(self);
519 raw.poll();
520 }
521
522 cfg_taskdump! {
523 /// Returns a `WakerRef` borrowing from this task.
524 ///
525 /// `WakerRef` derefs to `Waker` without bumping the task's refcount.
526 pub(crate) fn waker_ref(&self) -> waker::WakerRef<'_, S> {
527 waker::waker_ref::<S>(self.task.raw.header_ptr_ref())
528 }
529 }
530}
531
532impl<S: Schedule> UnownedTask<S> {
533 // Used in test of the inject queue.
534 #[cfg(test)]
535 #[cfg_attr(target_family = "wasm", allow(dead_code))]
536 pub(super) fn into_notified(self) -> Notified<S> {
537 Notified(self.into_task())
538 }
539
540 fn into_task(self) -> Task<S> {
541 // Convert into a task.
542 let task = Task {
543 raw: self.raw,
544 _p: PhantomData,
545 };
546 mem::forget(self);
547
548 // Drop a ref-count since an UnownedTask holds two.
549 task.header().state.ref_dec();
550
551 task
552 }
553
554 pub(crate) fn run(self) {
555 let raw = self.raw;
556 mem::forget(self);
557
558 // Transfer one ref-count to a Task object.
559 let task = Task::<S> {
560 raw,
561 _p: PhantomData,
562 };
563
564 // Use the other ref-count to poll the task.
565 raw.poll();
566 // Decrement our extra ref-count
567 drop(task);
568 }
569
570 pub(crate) fn shutdown(self) {
571 self.into_task().shutdown();
572 }
573}
574
575impl<S: 'static> Drop for Task<S> {
576 fn drop(&mut self) {
577 // Decrement the ref count
578 if self.header().state.ref_dec() {
579 // Deallocate if this is the final ref count
580 self.raw.dealloc();
581 }
582 }
583}
584
585impl<S: 'static> Drop for UnownedTask<S> {
586 fn drop(&mut self) {
587 // Decrement the ref count
588 if self.raw.header().state.ref_dec_twice() {
589 // Deallocate if this is the final ref count
590 self.raw.dealloc();
591 }
592 }
593}
594
595impl<S> fmt::Debug for Task<S> {
596 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
597 write!(fmt, "Task({:p})", self.header())
598 }
599}
600
601impl<S> fmt::Debug for Notified<S> {
602 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
603 write!(fmt, "task::Notified({:p})", self.0.header())
604 }
605}
606
607/// # Safety
608///
609/// Tasks are pinned.
610unsafe impl<S> linked_list::Link for Task<S> {
611 type Handle = Task<S>;
612 type Target = Header;
613
614 fn as_raw(handle: &Task<S>) -> NonNull<Header> {
615 handle.raw.header_ptr()
616 }
617
618 unsafe fn from_raw(ptr: NonNull<Header>) -> Task<S> {
619 unsafe { Task::from_raw(ptr) }
620 }
621
622 unsafe fn pointers(target: NonNull<Header>) -> NonNull<linked_list::Pointers<Header>> {
623 unsafe { self::core::Trailer::addr_of_owned(Header::get_trailer(target)) }
624 }
625}
626
627/// # Safety
628///
629/// The id of a task is never changed after creation of the task, so the return value of
630/// `get_shard_id` will not change. (The cast may throw away the upper 32 bits of the task id, but
631/// the shard id still won't change from call to call.)
632unsafe impl<S> sharded_list::ShardedListItem for Task<S> {
633 unsafe fn get_shard_id(target: NonNull<Self::Target>) -> usize {
634 // SAFETY: The caller guarantees that `target` points at a valid task.
635 let task_id = unsafe { Header::get_id(target) };
636 task_id.0.get() as usize
637 }
638}
639
640/// Wrapper around [`std::panic::Location`] that's conditionally compiled out
641/// when `tokio_unstable` is not enabled.
642#[cfg(tokio_unstable)]
643mod spawn_location {
644
645 use std::panic::Location;
646
647 #[derive(Copy, Clone)]
648 pub(crate) struct SpawnLocation(pub &'static Location<'static>);
649
650 impl From<&'static Location<'static>> for SpawnLocation {
651 fn from(location: &'static Location<'static>) -> Self {
652 Self(location)
653 }
654 }
655}
656
657#[cfg(not(tokio_unstable))]
658mod spawn_location {
659 use std::panic::Location;
660
661 #[derive(Copy, Clone)]
662 pub(crate) struct SpawnLocation();
663
664 impl From<&'static Location<'static>> for SpawnLocation {
665 fn from(_: &'static Location<'static>) -> Self {
666 Self()
667 }
668 }
669
670 #[cfg(test)]
671 #[test]
672 fn spawn_location_is_zero_sized() {
673 assert_eq!(std::mem::size_of::<SpawnLocation>(), 0);
674 }
675}
676
677impl SpawnLocation {
678 #[track_caller]
679 #[inline]
680 pub(crate) fn capture() -> Self {
681 Self::from(Location::caller())
682 }
683}