Skip to main content

pi_async_executor/
local.rs

1//! 所属线程(owner thread)的内部设施;普通业务不直接获得队列或原生所属域。
2use crate::{
3    parking::ThreadNotifier, registry::TaskRegistry, returns::ReturnQueue, state::ExecutorState,
4    timer::ExecutorTimer,
5};
6use pi_async_runtime_core::definitions::RuntimeId;
7use pi_async_task::{
8    definitions::{TaskId, TaskOwnerId},
9    Runnable, TaskRegistration, TaskThread,
10};
11use pi_async_task_queue::{timer::TimerSubmitError, QueuePushError, TaskQueue};
12use std::{
13    cell::{Cell, RefCell},
14    collections::{HashMap, VecDeque},
15    rc::Rc,
16    sync::Arc,
17};
18
19/// 本地设施(local facilities)的弱访问目标;不实现Send/Sync,不能跨线程借入。
20/// 公开给框架实现者用于静态接入,不向最终运行时(runtime)用户导出其实例。
21/// 释放(drop)时在原所属线程(owner thread)完成实际退出,仍在进行的同步活动可延迟最终释放。
22/// 原任务域与来源沿自身约定清理,首次恐慌(panic)继续传播;不可把关闭请求当成功确认。
23pub struct ExecutorLocal<T: ExecutorTimer + 'static> {
24    pub(crate) runtime: RuntimeId,
25    pub(crate) owner_id: TaskOwnerId,
26    pub(crate) owner: RefCell<Option<TaskThread>>,
27    pub(crate) ready: RefCell<Option<TaskQueue>>,
28    pub(crate) timer: RefCell<Option<T>>,
29    pub(crate) returns: RefCell<Option<ReturnQueue>>,
30    pub(crate) registry: RefCell<Option<TaskRegistry>>,
31    pub(crate) active: RefCell<HashMap<TaskId, ActiveRecord>>,
32    pub(crate) active_order: RefCell<VecDeque<TaskId>>,
33    pub(crate) state: Arc<ExecutorState>,
34    pub(crate) notifier: ThreadNotifier,
35    exit_requested: Cell<bool>,
36    exit_running: Cell<bool>,
37    source_failed: Cell<bool>,
38    exit_finished: Cell<bool>,
39}
40pub(crate) enum ActiveRecord {
41    Registered(Rc<TaskRegistration>),
42    Interrupted(pi_async_runtime_core::task::TaskQuery),
43}
44impl ActiveRecord {
45    fn snapshot(&self) -> pi_async_task::definitions::TaskSnapshot {
46        match self {
47            Self::Registered(r) => r.snapshot(),
48            Self::Interrupted(q) => q.snapshot(),
49        }
50    }
51}
52pub(crate) enum PreparedTask {
53    Business(Runnable, Rc<TaskRegistration>),
54    Cleanup(Runnable),
55    Settled(Runnable),
56}
57struct AdmissionAttemptGuard<'a, T: ExecutorTimer + 'static> {
58    local: &'a ExecutorLocal<T>,
59    task: &'a Runnable,
60    armed: bool,
61}
62impl<T: ExecutorTimer + 'static> Drop for AdmissionAttemptGuard<'_, T> {
63    fn drop(&mut self) {
64        admission_attempt_drop_inner(self)
65    }
66}
67enum LocalExitPhase {
68    Owner,
69    Ready,
70    Timer,
71    Returns,
72    Active,
73    Registry,
74    Finish,
75    Done,
76}
77struct LocalExitGuard<'a, T: ExecutorTimer + 'static> {
78    local: &'a ExecutorLocal<T>,
79    phase: LocalExitPhase,
80    current_failed: bool,
81    failed: bool,
82    domain_unconfirmed: usize,
83    admitted_unconfirmed: usize,
84}
85struct LocalActivityGuard<'a, T: ExecutorTimer + 'static> {
86    local: &'a ExecutorLocal<T>,
87}
88struct ReadyReleaseGuard<'a> {
89    state: &'a ExecutorState,
90    count: usize,
91}
92// 唯一TaskThread放Option中;只有共享不可变owner借用能跨一次poll/用户调用。
93// ready/timer/returns/registry/index/TLS可写借用必须在调用用户逻辑前全部结束。
94// 每次本地操作由TLS升级的临时Rc保活;退出先记意图,owner尚被借用则延后真实take。
95// 下一安全作用域结束或最后Local Drop继续;不强行穿透RefCell、转型生命周期或新增锁。
96// 真正TaskThread Drop -> ready/timer -> Returns OWNER_GONE -> active -> registry seal。
97// 原域失败统计在TaskThread真正结束后、registry移走前查询,失败不伪造Completed。
98impl<T: ExecutorTimer + 'static> ExecutorLocal<T> {
99    pub(crate) fn new(
100        runtime: RuntimeId,
101        owner: TaskThread,
102        ready: TaskQueue,
103        timer: T,
104        returns: ReturnQueue,
105        registry: TaskRegistry,
106        state: Arc<ExecutorState>,
107        notifier: ThreadNotifier,
108    ) -> Self {
109        local_new_inner(
110            runtime, owner, ready, timer, returns, registry, state, notifier,
111        )
112    }
113    pub fn runtime_id(&self) -> RuntimeId {
114        self.runtime
115    }
116    /// 同步框架访问;不允许返回owner借用。只读Ref可跨本次调用,不持其它队列借用。
117    pub fn with_owner<R>(&self, action: impl FnOnce(&TaskThread) -> R) -> pi_result::Result<R> {
118        local_owner_inner(self, action)
119    }
120    /// 原线程尾插/头插,尚未接纳的create_local可排队;不在此poll或提前admit。
121    /// 正常新入队用同一ExecutorState记数,拒绝返还原值。
122    pub fn try_push(
123        &self,
124        task: Runnable,
125        front: bool,
126    ) -> pi_result::RawResult<(), QueuePushError> {
127        local_push_inner(self, task, front)
128    }
129    /// 同源定时本地提交;不为Item添加Send/Sync,不刷新时钟。
130    pub fn try_push_timer(
131        &self,
132        deadline: T::Instant,
133        item: T::Item,
134    ) -> pi_result::RawResult<T::Key, TimerSubmitError<T::Item>> {
135        local_timer_push_inner(self, deadline, item)
136    }
137    pub(crate) fn selected(&self, task: Runnable) -> pi_result::Result<PreparedTask> {
138        local_selected_inner(self, task)
139    }
140    pub(crate) fn maintain(&self, max_nodes: usize) {
141        local_maintain_inner(self, max_nodes)
142    }
143    pub(crate) fn finish_exit(&self, source_failed: bool) -> bool {
144        local_finish_exit_inner(self, source_failed)
145    }
146}
147impl<T: ExecutorTimer + 'static> Drop for ExecutorLocal<T> {
148    fn drop(&mut self) {
149        local_drop_inner(self)
150    }
151}
152impl<T: ExecutorTimer + 'static> Drop for LocalActivityGuard<'_, T> {
153    fn drop(&mut self) {
154        local_activity_drop_inner(self)
155    }
156}
157impl Drop for ReadyReleaseGuard<'_> {
158    fn drop(&mut self) {
159        ready_release_inner(self)
160    }
161}
162impl<T: ExecutorTimer + 'static> LocalExitGuard<'_, T> {
163    fn drain(&mut self) {
164        local_exit_drain_inner(self)
165    }
166}
167impl<T: ExecutorTimer + 'static> Drop for LocalExitGuard<'_, T> {
168    fn drop(&mut self) {
169        local_exit_drop_inner(self)
170    }
171}
172include!("local_inner.rs");