feat: add spawn_local

master
dignifiedquire 5 years ago
parent 0a7a52aed5
commit 228cc59b3b

@ -60,6 +60,20 @@ impl Builder {
Ok(JoinHandle::new(smol_task, task))
}
/// Spawns a task locally with the configured settings.
pub fn local<F, T>(self, future: F) -> io::Result<JoinHandle<T>>
where
F: Future<Output = T> + 'static,
T: 'static,
{
let wrapped = self.build(future);
let task = wrapped.tag.task().clone();
let smol_task = smol::Task::local(wrapped).into();
Ok(JoinHandle::new(smol_task, task))
}
/// Spawns a task with the configured settings, blocking on its execution.
pub fn blocking<F, T>(self, future: F) -> T
where

@ -139,6 +139,7 @@ cfg_default! {
pub use join_handle::JoinHandle;
pub use sleep::sleep;
pub use spawn::spawn;
pub use spawn_local::spawn_local;
pub use task_local::{AccessError, LocalKey};
pub(crate) use task_local::LocalsMap;
@ -151,6 +152,7 @@ cfg_default! {
mod sleep;
mod spawn;
mod spawn_blocking;
mod spawn_local;
mod task;
mod task_id;
mod task_local;

@ -0,0 +1,32 @@
use std::future::Future;
use crate::task::{Builder, JoinHandle};
/// Spawns a task onto the thread-local executor.
///
/// This function is similar to [`std::thread::spawn`], except it spawns an asynchronous task.
///
/// [`std::thread`]: https://doc.rust-lang.org/std/thread/fn.spawn.html
///
/// # Examples
///
/// ```
/// # async_std::task::block_on(async {
/// #
/// use async_std::task;
///
/// let handle = task::spawn_local(async {
/// 1 + 2
/// });
///
/// assert_eq!(handle.await, 3);
/// #
/// # })
/// ```
pub fn spawn_local<F, T>(future: F) -> JoinHandle<T>
where
F: Future<Output = T> + 'static,
T: 'static,
{
Builder::new().local(future).expect("cannot spawn task")
}
Loading…
Cancel
Save