blob: 8a5339fcfead04fb9ac96d1c6cf8beaff541d332 [file] [log] [blame]
Stjepan Glavina1479e862019-08-12 20:18:51 +02001//! A single-threaded executor where join handles propagate panics from tasks.
2
Stjepan Glavina1479e862019-08-12 20:18:51 +02003use std::future::Future;
4use std::panic::{resume_unwind, AssertUnwindSafe};
5use std::pin::Pin;
6use std::task::{Context, Poll};
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) -> JoinHandle<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 // Wrap the handle into one that propagates panics.
48 JoinHandle(handle)
49}
50
51/// A join handle that propagates panics inside the task.
52struct JoinHandle<R>(async_task::JoinHandle<thread::Result<R>, ()>);
53
54impl<R> Future for JoinHandle<R> {
55 type Output = Option<R>;
56
57 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
58 match Pin::new(&mut self.0).poll(cx) {
59 Poll::Pending => Poll::Pending,
60 Poll::Ready(None) => Poll::Ready(None),
61 Poll::Ready(Some(Ok(val))) => Poll::Ready(Some(val)),
62 Poll::Ready(Some(Err(err))) => resume_unwind(err),
63 }
64 }
65}
66
67fn main() {
68 // Spawn a future that panics and block on it.
69 let handle = spawn(async {
70 panic!("Ooops!");
71 });
72 executor::block_on(handle);
73}