Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame^] | 1 | //! A single-threaded executor where join handles catch panics inside tasks. |
| 2 | |
| 3 | #![feature(async_await)] |
| 4 | |
| 5 | use std::future::Future; |
| 6 | use std::panic::AssertUnwindSafe; |
| 7 | use std::thread; |
| 8 | |
| 9 | use crossbeam::channel::{unbounded, Sender}; |
| 10 | use futures::executor; |
| 11 | use futures::future::FutureExt; |
| 12 | use lazy_static::lazy_static; |
| 13 | |
| 14 | /// Spawns a future on the executor. |
| 15 | fn spawn<F, R>(future: F) -> async_task::JoinHandle<thread::Result<R>, ()> |
| 16 | where |
| 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 | |
| 50 | fn 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 | } |