Skip to main content

mgui_task/
lib.rs

1//! UI 线程本地异步任务执行器
2//!
3//! 设计目标:
4//! - **零第三方依赖**:只用 std Future/Waker(不引入 futures/smol);
5//! - **!Send futures**:任务在 UI 线程轮询,可以捕获 `Rc`/`Signal` 等 UI 状态;
6//! - **跨线程唤醒**:后台线程持有的 `Waker` 通过 `Arc<Mutex<ready>>` 入队,
7//!   再调用 Runner 注入的 wake 回调(通常是 `EventLoopProxy::send_event`);
8//! - **取消/panic 隔离**:`TaskHandle::cancel()` 立即移除任务;poll panic 被
9//!   catch_unwind 捕获并记录,不影响其它任务与 UI 树。
10//!
11//! Runner 在 `user_event` / 每帧 redraw / `about_to_wait` 调用
12//! [`TaskExecutor::poll_ready`] 驱动就绪任务;任务回调更新 Signal 后由 Runner
13//! 标记重绘。
14
15use std::cell::{Cell, RefCell};
16use std::collections::{HashMap, VecDeque};
17use std::future::Future;
18use std::panic::AssertUnwindSafe;
19use std::pin::Pin;
20use std::rc::{Rc, Weak};
21use std::sync::{Arc, Mutex};
22use std::task::{Context, Poll, Wake, Waker};
23use std::time::Duration;
24
25type TaskId = u64;
26
27/// 单次 `poll_ready` 最多轮询的任务数,防止自唤醒 future 独占 UI 线程。
28const MAX_POLLS_PER_TURN: usize = 256;
29
30struct TaskEntry {
31    future: Pin<Box<dyn Future<Output = ()>>>,
32    waker: Waker,
33    cancelled: Rc<Cell<bool>>,
34}
35
36struct ExecutorInner {
37    tasks: HashMap<TaskId, TaskEntry>,
38    next_id: TaskId,
39}
40
41/// 唤醒回调:由 Runner 注入(通常是 `EventLoopProxy::send_event`)。
42pub type WakeCallback = Arc<dyn Fn() + Send + Sync>;
43
44/// UI 线程任务执行器(可 Clone;所有任务共享同一队列)
45#[derive(Clone)]
46pub struct TaskExecutor {
47    inner: Rc<RefCell<ExecutorInner>>,
48    /// 跨线程 waker 入队
49    ready: Arc<Mutex<VecDeque<TaskId>>>,
50    /// 唤醒事件循环(可在任意线程调用)
51    wake: WakeCallback,
52}
53
54/// 任务句柄:drop 不会取消任务;需要取消显式调用 [`TaskHandle::cancel`]。
55pub struct TaskHandle {
56    id: TaskId,
57    inner: Weak<RefCell<ExecutorInner>>,
58    cancelled: Rc<Cell<bool>>,
59}
60
61impl TaskHandle {
62    /// 取消任务并立即丢弃 future;完成回调不会再触发。
63    pub fn cancel(&self) {
64        self.cancelled.set(true);
65        if let Some(inner) = self.inner.upgrade() {
66            inner.borrow_mut().tasks.remove(&self.id);
67        }
68    }
69
70    pub fn is_cancelled(&self) -> bool {
71        self.cancelled.get()
72    }
73}
74
75impl TaskExecutor {
76    pub fn new(wake: WakeCallback) -> Self {
77        Self {
78            inner: Rc::new(RefCell::new(ExecutorInner { tasks: HashMap::new(), next_id: 0 })),
79            ready: Arc::new(Mutex::new(VecDeque::new())),
80            wake,
81        }
82    }
83
84    /// 派生一个输出为 `()` 的本地任务。
85    pub fn spawn<F>(&self, future: F) -> TaskHandle
86    where
87        F: Future<Output = ()> + 'static,
88    {
89        self.spawn_boxed(Box::pin(future))
90    }
91
92    /// 派生任务并在完成时于 UI 线程调用 `on_done`。
93    ///
94    /// 失败信息可直接通过 `Future<Output = Result<T, E>>` 交给回调处理。
95    pub fn spawn_with<F, T, C>(&self, future: F, on_done: C) -> TaskHandle
96    where
97        F: Future<Output = T> + 'static,
98        C: FnOnce(T) + 'static,
99    {
100        self.spawn(async move {
101            let value = future.await;
102            on_done(value);
103        })
104    }
105
106    /// 派生阻塞工作到后台线程,完成后在 UI 线程调用 `on_done(Result<T, String>)`。
107    ///
108    /// 用于文件 IO / 图片解码等不能占用 UI 线程的工作;线程内 panic 会转成 Err。
109    pub fn spawn_blocking<F, T, C>(&self, work: F, on_done: C) -> TaskHandle
110    where
111        F: FnOnce() -> Result<T, String> + Send + 'static,
112        T: Send + 'static,
113        C: FnOnce(Result<T, String>) + 'static,
114    {
115        let state = Arc::new(Mutex::new(BlockingState::<T> { value: None, waker: None }));
116        let thread_state = Arc::clone(&state);
117        let thread = std::thread::Builder::new().name("mgui-blocking".to_string()).spawn(move || {
118            let result = std::panic::catch_unwind(AssertUnwindSafe(work))
119                .unwrap_or_else(|payload| Err(format!("blocking task panicked: {}", panic_message(payload.as_ref()))));
120            if let Ok(mut state) = thread_state.lock() {
121                state.value = Some(result);
122                if let Some(waker) = state.waker.take() {
123                    drop(state);
124                    waker.wake();
125                }
126            }
127        });
128
129        match thread {
130            Ok(_) => self.spawn_with(BlockingFuture { state }, on_done),
131            Err(e) => {
132                // 线程创建失败:下一轮直接回报错误,任务不会永久挂起
133                let message = format!("spawn blocking thread: {e}");
134                self.spawn_with(async {}, move |_| on_done(Err(message)))
135            }
136        }
137    }
138
139    fn spawn_boxed(&self, future: Pin<Box<dyn Future<Output = ()>>>) -> TaskHandle {
140        let id = {
141            let mut inner = self.inner.borrow_mut();
142            let id = inner.next_id;
143            inner.next_id = inner.next_id.wrapping_add(1);
144            id
145        };
146
147        let cancelled = Rc::new(Cell::new(false));
148        let waker =
149            Waker::from(Arc::new(TaskWake { id, ready: Arc::clone(&self.ready), wake: Arc::clone(&self.wake) }));
150
151        self.inner.borrow_mut().tasks.insert(id, TaskEntry { future, waker, cancelled: Rc::clone(&cancelled) });
152        if let Ok(mut ready) = self.ready.lock() {
153            ready.push_back(id);
154        }
155        (self.wake)();
156
157        TaskHandle { id, inner: Rc::downgrade(&self.inner), cancelled }
158    }
159
160    /// 轮询当前就绪队列;返回本轮实际 poll 的任务数。
161    ///
162    /// 在 UI 线程调用。任务在 poll 中新 spawn 的任务也会在同一轮处理
163    /// (最多 MAX_POLLS_PER_TURN 个)。
164    pub fn poll_ready(&self) -> usize {
165        let mut polled = 0;
166        for _ in 0..MAX_POLLS_PER_TURN {
167            let id = match self.ready.lock() {
168                Ok(mut ready) => ready.pop_front(),
169                Err(_) => return polled,
170            };
171            let Some(id) = id else {
172                return polled;
173            };
174            let Some(mut entry) = self.inner.borrow_mut().tasks.remove(&id) else {
175                continue;
176            };
177            if entry.cancelled.get() {
178                continue;
179            }
180
181            polled += 1;
182            let waker = entry.waker.clone();
183            let mut cx = Context::from_waker(&waker);
184            let result = std::panic::catch_unwind(AssertUnwindSafe(|| entry.future.as_mut().poll(&mut cx)));
185            match result {
186                Ok(Poll::Ready(())) => {}
187                Ok(Poll::Pending) => {
188                    // 回调里可能已 cancel 自己:不再放回队列
189                    if !entry.cancelled.get() {
190                        self.inner.borrow_mut().tasks.insert(id, entry);
191                    }
192                }
193                Err(payload) => {
194                    log::error!(
195                        target: "mgui_async",
196                        "task {id} panicked: {}",
197                        panic_message(payload.as_ref())
198                    );
199                }
200            }
201        }
202
203        // 达到上限时不再立即 wake:剩余任务留给下一帧,避免自唤醒 future
204        // 在单次事件循环里长时间独占 UI 线程(调用方会因 polled>0 请求重绘)。
205        polled
206    }
207
208    pub fn len(&self) -> usize {
209        self.inner.borrow().tasks.len()
210    }
211
212    pub fn is_empty(&self) -> bool {
213        self.len() == 0
214    }
215}
216
217impl std::fmt::Debug for TaskExecutor {
218    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
219        f.debug_struct("TaskExecutor").field("pending", &self.len()).finish_non_exhaustive()
220    }
221}
222
223struct BlockingState<T> {
224    value: Option<Result<T, String>>,
225    waker: Option<Waker>,
226}
227
228struct BlockingFuture<T> {
229    state: Arc<Mutex<BlockingState<T>>>,
230}
231
232impl<T> Future for BlockingFuture<T> {
233    type Output = Result<T, String>;
234
235    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
236        let mut state = match self.state.lock() {
237            Ok(state) => state,
238            Err(_) => return Poll::Ready(Err("blocking task state poisoned".to_string())),
239        };
240        if let Some(value) = state.value.take() {
241            return Poll::Ready(value);
242        }
243        state.waker = Some(cx.waker().clone());
244        Poll::Pending
245    }
246}
247
248struct TaskWake {
249    id: TaskId,
250    ready: Arc<Mutex<VecDeque<TaskId>>>,
251    wake: WakeCallback,
252}
253
254impl Wake for TaskWake {
255    fn wake(self: Arc<Self>) {
256        self.wake_by_ref();
257    }
258
259    fn wake_by_ref(self: &Arc<Self>) {
260        if let Ok(mut ready) = self.ready.lock() {
261            ready.push_back(self.id);
262        }
263        (self.wake)();
264    }
265}
266
267fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
268    if let Some(s) = payload.downcast_ref::<&str>() {
269        (*s).to_string()
270    } else if let Some(s) = payload.downcast_ref::<String>() {
271        s.clone()
272    } else {
273        "unknown panic payload".to_string()
274    }
275}
276
277// =================================================================
278// 简易 sleep(后台线程定时;示例/测试用,大量定时器后续换 timer wheel)
279// =================================================================
280
281struct SleepState {
282    done: bool,
283    waker: Option<Waker>,
284}
285
286/// 在后台线程计时的 sleep future。
287///
288/// 每次 sleep 创建一个短生命周期线程,适合示例与小规模异步 IO 模拟;
289/// 高频定时器场景后续应替换为集中式 timer wheel。
290pub struct Sleep {
291    duration: Duration,
292    state: Arc<Mutex<SleepState>>,
293    started: bool,
294}
295
296pub fn sleep(duration: Duration) -> Sleep {
297    Sleep { duration, state: Arc::new(Mutex::new(SleepState { done: false, waker: None })), started: false }
298}
299
300impl Future for Sleep {
301    type Output = ();
302
303    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
304        let this = self.get_mut();
305        let mut state = match this.state.lock() {
306            Ok(state) => state,
307            Err(_) => return Poll::Ready(()),
308        };
309        if state.done {
310            return Poll::Ready(());
311        }
312
313        if !this.started {
314            this.started = true;
315            let sleep_state = Arc::clone(&this.state);
316            let duration = this.duration;
317            let spawned = std::thread::Builder::new().name("mgui-sleep".to_string()).spawn(move || {
318                std::thread::sleep(duration);
319                if let Ok(mut state) = sleep_state.lock() {
320                    state.done = true;
321                    if let Some(waker) = state.waker.take() {
322                        drop(state);
323                        waker.wake();
324                    }
325                }
326            });
327            if spawned.is_err() {
328                // 线程创建失败:同步完成,避免任务永久挂起
329                state.done = true;
330                return Poll::Ready(());
331            }
332        }
333
334        state.waker = Some(cx.waker().clone());
335        Poll::Pending
336    }
337}
338
339#[cfg(test)]
340mod tests {
341    use super::*;
342    use std::sync::atomic::{AtomicBool, Ordering};
343    use std::time::Instant;
344
345    fn noop_wake() -> WakeCallback {
346        Arc::new(|| {})
347    }
348
349    #[test]
350    fn ready_task_runs_and_calls_back() {
351        let executor = TaskExecutor::new(noop_wake());
352        let value = Rc::new(Cell::new(0));
353        let out = Rc::clone(&value);
354        let _handle = executor.spawn_with(async { 7 }, move |v| out.set(v));
355
356        assert_eq!(executor.poll_ready(), 1);
357        assert_eq!(value.get(), 7);
358        assert!(executor.is_empty());
359    }
360
361    #[test]
362    fn waker_requeues_pending_task() {
363        struct WakeOnce(bool);
364        impl Future for WakeOnce {
365            type Output = ();
366            fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
367                if self.0 {
368                    Poll::Ready(())
369                } else {
370                    self.0 = true;
371                    cx.waker().wake_by_ref();
372                    Poll::Pending
373                }
374            }
375        }
376
377        let executor = TaskExecutor::new(noop_wake());
378        let done = Rc::new(Cell::new(false));
379        let out = Rc::clone(&done);
380        let _handle = executor.spawn_with(WakeOnce(false), move |_| out.set(true));
381
382        assert_eq!(executor.poll_ready(), 2);
383        assert!(done.get());
384        assert!(executor.is_empty());
385    }
386
387    #[test]
388    fn cancel_drops_task_without_callback() {
389        struct Never;
390        impl Future for Never {
391            type Output = ();
392            fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> {
393                Poll::Pending
394            }
395        }
396
397        let executor = TaskExecutor::new(noop_wake());
398        let called = Rc::new(Cell::new(false));
399        let out = Rc::clone(&called);
400        let handle = executor.spawn_with(Never, move |_| out.set(true));
401
402        handle.cancel();
403        assert_eq!(executor.poll_ready(), 0);
404        assert!(!called.get());
405        assert!(executor.is_empty());
406    }
407
408    #[test]
409    fn panic_isolated_from_other_tasks() {
410        let executor = TaskExecutor::new(noop_wake());
411        let done = Rc::new(Cell::new(false));
412        let out = Rc::clone(&done);
413
414        let _panicking = executor.spawn(async {
415            panic!("intentional task panic");
416        });
417        let _healthy = executor.spawn_with(async {}, move |_| out.set(true));
418
419        assert_eq!(executor.poll_ready(), 2);
420        assert!(done.get(), "panic task 不得阻止其它任务完成");
421        assert!(executor.is_empty());
422    }
423
424    #[test]
425    fn sleep_completes_via_background_waker() {
426        let executor = TaskExecutor::new(noop_wake());
427        let done = Rc::new(Cell::new(false));
428        let out = Rc::clone(&done);
429        let _handle = executor.spawn_with(sleep(Duration::from_millis(20)), move |_| out.set(true));
430
431        let start = Instant::now();
432        while !done.get() && start.elapsed() < Duration::from_secs(2) {
433            executor.poll_ready();
434            std::thread::sleep(Duration::from_millis(2));
435        }
436
437        assert!(done.get(), "sleep 任务应在后台 waker 唤醒后完成");
438        assert!(executor.is_empty());
439    }
440
441    #[test]
442    fn spawn_during_poll_is_driven_same_turn() {
443        let executor = TaskExecutor::new(noop_wake());
444        let executor_for_task = executor.clone();
445        let done = Rc::new(Cell::new(false));
446        let out = Rc::clone(&done);
447
448        let _outer = executor.spawn(async move {
449            executor_for_task.spawn_with(async {}, move |_| out.set(true));
450        });
451
452        assert_eq!(executor.poll_ready(), 2);
453        assert!(done.get());
454        assert!(executor.is_empty());
455    }
456
457    #[test]
458    fn spawn_blocking_returns_result_on_ui_thread() {
459        let executor = TaskExecutor::new(noop_wake());
460        let value = Rc::new(Cell::new(0));
461        let out = Rc::clone(&value);
462        let _handle = executor.spawn_blocking(|| Ok(42), move |result| out.set(result.unwrap_or_default()));
463
464        let start = Instant::now();
465        while value.get() == 0 && start.elapsed() < Duration::from_secs(2) {
466            executor.poll_ready();
467            std::thread::sleep(Duration::from_millis(2));
468        }
469        assert_eq!(value.get(), 42);
470        assert!(executor.is_empty());
471    }
472
473    #[test]
474    fn spawn_blocking_panic_becomes_error() {
475        let executor = TaskExecutor::new(noop_wake());
476        let failed = Rc::new(Cell::new(false));
477        let out = Rc::clone(&failed);
478        let _handle = executor.spawn_blocking(
479            || -> Result<(), String> { panic!("blocking panic") },
480            move |result| out.set(result.is_err()),
481        );
482
483        let start = Instant::now();
484        while !failed.get() && start.elapsed() < Duration::from_secs(2) {
485            executor.poll_ready();
486            std::thread::sleep(Duration::from_millis(2));
487        }
488        assert!(failed.get());
489    }
490
491    #[test]
492    fn wake_callback_invoked_for_cross_thread_spawn() {
493        let woke = Arc::new(AtomicBool::new(false));
494        let flag = Arc::clone(&woke);
495        let executor = TaskExecutor::new(Arc::new(move || {
496            flag.store(true, Ordering::SeqCst);
497        }));
498
499        let _handle = executor.spawn(async {});
500        assert!(woke.load(Ordering::SeqCst), "spawn 应唤醒事件循环");
501        executor.poll_ready();
502    }
503}