| 1 |
use crate::runtime::BOX_FUTURE_THRESHOLD; |
| 2 |
use crate::task::JoinHandle; |
| 3 |
|
| 4 |
use std::future::Future; |
| 5 |
|
| 6 |
cfg_rt! { |
| 7 |
/// Spawns a new asynchronous task, returning a |
| 8 |
/// [`JoinHandle`](super::JoinHandle) for it. |
| 9 |
/// |
| 10 |
/// The provided future will start running in the background immediately |
| 11 |
/// when `spawn` is called, even if you don't await the returned |
| 12 |
/// `JoinHandle`. |
| 13 |
/// |
| 14 |
/// Spawning a task enables the task to execute concurrently to other tasks. The |
| 15 |
/// spawned task may execute on the current thread, or it may be sent to a |
| 16 |
/// different thread to be executed. The specifics depend on the current |
| 17 |
/// [`Runtime`](crate::runtime::Runtime) configuration. |
| 18 |
/// |
| 19 |
/// It is guaranteed that spawn will not synchronously poll the task being spawned. |
| 20 |
/// This means that calling spawn while holding a lock does not pose a risk of |
| 21 |
/// deadlocking with the spawned task. |
| 22 |
/// |
| 23 |
/// There is no guarantee that a spawned task will execute to completion. |
| 24 |
/// When a runtime is shutdown, all outstanding tasks are dropped, |
| 25 |
/// regardless of the lifecycle of that task. |
| 26 |
/// |
| 27 |
/// This function must be called from the context of a Tokio runtime. Tasks running on |
| 28 |
/// the Tokio runtime are always inside its context, but you can also enter the context |
| 29 |
/// using the [`Runtime::enter`](crate::runtime::Runtime::enter()) method. |
| 30 |
/// |
| 31 |
/// # Examples |
| 32 |
/// |
| 33 |
/// In this example, a server is started and `spawn` is used to start a new task |
| 34 |
/// that processes each received connection. |
| 35 |
/// |
| 36 |
/// ```no_run |
| 37 |
/// use tokio::net::{TcpListener, TcpStream}; |
| 38 |
/// |
| 39 |
/// use std::io; |
| 40 |
/// |
| 41 |
/// async fn process(socket: TcpStream) { |
| 42 |
/// // ... |
| 43 |
/// # drop(socket); |
| 44 |
/// } |
| 45 |
/// |
| 46 |
/// #[tokio::main] |
| 47 |
/// async fn main() -> io::Result<()> { |
| 48 |
/// let listener = TcpListener::bind("127.0.0.1:8080").await?; |
| 49 |
/// |
| 50 |
/// loop { |
| 51 |
/// let (socket, _) = listener.accept().await?; |
| 52 |
/// |
| 53 |
/// tokio::spawn(async move { |
| 54 |
/// // Process each socket concurrently. |
| 55 |
/// process(socket).await |
| 56 |
/// }); |
| 57 |
/// } |
| 58 |
/// } |
| 59 |
/// ``` |
| 60 |
/// |
| 61 |
/// To run multiple tasks in parallel and receive their results, join |
| 62 |
/// handles can be stored in a vector. |
| 63 |
/// ``` |
| 64 |
/// # #[tokio::main(flavor = "current_thread")] async fn main() { |
| 65 |
/// async fn my_background_op(id: i32) -> String { |
| 66 |
/// let s = format!("Starting background task {}.", id); |
| 67 |
/// println!("{}", s); |
| 68 |
/// s |
| 69 |
/// } |
| 70 |
/// |
| 71 |
/// let ops = vec![1, 2, 3]; |
| 72 |
/// let mut tasks = Vec::with_capacity(ops.len()); |
| 73 |
/// for op in ops { |
| 74 |
/// // This call will make them start running in the background |
| 75 |
/// // immediately. |
| 76 |
/// tasks.push(tokio::spawn(my_background_op(op))); |
| 77 |
/// } |
| 78 |
/// |
| 79 |
/// let mut outputs = Vec::with_capacity(tasks.len()); |
| 80 |
/// for task in tasks { |
| 81 |
/// outputs.push(task.await.unwrap()); |
| 82 |
/// } |
| 83 |
/// println!("{:?}", outputs); |
| 84 |
/// # } |
| 85 |
/// ``` |
| 86 |
/// This example pushes the tasks to `outputs` in the order they were |
| 87 |
/// started in. If you do not care about the ordering of the outputs, then |
| 88 |
/// you can also use a [`JoinSet`]. |
| 89 |
/// |
| 90 |
/// [`JoinSet`]: struct@crate::task::JoinSet |
| 91 |
/// |
| 92 |
/// # Panics |
| 93 |
/// |
| 94 |
/// Panics if called from **outside** of the Tokio runtime. |
| 95 |
/// |
| 96 |
/// # Using `!Send` values from a task |
| 97 |
/// |
| 98 |
/// The task supplied to `spawn` must implement `Send`. However, it is |
| 99 |
/// possible to **use** `!Send` values from the task as long as they only |
| 100 |
/// exist between calls to `.await`. |
| 101 |
/// |
| 102 |
/// For example, this will work: |
| 103 |
/// |
| 104 |
/// ``` |
| 105 |
/// use tokio::task; |
| 106 |
/// |
| 107 |
/// use std::rc::Rc; |
| 108 |
/// |
| 109 |
/// fn use_rc(rc: Rc<()>) { |
| 110 |
/// // Do stuff w/ rc |
| 111 |
/// # drop(rc); |
| 112 |
/// } |
| 113 |
/// |
| 114 |
/// #[tokio::main] |
| 115 |
/// async fn main() { |
| 116 |
/// tokio::spawn(async { |
| 117 |
/// // Force the `Rc` to stay in a scope with no `.await` |
| 118 |
/// { |
| 119 |
/// let rc = Rc::new(()); |
| 120 |
/// use_rc(rc.clone()); |
| 121 |
/// } |
| 122 |
/// |
| 123 |
/// task::yield_now().await; |
| 124 |
/// }).await.unwrap(); |
| 125 |
/// } |
| 126 |
/// ``` |
| 127 |
/// |
| 128 |
/// This will **not** work: |
| 129 |
/// |
| 130 |
/// ```compile_fail |
| 131 |
/// use tokio::task; |
| 132 |
/// |
| 133 |
/// use std::rc::Rc; |
| 134 |
/// |
| 135 |
/// fn use_rc(rc: Rc<()>) { |
| 136 |
/// // Do stuff w/ rc |
| 137 |
/// # drop(rc); |
| 138 |
/// } |
| 139 |
/// |
| 140 |
/// #[tokio::main] |
| 141 |
/// async fn main() { |
| 142 |
/// tokio::spawn(async { |
| 143 |
/// let rc = Rc::new(()); |
| 144 |
/// |
| 145 |
/// task::yield_now().await; |
| 146 |
/// |
| 147 |
/// use_rc(rc.clone()); |
| 148 |
/// }).await.unwrap(); |
| 149 |
/// } |
| 150 |
/// ``` |
| 151 |
/// |
| 152 |
/// Holding on to a `!Send` value across calls to `.await` will result in |
| 153 |
/// an unfriendly compile error message similar to: |
| 154 |
/// |
| 155 |
/// ```text |
| 156 |
/// `[... some type ...]` cannot be sent between threads safely |
| 157 |
/// ``` |
| 158 |
/// |
| 159 |
/// or: |
| 160 |
/// |
| 161 |
/// ```text |
| 162 |
/// error[E0391]: cycle detected when processing `main` |
| 163 |
/// ``` |
| 164 |
#[track_caller] |
| 165 |
pub fn spawn<F>(future: F) -> JoinHandle<F::Output> |
| 166 |
where |
| 167 |
F: Future + Send + 'static, |
| 168 |
F::Output: Send + 'static, |
| 169 |
{ |
| 170 |
// preventing stack overflows on debug mode, by quickly sending the |
| 171 |
// task to the heap. |
| 172 |
if cfg!(debug_assertions) && std::mem::size_of::<F>() > BOX_FUTURE_THRESHOLD { |
| 173 |
spawn_inner(Box::pin(future), None) |
| 174 |
} else { |
| 175 |
spawn_inner(future, None) |
| 176 |
} |
| 177 |
} |
| 178 |
|
| 179 |
#[track_caller] |
| 180 |
pub(super) fn spawn_inner<T>(future: T, name: Option<&str>) -> JoinHandle<T::Output> |
| 181 |
where |
| 182 |
T: Future + Send + 'static, |
| 183 |
T::Output: Send + 'static, |
| 184 |
{ |
| 185 |
use crate::runtime::{context, task}; |
| 186 |
|
| 187 |
#[cfg(all( |
| 188 |
tokio_unstable, |
| 189 |
tokio_taskdump, |
| 190 |
feature = "rt", |
| 191 |
target_os = "linux", |
| 192 |
any( |
| 193 |
target_arch = "aarch64", |
| 194 |
target_arch = "x86", |
| 195 |
target_arch = "x86_64" |
| 196 |
) |
| 197 |
))] |
| 198 |
let future = task::trace::Trace::root(future); |
| 199 |
let id = task::Id::next(); |
| 200 |
let task = crate::util::trace::task(future, "task", name, id.as_u64()); |
| 201 |
|
| 202 |
match context::with_current(|handle| handle.spawn(task, id)) { |
| 203 |
Ok(join_handle) => join_handle, |
| 204 |
Err(e) => panic!("{}", e), |
| 205 |
} |
| 206 |
} |
| 207 |
} |