[−][src]Crate async_spawner
Executor agnostic task spawning
#[async_std::main] async fn main() { struct AsyncStd; impl async_spawner::Executor for AsyncStd { fn block_on(&self, future: BoxedFuture) { async_std::task::block_on(future); } fn spawn(&self, future: BoxedFuture) -> BoxedFuture { Box::pin(async_std::task::spawn(future)) } fn spawn_blocking(&self, task: Box<dyn FnOnce() + Send>) -> BoxedFuture { Box::pin(async_std::task::spawn_blocking(task)) } fn spawn_local( &self, future: Pin<Box<dyn Future<Output = ()> + 'static>>, ) -> BoxedFuture { Box::pin(async_std::task::spawn_local(future)) } } async_spawner::register_executor(Box::new(AsyncStd)); let res = async_spawner::spawn(async { println!("executor agnostic spawning"); 1 }) .await; assert_eq!(res, 1); }
#[tokio::main] async fn main() { struct Tokio; impl async_spawner::Executor for Tokio { fn block_on(&self, future: BoxedFuture) { tokio::runtime::Builder::new_multi_thread() .build() .unwrap() .block_on(future); } fn spawn(&self, future: BoxedFuture) -> BoxedFuture { Box::pin(async { tokio::task::spawn(future).await.unwrap() }) } fn spawn_blocking(&self, task: Box<dyn FnOnce() + Send>) -> BoxedFuture { Box::pin(async { tokio::task::spawn_blocking(task).await.unwrap() }) } fn spawn_local( &self, future: Pin<Box<dyn Future<Output = ()> + 'static>>, ) -> BoxedFuture { let handle = tokio::task::spawn_local(future); Box::pin(async { handle.await.unwrap() }) } } async_spawner::register_executor(Box::new(Tokio)); let res = async_spawner::spawn(async { println!("executor agnostic spawning"); 1 }) .await; assert_eq!(res, 1); }
Structs
ExecutorRegistered | Error returned by |
JoinHandle | Executor agnostic join handle. |
Traits
Executor | Trait abstracting over an executor. |
Functions
block_on | Blocks until the future has finished. |
executor | Returns the registered executor. |
register_executor | Register an executor. Panics if an executor was already registered. |
spawn | Spawns an asynchronous task using the underlying executor. |
spawn_blocking | Runs the provided closure on a thread, which can execute blocking tasks asynchronously. |
spawn_local | Spawns a future that doesn't implement Send. |
try_register_executor | Tries registering an executor. |