summaryrefslogtreecommitdiffstats
path: root/tokio/src/task/spawn.rs
diff options
context:
space:
mode:
authorCarl Lerche <me@carllerche.com>2019-11-16 08:28:34 -0800
committerGitHub <noreply@github.com>2019-11-16 08:28:34 -0800
commit19f1fc36bd567377bde4a2c6818c6b606d89d488 (patch)
tree44ab1d6dceabbb8353ab6369779cce4d3333075f /tokio/src/task/spawn.rs
parent3f0eabe7798de624f5ee9c7562803bfb97e6088f (diff)
task: return `JoinHandle` from spawn (#1777)
`tokio::spawn` now returns a `JoinHandle` to obtain the result of the task: Closes #887.
Diffstat (limited to 'tokio/src/task/spawn.rs')
-rw-r--r--tokio/src/task/spawn.rs53
1 files changed, 53 insertions, 0 deletions
diff --git a/tokio/src/task/spawn.rs b/tokio/src/task/spawn.rs
new file mode 100644
index 00000000..6fdff651
--- /dev/null
+++ b/tokio/src/task/spawn.rs
@@ -0,0 +1,53 @@
+use crate::runtime;
+use crate::task::JoinHandle;
+
+use std::future::Future;
+
+/// Spawns a new asynchronous task, returning a
+/// [`JoinHandle`](super::JoinHandle)] for it.
+///
+/// Spawning a task enables the task to execute concurrently to other tasks. The
+/// spawned task may execute on the current thread, or it may be sent to a
+/// different thread to be executed. The specifics depend on the current
+/// [`Runtime`](crate::runtime::Runtime) configuration.
+///
+/// # Examples
+///
+/// In this example, a server is started and `spawn` is used to start a new task
+/// that processes each received connection.
+///
+/// ```no_run
+/// use tokio::net::{TcpListener, TcpStream};
+///
+/// use std::io;
+///
+/// async fn process(socket: TcpStream) {
+/// // ...
+/// # drop(socket);
+/// }
+///
+/// #[tokio::main]
+/// async fn main() -> io::Result<()> {
+/// let mut listener = TcpListener::bind("127.0.0.1:8080").await?;
+///
+/// loop {
+/// let (socket, _) = listener.accept().await?;
+///
+/// tokio::spawn(async move {
+/// // Process each socket concurrently.
+/// process(socket).await
+/// });
+/// }
+/// }
+/// ```
+///
+/// # Panics
+///
+/// Panics if called from **outside** of the Tokio runtime.
+pub fn spawn<T>(task: T) -> JoinHandle<T::Output>
+where
+ T: Future + Send + 'static,
+ T::Output: Send + 'static,
+{
+ runtime::spawn(task)
+}