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);
type Task = async_task::Task<TaskId>;
type JoinHandle<T> = async_task::JoinHandle<T, TaskId>;
thread_local! {
static TASK_ID: Cell<Option<TaskId>> = Cell::new(None);
}
fn task_id() -> Option<TaskId> {
TASK_ID.with(|id| id.get())
}
fn spawn<F, R>(future: F) -> JoinHandle<R>
where
F: Future<Output = R> + Send + 'static,
R: Send + 'static,
{
lazy_static! {
static ref QUEUE: Sender<Task> = {
let (sender, receiver) = unbounded::<Task>();
thread::spawn(|| {
TASK_ID.with(|id| {
for task in receiver {
id.set(Some(*task.tag()));
let _ignore_panic = catch_unwind(|| task.run());
}
})
});
sender
};
static ref COUNTER: AtomicCell<usize> = AtomicCell::new(0);
}
let id = TaskId(COUNTER.fetch_add(1));
let schedule = |task| QUEUE.send(task).unwrap();
let (task, handle) = async_task::spawn(future, schedule, id);
task.schedule();
handle
}
fn main() {
let mut handles = vec![];
for _ in 0..10 {
handles.push(spawn(async move {
println!("Hello from task with {:?}", task_id());
}));
}
for handle in handles {
executor::block_on(handle);
}
}