use std::future::Future;
use crate::timer::sleep;
pub fn run<F>(spawn_closure: F)
where
F: Future<Output = ()> + Send + 'static,
{
cfg_if::cfg_if! {
if #[cfg(target_arch = "wasm32")] {
wasm_bindgen_futures::spawn_local(spawn_closure);
} else {
async_global_executor::block_on(spawn_closure);
}
}
}
pub fn main<F>(spawn_closure: F)
where
F: Future<Output = ()> + Send + 'static,
{
use std::time::Duration;
run(async {
spawn_closure.await;
loop {
cfg_if::cfg_if! {
if #[cfg(target_arch = "wasm32")] {
sleep(Duration::from_secs(3600)).await.unwrap();
} else {
sleep(Duration::from_secs(3600)).await;
}
}
}
});
}
cfg_if::cfg_if! {
if #[cfg(target_arch = "wasm32")] {
pub fn spawn<F: Future<Output = T> + 'static, T: 'static>(future: F) {
wasm_bindgen_futures::spawn_local(async move {
let _ = future.await;
});
}
} else {
pub fn spawn<F: Future<Output = T> + Send + 'static, T: Send + 'static>(future: F) {
async_global_executor::spawn(future).detach();
}
pub fn spawn_task<F: Future<Output = T> + Send + 'static, T: Send + 'static>(future: F) -> async_task::Task<T> {
async_global_executor::spawn(future)
}
}
}
#[cfg(not(target_arch = "wasm32"))]
pub use async_global_executor::spawn_blocking;
cfg_if::cfg_if! {
if #[cfg(target_arch = "wasm32")] {
pub fn run_block_on<F, T>(f: F)
where
F: Future<Output = T> + 'static,
T: 'static,
{
wasm_bindgen_futures::spawn_local(async move {
let _ = f.await;
});
}
} else {
pub use async_global_executor::block_on as run_block_on;
}
}
#[cfg(not(target_arch = "wasm32"))]
pub type Task<T> = async_task::Task<T>;
#[cfg(test)]
mod basic_test {
use std::io::Error;
use std::thread;
use std::time;
use futures_lite::future::zip;
use tracing::debug;
use crate::task::spawn;
use crate::test_async;
#[test_async]
async fn future_join() -> Result<(), Error> {
let ft1 = async {
debug!("ft1: starting sleeping for 1000ms");
thread::sleep(time::Duration::from_millis(1000));
debug!("ft1: woke from sleep");
Ok(()) as Result<(), ()>
};
let ft2 = async {
debug!("ft2: starting sleeping for 500ms");
thread::sleep(time::Duration::from_millis(500));
debug!("ft2: woke up");
Ok(()) as Result<(), ()>
};
let core_threads = num_cpus::get().max(1);
debug!("num threads: {}", core_threads);
let _ = zip(ft1, ft2).await;
Ok(())
}
#[test_async]
async fn future_spawn() -> Result<(), Error> {
let ft1 = async {
debug!("ft1: starting sleeping for 1000ms");
thread::sleep(time::Duration::from_millis(1000)); debug!("ft1: woke from sleep");
};
let ft2 = async {
debug!("ft2: starting sleeping for 500ms");
thread::sleep(time::Duration::from_millis(500));
debug!("ft2: woke up");
};
let core_threads = num_cpus::get().max(1);
debug!("num threads: {}", core_threads);
spawn(ft1);
spawn(ft2);
thread::sleep(time::Duration::from_millis(2000));
Ok(())
}
}