tasic/
task.rs

1use core::future::Future;
2
3use cfg_if::cfg_if;
4cfg_if! {
5    if #[cfg(feature = "tokio")] {
6        use tokio::task::JoinHandle;
7    } else if #[cfg(feature = "async_std")] {
8        use async_std::task::JoinHandle;
9    } else if #[cfg(feature = "smol")] {
10        use smol::Task as JoinHandle;
11    } else {
12        use std::thread::JoinHandle;
13    }
14}
15
16/// Spawn a new async task
17pub fn spawn<T>(future: T) -> JoinHandle<T::Output>
18where
19    T: Future + Send + 'static,
20    T::Output: Send + 'static {
21    cfg_if! {
22        if #[cfg(feature = "tokio")] {
23            tokio::spawn(future)
24        } else if #[cfg(feature = "async_std")] {
25            async_std::task::spawn(future)
26        } else if #[cfg(feature = "smol")] {
27            smol::spawn(future)
28        } else {
29            std::thread::spawn(|| {
30                futures::executor::block_on(future)
31            })
32        }
33    }
34}
35
36/// Yields the current task
37#[cfg(any(
38    feature = "tokio",
39    feature = "smol",
40    feature = "async_std",
41))]
42pub async fn yield_now() {
43    cfg_if! {
44        if #[cfg(feature = "tokio")] {
45            tokio::task::yield_now().await
46        } else if #[cfg(feature = "async_std")] {
47            async_std::task::yield_now().await
48        } else if #[cfg(feature = "smol")] {
49            smol::future::yield_now().await
50        }
51    }
52}