blob: 6dd612861d5db63fc85bc3af77aa0ee667519a71 [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
Stjepan Glavina42e3a692020-09-17 14:58:40 +02009use async_task::Task;
Stjepan Glavina1479e862019-08-12 20:18:51 +020010use crossbeam::channel::{unbounded, Sender};
Stjepan Glavinaceeb5a12020-09-18 11:45:24 +020011use futures_lite::{future, FutureExt};
12use once_cell::sync::Lazy;
Stjepan Glavina1479e862019-08-12 20:18:51 +020013
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{
Stjepan Glavinaceeb5a12020-09-18 11:45:24 +020020 // A channel that holds scheduled tasks.
21 static QUEUE: Lazy<Sender<Task>> = Lazy::new(|| {
22 let (sender, receiver) = unbounded::<Task>();
Stjepan Glavina1479e862019-08-12 20:18:51 +020023
Stjepan Glavinaceeb5a12020-09-18 11:45:24 +020024 // Start the executor thread.
25 thread::spawn(|| {
26 for task in receiver {
27 // No need for `catch_unwind()` here because panics are already caught.
28 task.run();
29 }
30 });
Stjepan Glavina1479e862019-08-12 20:18:51 +020031
Stjepan Glavinaceeb5a12020-09-18 11:45:24 +020032 sender
33 });
Stjepan Glavina1479e862019-08-12 20:18:51 +020034
35 // Create a future that catches panics within itself.
36 let future = AssertUnwindSafe(future).catch_unwind();
37
38 // Create a task that is scheduled by sending itself into the channel.
39 let schedule = |t| QUEUE.send(t).unwrap();
Stjepan Glavina42e3a692020-09-17 14:58:40 +020040 let (task, handle) = async_task::spawn(future, schedule);
Stjepan Glavina1479e862019-08-12 20:18:51 +020041
42 // Schedule the task by sending it into the channel.
43 task.schedule();
44
45 // Wrap the handle into one that propagates panics.
46 JoinHandle(handle)
47}
48
49/// A join handle that propagates panics inside the task.
Stjepan Glavina42e3a692020-09-17 14:58:40 +020050struct JoinHandle<R>(async_task::JoinHandle<thread::Result<R>>);
Stjepan Glavina1479e862019-08-12 20:18:51 +020051
52impl<R> Future for JoinHandle<R> {
53 type Output = Option<R>;
54
55 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
56 match Pin::new(&mut self.0).poll(cx) {
57 Poll::Pending => Poll::Pending,
58 Poll::Ready(None) => Poll::Ready(None),
59 Poll::Ready(Some(Ok(val))) => Poll::Ready(Some(val)),
60 Poll::Ready(Some(Err(err))) => resume_unwind(err),
61 }
62 }
63}
64
65fn main() {
66 // Spawn a future that panics and block on it.
67 let handle = spawn(async {
68 panic!("Ooops!");
69 });
Stjepan Glavinaceeb5a12020-09-18 11:45:24 +020070 future::block_on(handle);
Stjepan Glavina1479e862019-08-12 20:18:51 +020071}