blob: b1200a3879c6800a34fb8b95c46452063f404696 [file] [log] [blame]
Stjepan Glavina1479e862019-08-12 20:18:51 +02001//! A single-threaded executor where join handles catch panics inside tasks.
2
3#![feature(async_await)]
4
5use std::future::Future;
6use std::panic::AssertUnwindSafe;
7use std::thread;
8
9use crossbeam::channel::{unbounded, Sender};
10use futures::executor;
11use futures::future::FutureExt;
12use lazy_static::lazy_static;
13
14/// Spawns a future on the executor.
15fn spawn<F, R>(future: F) -> async_task::JoinHandle<thread::Result<R>, ()>
16where
17 F: Future<Output = R> + Send + 'static,
18 R: Send + 'static,
19{
20 lazy_static! {
21 // A channel that holds scheduled tasks.
22 static ref QUEUE: Sender<async_task::Task<()>> = {
23 let (sender, receiver) = unbounded::<async_task::Task<()>>();
24
25 // Start the executor thread.
26 thread::spawn(|| {
27 for task in receiver {
28 // No need for `catch_unwind()` here because panics are already caught.
29 task.run();
30 }
31 });
32
33 sender
34 };
35 }
36
37 // Create a future that catches panics within itself.
38 let future = AssertUnwindSafe(future).catch_unwind();
39
40 // Create a task that is scheduled by sending itself into the channel.
41 let schedule = |t| QUEUE.send(t).unwrap();
42 let (task, handle) = async_task::spawn(future, schedule, ());
43
44 // Schedule the task by sending it into the channel.
45 task.schedule();
46
47 handle
48}
49
50fn main() {
51 // Spawn a future that completes succesfully.
52 let handle = spawn(async {
53 println!("Hello, world!");
54 });
55
56 // Block on the future and report its result.
57 match executor::block_on(handle) {
58 None => println!("The task was cancelled."),
59 Some(Ok(val)) => println!("The task completed with {:?}", val),
60 Some(Err(_)) => println!("The task has panicked"),
61 }
62
63 // Spawn a future that panics.
64 let handle = spawn(async {
65 panic!("Ooops!");
66 });
67
68 // Block on the future and report its result.
69 match executor::block_on(handle) {
70 None => println!("The task was cancelled."),
71 Some(Ok(val)) => println!("The task completed with {:?}", val),
72 Some(Err(_)) => println!("The task has panicked"),
73 }
74}