Initial commit
diff --git a/examples/panic-propagation.rs b/examples/panic-propagation.rs
new file mode 100644
index 0000000..9c4f081
--- /dev/null
+++ b/examples/panic-propagation.rs
@@ -0,0 +1,75 @@
+//! A single-threaded executor where join handles propagate panics from tasks.
+
+#![feature(async_await)]
+
+use std::future::Future;
+use std::panic::{resume_unwind, AssertUnwindSafe};
+use std::pin::Pin;
+use std::task::{Context, Poll};
+use std::thread;
+
+use crossbeam::channel::{unbounded, Sender};
+use futures::executor;
+use futures::future::FutureExt;
+use lazy_static::lazy_static;
+
+/// Spawns a future on the executor.
+fn spawn<F, R>(future: F) -> JoinHandle<R>
+where
+ F: Future<Output = R> + Send + 'static,
+ R: Send + 'static,
+{
+ lazy_static! {
+ // A channel that holds scheduled tasks.
+ static ref QUEUE: Sender<async_task::Task<()>> = {
+ let (sender, receiver) = unbounded::<async_task::Task<()>>();
+
+ // Start the executor thread.
+ thread::spawn(|| {
+ for task in receiver {
+ // No need for `catch_unwind()` here because panics are already caught.
+ task.run();
+ }
+ });
+
+ sender
+ };
+ }
+
+ // Create a future that catches panics within itself.
+ let future = AssertUnwindSafe(future).catch_unwind();
+
+ // Create a task that is scheduled by sending itself into the channel.
+ let schedule = |t| QUEUE.send(t).unwrap();
+ let (task, handle) = async_task::spawn(future, schedule, ());
+
+ // Schedule the task by sending it into the channel.
+ task.schedule();
+
+ // Wrap the handle into one that propagates panics.
+ JoinHandle(handle)
+}
+
+/// A join handle that propagates panics inside the task.
+struct JoinHandle<R>(async_task::JoinHandle<thread::Result<R>, ()>);
+
+impl<R> Future for JoinHandle<R> {
+ type Output = Option<R>;
+
+ fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+ match Pin::new(&mut self.0).poll(cx) {
+ Poll::Pending => Poll::Pending,
+ Poll::Ready(None) => Poll::Ready(None),
+ Poll::Ready(Some(Ok(val))) => Poll::Ready(Some(val)),
+ Poll::Ready(Some(Err(err))) => resume_unwind(err),
+ }
+ }
+}
+
+fn main() {
+ // Spawn a future that panics and block on it.
+ let handle = spawn(async {
+ panic!("Ooops!");
+ });
+ executor::block_on(handle);
+}
diff --git a/examples/panic-result.rs b/examples/panic-result.rs
new file mode 100644
index 0000000..b1200a3
--- /dev/null
+++ b/examples/panic-result.rs
@@ -0,0 +1,74 @@
+//! A single-threaded executor where join handles catch panics inside tasks.
+
+#![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;
+
+/// Spawns a future on the executor.
+fn spawn<F, R>(future: F) -> async_task::JoinHandle<thread::Result<R>, ()>
+where
+ F: Future<Output = R> + Send + 'static,
+ R: Send + 'static,
+{
+ lazy_static! {
+ // A channel that holds scheduled tasks.
+ static ref QUEUE: Sender<async_task::Task<()>> = {
+ let (sender, receiver) = unbounded::<async_task::Task<()>>();
+
+ // Start the executor thread.
+ thread::spawn(|| {
+ for task in receiver {
+ // No need for `catch_unwind()` here because panics are already caught.
+ task.run();
+ }
+ });
+
+ sender
+ };
+ }
+
+ // Create a future that catches panics within itself.
+ let future = AssertUnwindSafe(future).catch_unwind();
+
+ // Create a task that is scheduled by sending itself into the channel.
+ let schedule = |t| QUEUE.send(t).unwrap();
+ let (task, handle) = async_task::spawn(future, schedule, ());
+
+ // Schedule the task by sending it into the channel.
+ task.schedule();
+
+ handle
+}
+
+fn main() {
+ // Spawn a future that completes succesfully.
+ let handle = spawn(async {
+ println!("Hello, world!");
+ });
+
+ // Block on the future and report its result.
+ 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"),
+ }
+
+ // Spawn a future that panics.
+ let handle = spawn(async {
+ panic!("Ooops!");
+ });
+
+ // Block on the future and report its result.
+ 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"),
+ }
+}
diff --git a/examples/spawn-on-thread.rs b/examples/spawn-on-thread.rs
new file mode 100644
index 0000000..6d5b9a2
--- /dev/null
+++ b/examples/spawn-on-thread.rs
@@ -0,0 +1,55 @@
+//! A function that runs a future to completion on a dedicated thread.
+
+#![feature(async_await)]
+
+use std::future::Future;
+use std::sync::Arc;
+use std::thread;
+
+use crossbeam::channel;
+use futures::executor;
+
+/// Spawns a future on a new dedicated thread.
+///
+/// The returned handle can be used to await the output of the future.
+fn spawn_on_thread<F, R>(future: F) -> async_task::JoinHandle<R, ()>
+where
+ F: Future<Output = R> + Send + 'static,
+ R: Send + 'static,
+{
+ // Create a channel that holds the task when it is scheduled for running.
+ let (sender, receiver) = channel::unbounded();
+ let sender = Arc::new(sender);
+ let s = Arc::downgrade(&sender);
+
+ // Wrap the future into one that disconnects the channel on completion.
+ let future = async move {
+ // When the inner future completes, the sender gets dropped and disconnects the channel.
+ let _sender = sender;
+ future.await
+ };
+
+ // Create a task that is scheduled by sending itself into the channel.
+ let schedule = move |t| s.upgrade().unwrap().send(t).unwrap();
+ let (task, handle) = async_task::spawn(future, schedule, ());
+
+ // Schedule the task by sending it into the channel.
+ task.schedule();
+
+ // Spawn a thread running the task to completion.
+ thread::spawn(move || {
+ // Keep taking the task from the channel and running it until completion.
+ for task in receiver {
+ task.run();
+ }
+ });
+
+ handle
+}
+
+fn main() {
+ // Spawn a future on a dedicated thread.
+ executor::block_on(spawn_on_thread(async {
+ println!("Hello, world!");
+ }));
+}
diff --git a/examples/spawn.rs b/examples/spawn.rs
new file mode 100644
index 0000000..6e798c0
--- /dev/null
+++ b/examples/spawn.rs
@@ -0,0 +1,52 @@
+//! A simple single-threaded executor.
+
+#![feature(async_await)]
+
+use std::future::Future;
+use std::panic::catch_unwind;
+use std::thread;
+
+use crossbeam::channel::{unbounded, Sender};
+use futures::executor;
+use lazy_static::lazy_static;
+
+/// Spawns a future on the executor.
+fn spawn<F, R>(future: F) -> async_task::JoinHandle<R, ()>
+where
+ F: Future<Output = R> + Send + 'static,
+ R: Send + 'static,
+{
+ lazy_static! {
+ // A channel that holds scheduled tasks.
+ static ref QUEUE: Sender<async_task::Task<()>> = {
+ let (sender, receiver) = unbounded::<async_task::Task<()>>();
+
+ // Start the executor thread.
+ thread::spawn(|| {
+ for task in receiver {
+ // Ignore panics for simplicity.
+ let _ignore_panic = catch_unwind(|| task.run());
+ }
+ });
+
+ sender
+ };
+ }
+
+ // Create a task that is scheduled by sending itself into the channel.
+ let schedule = |t| QUEUE.send(t).unwrap();
+ let (task, handle) = async_task::spawn(future, schedule, ());
+
+ // Schedule the task by sending it into the channel.
+ task.schedule();
+
+ handle
+}
+
+fn main() {
+ // Spawn a future and await its result.
+ let handle = spawn(async {
+ println!("Hello, world!");
+ });
+ executor::block_on(handle);
+}
diff --git a/examples/task-id.rs b/examples/task-id.rs
new file mode 100644
index 0000000..b3832d0
--- /dev/null
+++ b/examples/task-id.rs
@@ -0,0 +1,88 @@
+//! An executor that assigns an ID to every spawned task.
+
+#![feature(async_await)]
+
+use std::cell::Cell;
+use std::future::Future;
+use std::panic::catch_unwind;
+use std::thread;
+
+use crossbeam::atomic::AtomicCell;
+use crossbeam::channel::{unbounded, Sender};
+use futures::executor;
+use lazy_static::lazy_static;
+
+#[derive(Clone, Copy, Debug)]
+struct TaskId(usize);
+
+thread_local! {
+ /// The ID of the current task.
+ static TASK_ID: Cell<Option<TaskId>> = Cell::new(None);
+}
+
+/// Returns the ID of the currently executing task.
+///
+/// Returns `None` if called outside the runtime.
+fn task_id() -> Option<TaskId> {
+ TASK_ID.with(|id| id.get())
+}
+
+/// Spawns a future on the executor.
+fn spawn<F, R>(future: F) -> async_task::JoinHandle<R, TaskId>
+where
+ F: Future<Output = R> + Send + 'static,
+ R: Send + 'static,
+{
+ lazy_static! {
+ // A channel that holds scheduled tasks.
+ static ref QUEUE: Sender<async_task::Task<TaskId>> = {
+ let (sender, receiver) = unbounded::<async_task::Task<TaskId>>();
+
+ // Start the executor thread.
+ thread::spawn(|| {
+ TASK_ID.with(|id| {
+ for task in receiver {
+ // Store the task ID into the thread-local before running.
+ id.set(Some(*task.tag()));
+
+ // Ignore panics for simplicity.
+ let _ignore_panic = catch_unwind(|| task.run());
+ }
+ })
+ });
+
+ sender
+ };
+
+ // A counter that assigns IDs to spawned tasks.
+ static ref COUNTER: AtomicCell<usize> = AtomicCell::new(0);
+ }
+
+ // Reserve an ID for the new task.
+ let id = TaskId(COUNTER.fetch_add(1));
+
+ // Create a task that is scheduled by sending itself into the channel.
+ let schedule = |task| QUEUE.send(task).unwrap();
+ let (task, handle) = async_task::spawn(future, schedule, id);
+
+ // Schedule the task by sending it into the channel.
+ task.schedule();
+
+ handle
+}
+
+fn main() {
+ let mut handles = vec![];
+
+ // Spawn a bunch of tasks.
+ for _ in 0..10 {
+ handles.push(spawn(async move {
+ println!("Hello from task with {:?}", task_id());
+ }));
+ }
+
+ // Wait for the tasks to finish.
+ for handle in handles {
+ executor::block_on(handle);
+ }
+}