async_local_executor/
lib.rs1#![doc = include_str!("../README.md")]
2#![allow(clippy::missing_transmute_annotations)]
4
5mod executor;
6#[cfg(test)]
7mod tests;
8mod tls;
9
10use crate::tls::executor;
11use std::thread;
12
13pub use crate::executor::{Executor, JoinHandle};
14pub use crate::tls::EnterGuard;
15
16#[inline]
17pub fn spawn_local<F>(future: F) -> JoinHandle<F::Output>
18where
19 F: IntoFuture + 'static,
20{
21 #[cfg(feature = "tokio")]
22 let future = async_compat::Compat::new(future.into_future());
23 executor().spawn_local(future.into_future())
24}
25
26#[inline]
27pub fn run_ready_tasks() {
28 while let Some(ticker) = { executor().ticker() } {
29 ticker.tick();
30 }
31}
32
33#[inline]
34pub fn exit() {
35 executor().exit();
36}
37
38#[inline]
39pub fn block_on<F>(future: F) -> F::Output
40where
41 F: IntoFuture + 'static,
42{
43 let thread = thread::current();
44 let mut executor = Executor::new(move || thread.unpark());
45 let _guard = executor.enter();
46 let main = spawn_local(async move {
47 let result = future.await;
48 exit();
49 result
50 });
51 loop {
52 run_ready_tasks();
53 if let Some(result) = main.result() {
54 return result;
55 }
56 thread::park();
57 }
58}