#![feature(async_await)]
use std::future::Future;
use std::panic::AssertUnwindSafe;
use std::thread;
use crossbeam::channel::{unbounded, Sender};
use futures::executor;
use futures::future::FutureExt;
use lazy_static::lazy_static;
fn spawn<F, R>(future: F) -> async_task::JoinHandle<thread::Result<R>, ()>
where
F: Future<Output = R> + Send + 'static,
R: Send + 'static,
{
lazy_static! {
static ref QUEUE: Sender<async_task::Task<()>> = {
let (sender, receiver) = unbounded::<async_task::Task<()>>();
thread::spawn(|| {
for task in receiver {
task.run();
}
});
sender
};
}
let future = AssertUnwindSafe(future).catch_unwind();
let schedule = |t| QUEUE.send(t).unwrap();
let (task, handle) = async_task::spawn(future, schedule, ());
task.schedule();
handle
}
fn main() {
let handle = spawn(async {
println!("Hello, world!");
});
match executor::block_on(handle) {
None => println!("The task was cancelled."),
Some(Ok(val)) => println!("The task completed with {:?}", val),
Some(Err(_)) => println!("The task has panicked"),
}
let handle = spawn(async {
panic!("Ooops!");
});
match executor::block_on(handle) {
None => println!("The task was cancelled."),
Some(Ok(val)) => println!("The task completed with {:?}", val),
Some(Err(_)) => println!("The task has panicked"),
}
}