Skip to main content

pi_async_executor/
parking.rs

1//! 绑定线程(thread)的主动通知与被动限时返回,不是任务唤醒器(Waker)。
2use pi_async_runtime_core::task::TaskNotifier;
3use pi_async_task_queue::notify::QueueNotifier;
4use std::{
5    marker::PhantomData,
6    rc::Rc,
7    sync::{atomic::AtomicBool, Arc},
8    thread::{Thread, ThreadId},
9    time::Duration,
10};
11
12/// 原线程的透明通知句柄(notification handle),支持Clone+Send+Sync。
13///
14/// 只保住线程通知状态,不保住原Future或完整服务。并发通知合并,不为一次通知创建任务。
15/// 只保证安排线程重新检查,不承诺已经轮询任务或完成取消/关闭。
16pub struct ThreadNotifier {
17    shared: Arc<ThreadNotification>,
18}
19struct ThreadNotification {
20    thread: Thread,
21    notified: AtomicBool,
22}
23impl Clone for ThreadNotifier {
24    fn clone(&self) -> Self {
25        Self {
26            shared: Arc::clone(&self.shared),
27        }
28    }
29}
30impl QueueNotifier for ThreadNotifier {
31    /// 先Release记录通知,再按需unpark同一线程;已存在通知时合并。
32    fn notify(&self) {
33        thread_notify_inner(&self.shared)
34    }
35}
36impl TaskNotifier for ThreadNotifier {}
37
38/// 只有创建线程可以停放和消费通知;不可跨线程转移或共享。
39///
40/// 提交、任务唤醒、取消和关闭的实际发布者通过[`ThreadNotifier`]通知。
41/// 策略、来源重查和最迟再次检查时刻由执行器负责,本对象不判断空闲,不访问队列。
42pub struct ThreadParker {
43    notifier: ThreadNotifier,
44    owner: ThreadId,
45    local: PhantomData<Rc<()>>,
46}
47/// 标准线程停放允许伪唤醒;不能把一次返回伪报成已经到达截止时间。
48#[derive(Clone, Copy, Debug, Eq, PartialEq)]
49pub enum ThreadParkResult {
50    /// 已取得一次实际通知;对外工作仍须重新检查。
51    Notified,
52    /// 超时、伪唤醒或零时长返回,须重查,不保证发生过主动通知。
53    Recheck,
54}
55impl ThreadParker {
56    /// 绑定当前线程,准备一份共享通知状态,初始notified=true以安排首次检查。
57    pub fn new() -> Self {
58        thread_parker_new_inner()
59    }
60    /// 克隆同一原线程的受限通知,不产生另一个停放拥有者。
61    pub fn notifier(&self) -> ThreadNotifier {
62        self.notifier.clone()
63    }
64    /// 读取固定原线程身份,不取得其它线程推进权。
65    pub fn owner_thread(&self) -> ThreadId {
66        self.owner
67    }
68    /// Acquire取样,不消费通知,不证明下一瞬间可以休眠。
69    pub fn is_notified(&self) -> bool {
70        thread_is_notified_inner(&self.notifier.shared)
71    }
72    /// 原线程一次Acquire交换,取走现有通知;取走后必须实际重新检查工作。
73    pub fn take_notification(&mut self) -> bool {
74        thread_take_notification_inner(self)
75    }
76    /// 通知存在则直接返回,否则限时停放,返回后再次取得通知并重新分类。
77    ///
78    /// `duration`是调用方选定的本次上限,零不等待。休眠策略与定时来源最迟检查时刻须
79    /// 在调用前组合;本层不擅自延长上限。最后通知检查到实际park之间不得执行用户回调、
80    /// 日志或另一个park,以免其它代码消费同一线程permit。任何返回都需要上层重查来源。
81    /// 系统调度可能延迟线程恢复,本函数不承诺墙钟硬上界。
82    pub fn park_timeout(&mut self, duration: Duration) -> ThreadParkResult {
83        thread_park_inner(self, duration)
84    }
85}
86impl Default for ThreadParker {
87    fn default() -> Self {
88        Self::new()
89    }
90}
91include!("parking_inner.rs");