use std::cell::{Cell, RefCell};
use std::collections::{HashMap, VecDeque};
use std::future::Future;
use std::panic::AssertUnwindSafe;
use std::pin::Pin;
use std::rc::{Rc, Weak};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Wake, Waker};
use std::time::Duration;
type TaskId = u64;
const MAX_POLLS_PER_TURN: usize = 256;
struct TaskEntry {
future: Pin<Box<dyn Future<Output = ()>>>,
waker: Waker,
cancelled: Rc<Cell<bool>>,
}
struct ExecutorInner {
tasks: HashMap<TaskId, TaskEntry>,
next_id: TaskId,
}
pub type WakeCallback = Arc<dyn Fn() + Send + Sync>;
#[derive(Clone)]
pub struct TaskExecutor {
inner: Rc<RefCell<ExecutorInner>>,
ready: Arc<Mutex<VecDeque<TaskId>>>,
wake: WakeCallback,
}
pub struct TaskHandle {
id: TaskId,
inner: Weak<RefCell<ExecutorInner>>,
cancelled: Rc<Cell<bool>>,
}
impl TaskHandle {
pub fn cancel(&self) {
self.cancelled.set(true);
if let Some(inner) = self.inner.upgrade() {
inner.borrow_mut().tasks.remove(&self.id);
}
}
pub fn is_cancelled(&self) -> bool {
self.cancelled.get()
}
}
impl TaskExecutor {
pub fn new(wake: WakeCallback) -> Self {
Self {
inner: Rc::new(RefCell::new(ExecutorInner { tasks: HashMap::new(), next_id: 0 })),
ready: Arc::new(Mutex::new(VecDeque::new())),
wake,
}
}
pub fn spawn<F>(&self, future: F) -> TaskHandle
where
F: Future<Output = ()> + 'static,
{
self.spawn_boxed(Box::pin(future))
}
pub fn spawn_with<F, T, C>(&self, future: F, on_done: C) -> TaskHandle
where
F: Future<Output = T> + 'static,
C: FnOnce(T) + 'static,
{
self.spawn(async move {
let value = future.await;
on_done(value);
})
}
pub fn spawn_blocking<F, T, C>(&self, work: F, on_done: C) -> TaskHandle
where
F: FnOnce() -> Result<T, String> + Send + 'static,
T: Send + 'static,
C: FnOnce(Result<T, String>) + 'static,
{
let state = Arc::new(Mutex::new(BlockingState::<T> { value: None, waker: None }));
let thread_state = Arc::clone(&state);
let thread = std::thread::Builder::new().name("mgui-blocking".to_string()).spawn(move || {
let result = std::panic::catch_unwind(AssertUnwindSafe(work))
.unwrap_or_else(|payload| Err(format!("blocking task panicked: {}", panic_message(payload.as_ref()))));
if let Ok(mut state) = thread_state.lock() {
state.value = Some(result);
if let Some(waker) = state.waker.take() {
drop(state);
waker.wake();
}
}
});
match thread {
Ok(_) => self.spawn_with(BlockingFuture { state }, on_done),
Err(e) => {
let message = format!("spawn blocking thread: {e}");
self.spawn_with(async {}, move |_| on_done(Err(message)))
}
}
}
fn spawn_boxed(&self, future: Pin<Box<dyn Future<Output = ()>>>) -> TaskHandle {
let id = {
let mut inner = self.inner.borrow_mut();
let id = inner.next_id;
inner.next_id = inner.next_id.wrapping_add(1);
id
};
let cancelled = Rc::new(Cell::new(false));
let waker =
Waker::from(Arc::new(TaskWake { id, ready: Arc::clone(&self.ready), wake: Arc::clone(&self.wake) }));
self.inner.borrow_mut().tasks.insert(id, TaskEntry { future, waker, cancelled: Rc::clone(&cancelled) });
if let Ok(mut ready) = self.ready.lock() {
ready.push_back(id);
}
(self.wake)();
TaskHandle { id, inner: Rc::downgrade(&self.inner), cancelled }
}
pub fn poll_ready(&self) -> usize {
let mut polled = 0;
for _ in 0..MAX_POLLS_PER_TURN {
let id = match self.ready.lock() {
Ok(mut ready) => ready.pop_front(),
Err(_) => return polled,
};
let Some(id) = id else {
return polled;
};
let Some(mut entry) = self.inner.borrow_mut().tasks.remove(&id) else {
continue;
};
if entry.cancelled.get() {
continue;
}
polled += 1;
let waker = entry.waker.clone();
let mut cx = Context::from_waker(&waker);
let result = std::panic::catch_unwind(AssertUnwindSafe(|| entry.future.as_mut().poll(&mut cx)));
match result {
Ok(Poll::Ready(())) => {}
Ok(Poll::Pending) => {
if !entry.cancelled.get() {
self.inner.borrow_mut().tasks.insert(id, entry);
}
}
Err(payload) => {
log::error!(
target: "mgui_async",
"task {id} panicked: {}",
panic_message(payload.as_ref())
);
}
}
}
polled
}
pub fn len(&self) -> usize {
self.inner.borrow().tasks.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl std::fmt::Debug for TaskExecutor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TaskExecutor").field("pending", &self.len()).finish_non_exhaustive()
}
}
struct BlockingState<T> {
value: Option<Result<T, String>>,
waker: Option<Waker>,
}
struct BlockingFuture<T> {
state: Arc<Mutex<BlockingState<T>>>,
}
impl<T> Future for BlockingFuture<T> {
type Output = Result<T, String>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut state = match self.state.lock() {
Ok(state) => state,
Err(_) => return Poll::Ready(Err("blocking task state poisoned".to_string())),
};
if let Some(value) = state.value.take() {
return Poll::Ready(value);
}
state.waker = Some(cx.waker().clone());
Poll::Pending
}
}
struct TaskWake {
id: TaskId,
ready: Arc<Mutex<VecDeque<TaskId>>>,
wake: WakeCallback,
}
impl Wake for TaskWake {
fn wake(self: Arc<Self>) {
self.wake_by_ref();
}
fn wake_by_ref(self: &Arc<Self>) {
if let Ok(mut ready) = self.ready.lock() {
ready.push_back(self.id);
}
(self.wake)();
}
}
fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
if let Some(s) = payload.downcast_ref::<&str>() {
(*s).to_string()
} else if let Some(s) = payload.downcast_ref::<String>() {
s.clone()
} else {
"unknown panic payload".to_string()
}
}
struct SleepState {
done: bool,
waker: Option<Waker>,
}
pub struct Sleep {
duration: Duration,
state: Arc<Mutex<SleepState>>,
started: bool,
}
pub fn sleep(duration: Duration) -> Sleep {
Sleep { duration, state: Arc::new(Mutex::new(SleepState { done: false, waker: None })), started: false }
}
impl Future for Sleep {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
let this = self.get_mut();
let mut state = match this.state.lock() {
Ok(state) => state,
Err(_) => return Poll::Ready(()),
};
if state.done {
return Poll::Ready(());
}
if !this.started {
this.started = true;
let sleep_state = Arc::clone(&this.state);
let duration = this.duration;
let spawned = std::thread::Builder::new().name("mgui-sleep".to_string()).spawn(move || {
std::thread::sleep(duration);
if let Ok(mut state) = sleep_state.lock() {
state.done = true;
if let Some(waker) = state.waker.take() {
drop(state);
waker.wake();
}
}
});
if spawned.is_err() {
state.done = true;
return Poll::Ready(());
}
}
state.waker = Some(cx.waker().clone());
Poll::Pending
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;
fn noop_wake() -> WakeCallback {
Arc::new(|| {})
}
#[test]
fn ready_task_runs_and_calls_back() {
let executor = TaskExecutor::new(noop_wake());
let value = Rc::new(Cell::new(0));
let out = Rc::clone(&value);
let _handle = executor.spawn_with(async { 7 }, move |v| out.set(v));
assert_eq!(executor.poll_ready(), 1);
assert_eq!(value.get(), 7);
assert!(executor.is_empty());
}
#[test]
fn waker_requeues_pending_task() {
struct WakeOnce(bool);
impl Future for WakeOnce {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
if self.0 {
Poll::Ready(())
} else {
self.0 = true;
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
let executor = TaskExecutor::new(noop_wake());
let done = Rc::new(Cell::new(false));
let out = Rc::clone(&done);
let _handle = executor.spawn_with(WakeOnce(false), move |_| out.set(true));
assert_eq!(executor.poll_ready(), 2);
assert!(done.get());
assert!(executor.is_empty());
}
#[test]
fn cancel_drops_task_without_callback() {
struct Never;
impl Future for Never {
type Output = ();
fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> {
Poll::Pending
}
}
let executor = TaskExecutor::new(noop_wake());
let called = Rc::new(Cell::new(false));
let out = Rc::clone(&called);
let handle = executor.spawn_with(Never, move |_| out.set(true));
handle.cancel();
assert_eq!(executor.poll_ready(), 0);
assert!(!called.get());
assert!(executor.is_empty());
}
#[test]
fn panic_isolated_from_other_tasks() {
let executor = TaskExecutor::new(noop_wake());
let done = Rc::new(Cell::new(false));
let out = Rc::clone(&done);
let _panicking = executor.spawn(async {
panic!("intentional task panic");
});
let _healthy = executor.spawn_with(async {}, move |_| out.set(true));
assert_eq!(executor.poll_ready(), 2);
assert!(done.get(), "panic task 不得阻止其它任务完成");
assert!(executor.is_empty());
}
#[test]
fn sleep_completes_via_background_waker() {
let executor = TaskExecutor::new(noop_wake());
let done = Rc::new(Cell::new(false));
let out = Rc::clone(&done);
let _handle = executor.spawn_with(sleep(Duration::from_millis(20)), move |_| out.set(true));
let start = Instant::now();
while !done.get() && start.elapsed() < Duration::from_secs(2) {
executor.poll_ready();
std::thread::sleep(Duration::from_millis(2));
}
assert!(done.get(), "sleep 任务应在后台 waker 唤醒后完成");
assert!(executor.is_empty());
}
#[test]
fn spawn_during_poll_is_driven_same_turn() {
let executor = TaskExecutor::new(noop_wake());
let executor_for_task = executor.clone();
let done = Rc::new(Cell::new(false));
let out = Rc::clone(&done);
let _outer = executor.spawn(async move {
executor_for_task.spawn_with(async {}, move |_| out.set(true));
});
assert_eq!(executor.poll_ready(), 2);
assert!(done.get());
assert!(executor.is_empty());
}
#[test]
fn spawn_blocking_returns_result_on_ui_thread() {
let executor = TaskExecutor::new(noop_wake());
let value = Rc::new(Cell::new(0));
let out = Rc::clone(&value);
let _handle = executor.spawn_blocking(|| Ok(42), move |result| out.set(result.unwrap_or_default()));
let start = Instant::now();
while value.get() == 0 && start.elapsed() < Duration::from_secs(2) {
executor.poll_ready();
std::thread::sleep(Duration::from_millis(2));
}
assert_eq!(value.get(), 42);
assert!(executor.is_empty());
}
#[test]
fn spawn_blocking_panic_becomes_error() {
let executor = TaskExecutor::new(noop_wake());
let failed = Rc::new(Cell::new(false));
let out = Rc::clone(&failed);
let _handle = executor.spawn_blocking(
|| -> Result<(), String> { panic!("blocking panic") },
move |result| out.set(result.is_err()),
);
let start = Instant::now();
while !failed.get() && start.elapsed() < Duration::from_secs(2) {
executor.poll_ready();
std::thread::sleep(Duration::from_millis(2));
}
assert!(failed.get());
}
#[test]
fn wake_callback_invoked_for_cross_thread_spawn() {
let woke = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&woke);
let executor = TaskExecutor::new(Arc::new(move || {
flag.store(true, Ordering::SeqCst);
}));
let _handle = executor.spawn(async {});
assert!(woke.load(Ordering::SeqCst), "spawn 应唤醒事件循环");
executor.poll_ready();
}
}