Skip to main content

pi_async_rt/rt/
serial.rs

1use std::thread;
2use std::any::Any;
3use std::pin::Pin;
4use std::ptr::null_mut;
5use std::vec::IntoIter;
6use std::time::Duration;
7use std::future::Future;
8use std::marker::PhantomData;
9use std::ops::{Deref, DerefMut};
10use std::cell::{RefCell, UnsafeCell};
11use std::task::{Poll, Waker, Context};
12use std::io::{Error, Result, ErrorKind};
13use std::fmt::{Debug, Formatter, Result as FmtResult};
14use std::sync::{Arc, atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering}};
15
16use futures::{future::{FutureExt, LocalBoxFuture},
17              stream::{Stream, StreamExt, LocalBoxStream},
18              task::{ArcWake, AtomicWaker}};
19use parking_lot::{Mutex, Condvar};
20use crossbeam_queue::ArrayQueue;
21use crossbeam_channel::{Sender, Receiver, unbounded};
22use flume::{Sender as AsyncSender, Receiver as AsyncReceiver};
23#[cfg(not(target_arch = "wasm32"))]
24use polling::Poller;
25use num_cpus;
26
27use pi_cancel_timer::Timer;
28use slotmap::{Key, KeyData};
29use quanta::{Clock, Instant as QInstant};
30
31use crate::{lock::spin,
32            rt::{PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME, TaskId, AsyncPipelineResult,
33                 TimeoutWaiter, wake_thread_waker, wake_waiting_worker,
34                 ASYNC_VALUE_EMPTY, ASYNC_VALUE_WAITING, ASYNC_VALUE_SETTING,
35                 ASYNC_VALUE_READY, ASYNC_VALUE_TAKING, ASYNC_VALUE_CONSUMED,
36                 serial_local_thread::{LocalTaskRunner, LocalTaskRuntime},
37                 serial_single_thread::SingleTaskRuntime,
38                 serial_worker_thread::{WorkerTaskRunner, WorkerRuntime}}};
39
40///
41/// 顺序执行的异步任务
42///
43pub struct AsyncTask<
44    P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
45    O: Default + 'static = (),
46> {
47    uid:        TaskId,                                     //任务唯一id
48    future:     Mutex<Option<LocalBoxFuture<'static, O>>>,  //异步任务
49    pool:       Arc<P>,                                     //异步任务池
50    priority:   usize,                                      //异步任务优先级
51    context:    Option<UnsafeCell<Box<dyn Any>>>,           //异步任务上下文
52}
53
54unsafe impl<
55    P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
56    O: Default + 'static,
57> Send for AsyncTask<P, O> {}
58unsafe impl<
59    P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
60    O: Default + 'static,
61> Sync for AsyncTask<P, O> {}
62
63impl<
64    P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P>,
65    O: Default + 'static,
66> ArcWake for AsyncTask<P, O> {
67    fn wake_by_ref(arc_self: &Arc<Self>) {
68        let pool = arc_self.get_pool();
69        let _ = pool.push_keep(arc_self.clone());
70
71        if let Some(waits) = pool.get_waits() {
72            //当前任务属于多线程异步运行时
73            let _ = wake_waiting_worker(waits);
74        } else {
75            //当前线程属于单线程异步运行时
76            if let Some(thread_waker) = pool.get_thread_waker() {
77                let _ = wake_thread_waker(thread_waker);
78            }
79        }
80    }
81}
82
83impl<
84    P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P>,
85    O: Default + 'static,
86> AsyncTask<P, O> {
87    /// 构建单线程任务
88    pub fn new(uid: TaskId,
89               pool: Arc<P>,
90               priority: usize,
91               future: Option<LocalBoxFuture<'static, O>>) -> AsyncTask<P, O> {
92        AsyncTask {
93            uid,
94            future: Mutex::new(future),
95            pool,
96            priority,
97            context: None,
98        }
99    }
100
101    /// 使用指定上下文构建单线程任务
102    pub fn with_context<C: 'static>(uid: TaskId,
103                                    pool: Arc<P>,
104                                    priority: usize,
105                                    future: Option<LocalBoxFuture<'static, O>>,
106                                    context: C) -> AsyncTask<P, O> {
107        let any = Box::new(context);
108
109        AsyncTask {
110            uid,
111            future: Mutex::new(future),
112            pool,
113            priority,
114            context: Some(UnsafeCell::new(any)),
115        }
116    }
117
118    /// 使用指定异步运行时和上下文构建单线程任务
119    pub fn with_runtime_and_context<RT, C>(runtime: &RT,
120                                           priority: usize,
121                                           future: Option<LocalBoxFuture<'static, O>>,
122                                           context: C) -> AsyncTask<P, O>
123        where RT: AsyncRuntime<O, Pool = P>,
124              C: 'static {
125        let any = Box::new(context);
126
127        AsyncTask {
128            uid: runtime.alloc::<O>(),
129            future: Mutex::new(future),
130            pool: runtime.shared_pool(),
131            priority,
132            context: Some(UnsafeCell::new(any)),
133        }
134    }
135
136    /// 检查是否允许唤醒
137    pub fn is_enable_wakeup(&self) -> bool {
138        self.uid.exist_waker::<O>()
139    }
140
141    /// 获取内部任务
142    pub fn get_inner(&self) -> Option<LocalBoxFuture<'static, O>> {
143        self.future.lock().take()
144    }
145
146    /// 设置内部任务
147    pub fn set_inner(&self, inner: Option<LocalBoxFuture<'static, O>>) {
148        *self.future.lock() = inner;
149    }
150
151    /// 获取任务的所有者
152    #[inline]
153    pub fn owner(&self) -> usize {
154        unsafe {
155            *self.uid.0.get() as usize
156        }
157    }
158
159    /// 获取异步任务优先级
160    pub fn priority(&self) -> usize {
161        self.priority
162    }
163
164    //判断异步任务是否有上下文
165    pub fn exist_context(&self) -> bool {
166        self.context.is_some()
167    }
168
169    //获取异步任务上下文的只读引用
170    pub fn get_context<C: 'static>(&self) -> Option<&C> {
171        if let Some(context) = &self.context {
172            //存在上下文
173            let any = unsafe { &*context.get() };
174            return <dyn Any>::downcast_ref::<C>(&**any);
175        }
176
177        None
178    }
179
180    //获取异步任务上下文的可写引用
181    pub fn get_context_mut<C: 'static>(&self) -> Option<&mut C> {
182        if let Some(context) = &self.context {
183            //存在上下文
184            let any = unsafe { &mut *context.get() };
185            return <dyn Any>::downcast_mut::<C>(&mut **any);
186        }
187
188        None
189    }
190
191    //设置异步任务上下文,返回上一个异步任务上下文
192    pub fn set_context<C: 'static>(&self, new: C) {
193        if let Some(context) = &self.context {
194            //存在上一个上下文,则释放上一个上下文
195            let _ = unsafe { &*context.get() };
196
197            //设置新的上下文
198            let any: Box<dyn Any + 'static> = Box::new(new);
199            unsafe { *context.get() = any; }
200        }
201    }
202
203    //获取异步任务的任务池
204    pub fn get_pool(&self) -> &P {
205        self.pool.as_ref()
206    }
207}
208
209///
210/// 异步任务池
211///
212pub trait AsyncTaskPool<O: Default + 'static = ()>: Default + 'static {
213    type Pool: AsyncTaskPoolExt<O> + AsyncTaskPool<O>;
214
215    /// 获取绑定的线程唯一id
216    fn get_thread_id(&self) -> usize;
217
218    /// 获取当前异步任务池内任务数量
219    fn len(&self) -> usize;
220
221    /// 将异步任务加入异步任务池
222    fn push(&self, task: Arc<AsyncTask<Self::Pool, O>>) -> Result<()>;
223
224    /// 将异步任务加入本地异步任务池
225    fn push_local(&self, task: Arc<AsyncTask<Self::Pool, O>>) -> Result<()>;
226
227    /// 将指定了优先级的异步任务加入任务池
228    fn push_priority(&self, priority: usize, task: Arc<AsyncTask<Self::Pool, O>>) -> Result<()>;
229
230    /// 异步任务被唤醒时,将异步任务继续加入异步任务池
231    fn push_keep(&self, task: Arc<AsyncTask<Self::Pool, O>>) -> Result<()>;
232
233    /// 尝试从异步任务池中弹出一个异步任务
234    fn try_pop(&self) -> Option<Arc<AsyncTask<Self::Pool, O>>>;
235
236    /// 尝试从异步任务池中弹出所有异步任务
237    fn try_pop_all(&self) -> IntoIter<Arc<AsyncTask<Self::Pool, O>>>;
238
239    /// 获取本地线程的唤醒器
240    fn get_thread_waker(&self) -> Option<&Arc<(AtomicBool, Mutex<()>, Condvar)>> {
241        None
242    }
243}
244
245///
246/// 异步任务池扩展
247///
248pub trait AsyncTaskPoolExt<O: Default + 'static = ()>: 'static {
249    /// 设置待唤醒的工作者唤醒器队列
250    fn set_waits(&mut self,
251                 _waits: Arc<ArrayQueue<Arc<(AtomicBool, Mutex<()>, Condvar)>>>) {}
252
253    /// 获取待唤醒的工作者唤醒器队列
254    fn get_waits(&self) -> Option<&Arc<ArrayQueue<Arc<(AtomicBool, Mutex<()>, Condvar)>>>> {
255        //默认没有待唤醒的工作者唤醒器队列
256        None
257    }
258
259    /// 获取空闲的工作者的数量,这个数量大于0,表示可以新开线程来运行可分派的工作者
260    fn idler_len(&self) -> usize {
261        //默认不分派
262        0
263    }
264
265    /// 分派一个空闲的工作者
266    fn spawn_worker(&self) -> Option<usize> {
267        //默认不分派
268        None
269    }
270
271    /// 获取工作者的数量
272    fn worker_len(&self) -> usize {
273        //默认工作者数量和本机逻辑核数相同
274        #[cfg(not(target_arch = "wasm32"))]
275        return num_cpus::get();
276        #[cfg(target_arch = "wasm32")]
277        return 1;
278    }
279
280    /// 获取缓冲区的任务数量,缓冲区任务是未分配给工作者的任务
281    fn buffer_len(&self) -> usize {
282        //默认没有缓冲区
283        0
284    }
285
286    /// 设置当前绑定本地线程的唤醒器
287    fn set_thread_waker(&mut self, _thread_waker: Arc<(AtomicBool, Mutex<()>, Condvar)>) {
288        //默认不设置
289    }
290
291    /// 复制当前绑定本地线程的唤醒器
292    fn clone_thread_waker(&self) -> Option<Arc<(AtomicBool, Mutex<()>, Condvar)>> {
293        //默认不复制
294        None
295    }
296
297    /// 关闭当前工作者
298    fn close_worker(&self) {
299        //默认不允许关闭工作者
300    }
301}
302
303///
304/// 顺序执行任务的异步运行时
305///
306pub trait AsyncRuntime<O: Default + 'static = ()>: Clone + Send + Sync + 'static {
307    type Pool: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = Self::Pool>;
308
309    /// 共享运行时内部任务池
310    fn shared_pool(&self) -> Arc<Self::Pool>;
311
312    /// 获取当前异步运行时的唯一id
313    fn get_id(&self) -> usize;
314
315    /// 获取当前异步运行时待处理任务数量
316    fn wait_len(&self) -> usize;
317
318    /// 获取当前异步运行时任务数量
319    fn len(&self) -> usize;
320
321    /// 分配异步任务的唯一id
322    fn alloc<R: 'static>(&self) -> TaskId;
323
324    /// 派发一个指定的异步任务到异步运行时
325    fn spawn<F>(&self, future: F) -> Result<TaskId>
326        where F: Future<Output = O> + 'static;
327
328    /// 派发一个异步任务到本地异步运行时,如果本地没有本异步运行时,则会派发到当前运行时中
329    fn spawn_local<F>(&self, future: F) -> Result<TaskId>
330        where F: Future<Output = O> + 'static;
331
332    /// 派发一个指定优先级的异步任务到异步运行时
333    fn spawn_priority<F>(&self, priority: usize, future: F) -> Result<TaskId>
334        where F: Future<Output = O> + 'static;
335
336    /// 派发一个异步任务到异步运行时,并立即让出任务的当前运行
337    fn spawn_yield<F>(&self, future: F) -> Result<TaskId>
338        where F: Future<Output = O> + 'static;
339
340    /// 派发一个在指定时间后执行的异步任务到异步运行时,时间单位ms
341    fn spawn_timing<F>(&self, future: F, time: usize) -> Result<TaskId>
342        where F: Future<Output = O> + 'static;
343
344    /// 派发一个指定任务唯一id的异步任务到异步运行时
345    fn spawn_by_id<F>(&self, task_id: TaskId, future: F) -> Result<()>
346        where F: Future<Output = O> + 'static;
347
348    /// 派发一个指定任务唯一id的异步任务到本地异步运行时,如果本地没有本异步运行时,则会派发到当前运行时中
349    fn spawn_local_by_id<F>(&self, task_id: TaskId, future: F) -> Result<()>
350        where F: Future<Output = O> + 'static;
351
352    /// 派发一个指定任务唯一id和任务优先级的异步任务到异步运行时
353    fn spawn_priority_by_id<F>(&self,
354                               task_id: TaskId,
355                               priority: usize,
356                               future: F) -> Result<()>
357        where F: Future<Output = O> + 'static;
358
359    /// 派发一个指定任务唯一id的异步任务到异步运行时,并立即让出任务的当前运行
360    fn spawn_yield_by_id<F>(&self, task_id: TaskId, future: F) -> Result<()>
361        where F: Future<Output = O> + 'static;
362
363    /// 派发一个指定任务唯一id和在指定时间后执行的异步任务到异步运行时,时间单位ms
364    fn spawn_timing_by_id<F>(&self,
365                             task_id: TaskId,
366                             future: F,
367                             time: usize) -> Result<()>
368        where F: Future<Output = O> + 'static;
369
370    /// 挂起指定唯一id的异步任务
371    fn pending<Output: 'static>(&self, task_id: &TaskId, waker: Waker) -> Poll<Output>;
372
373    /// 唤醒指定唯一id的异步任务
374    fn wakeup<Output: 'static>(&self, task_id: &TaskId);
375
376    /// 挂起当前异步运行时的当前任务,并在指定的其它运行时上派发一个指定的异步任务,等待其它运行时上的异步任务完成后,唤醒当前运行时的当前任务,并返回其它运行时上的异步任务的值
377    fn wait<V: 'static>(&self) -> AsyncWait<V>;
378
379    /// 挂起当前异步运行时的当前任务,并在多个其它运行时上执行多个其它任务,其中任意一个任务完成,则唤醒当前运行时的当前任务,并返回这个已完成任务的值,而其它未完成的任务的值将被忽略
380    fn wait_any<V: 'static>(&self, capacity: usize) -> AsyncWaitAny<V>;
381
382    /// 挂起当前异步运行时的当前任务,并在多个其它运行时上执行多个其它任务,任务返回后需要通过用户指定的检查回调进行检查,其中任意一个任务检查通过,则唤醒当前运行时的当前任务,并返回这个已完成任务的值,而其它未完成或未检查通过的任务的值将被忽略,如果所有任务都未检查通过,则强制唤醒当前运行时的当前任务
383    fn wait_any_callback<V: 'static>(&self, capacity: usize) -> AsyncWaitAnyCallback<V>;
384
385    /// 构建用于派发多个异步任务到指定运行时的映射归并,需要指定映射归并的容量
386    fn map_reduce<V: 'static>(&self, capacity: usize) -> AsyncMapReduce<V>;
387
388    /// 挂起当前异步运行时的当前任务,等待指定的时间后唤醒当前任务
389    fn timeout(&self, timeout: usize) -> LocalBoxFuture<'static, ()>;
390
391    /// 立即让出当前任务的执行
392    fn yield_now(&self) -> LocalBoxFuture<'static, ()>;
393
394    /// 生成一个异步管道,输入指定流,输入流的每个值通过过滤器生成输出流的值
395    fn pipeline<S, SO, F, FO>(&self, input: S, filter: F) -> LocalBoxStream<'static, FO>
396        where S: Stream<Item = SO> + 'static,
397              SO: 'static,
398              F: FnMut(SO) -> AsyncPipelineResult<FO> + 'static,
399              FO: 'static;
400
401    /// 关闭异步运行时,返回请求关闭是否成功
402    fn close(&self) -> bool;
403}
404
405///
406/// 顺序执行的异步运行时扩展
407///
408pub trait AsyncRuntimeExt<O: Default + 'static = ()> {
409    /// 派发一个指定的异步任务到异步运行时,并指定异步任务的初始化上下文
410    fn spawn_with_context<F, C>(&self,
411                                task_id: TaskId,
412                                future: F,
413                                context: C) -> Result<()>
414        where F: Future<Output = O> + 'static,
415              C: 'static;
416
417    /// 派发一个在指定时间后执行的异步任务到异步运行时,并指定异步任务的初始化上下文,时间单位ms
418    fn spawn_timing_with_context<F, C>(&self,
419                                       task_id: TaskId,
420                                       future: F,
421                                       context: C,
422                                       time: usize) -> Result<()>
423        where F: Future<Output = O> + 'static,
424              C: 'static;
425
426    /// 立即创建一个指定任务池的异步运行时,并执行指定的异步任务,阻塞当前线程,等待异步任务完成后返回
427    fn block_on<F>(&self, future: F) -> Result<F::Output>
428        where F: Future + 'static,
429              <F as Future>::Output: Default + 'static;
430}
431
432///
433/// 异步运行时构建器
434///
435pub struct AsyncRuntimeBuilder<O: Default + 'static = ()>(PhantomData<O>);
436
437impl<O: Default + 'static> AsyncRuntimeBuilder<O> {
438    /// 构建默认的本地异步任务运行时
439    pub fn default_local_thread(name: Option<&str>,
440                                stack_size: Option<usize>) -> LocalTaskRuntime<O> {
441        let runner = LocalTaskRunner::new();
442
443        let thread_name = if let Some(name) = name {
444            name
445        } else {
446            //默认的线程名称
447            "Default-Local-RT"
448        };
449        let thread_stack_size = if let Some(size) = stack_size {
450            size
451        } else {
452            //默认的线程堆栈大小
453            2 * 1024 * 1024
454        };
455
456        runner.startup(thread_name, thread_stack_size)
457    }
458
459    /// 构建默认的工作者异步运行时
460    pub fn default_worker_thread(worker_name: Option<&str>,
461                                 worker_stack_size: Option<usize>,
462                                 worker_sleep_timeout: Option<u64>,
463                                 worker_loop_interval: Option<Option<u64>>) -> WorkerRuntime<O> {
464        let runner = WorkerTaskRunner::default();
465
466        let thread_name = if let Some(name) = worker_name {
467            name
468        } else {
469            //默认的线程名称
470            "Default-Single-Worker"
471        };
472        let thread_stack_size = if let Some(size) = worker_stack_size {
473            size
474        } else {
475            //默认的线程堆栈大小
476            2 * 1024 * 1024
477        };
478        let sleep_timeout = if let Some(timeout) = worker_sleep_timeout {
479            timeout
480        } else {
481            //默认的线程休眠时长
482            1
483        };
484        let loop_interval = if let Some(interval) = worker_loop_interval {
485            interval
486        } else {
487            //默认的线程循环间隔时长
488            None
489        };
490
491        //创建线程并在线程中执行异步运行时
492        let clock = Clock::new();
493        let runner_copy = runner.clone();
494        let rt_copy = runner.get_runtime();
495        let rt = runner.startup(
496            thread_name,
497            thread_stack_size,
498            sleep_timeout,
499            loop_interval,
500            move || {
501                let now = clock.recent();
502                match runner_copy.run_once() {
503                    Err(e) => {
504                        panic!("Run runner failed, reason: {:?}", e);
505                    },
506                    Ok(len) => {
507                        (len == 0,
508                         clock
509                             .recent()
510                             .duration_since(now))
511                    },
512                }
513            },
514            move || {
515                rt_copy.wait_len() + rt_copy.len()
516            },
517        );
518
519        rt
520    }
521
522    /// 构建自定义的本地异步任务运行时
523    #[cfg(not(target_arch = "wasm32"))]
524    pub fn custom_local_thread(name: Option<&str>,
525                               stack_size: Option<usize>,
526                               poller: Option<Arc<Poller>>,
527                               try_count: Option<usize>,
528                               timeout: Option<Duration>,) -> LocalTaskRuntime<O> {
529        let poller = if let Some(poller) = poller {
530            poller
531        } else {
532            Arc::new(Poller::new().expect("Failed to create poller"))
533        };
534        let runner = LocalTaskRunner::with_poll(poller);
535
536        let thread_name = if let Some(name) = name {
537            name
538        } else {
539            //默认的线程名称
540            "Custom-Local-RT"
541        };
542        let thread_stack_size = if let Some(size) = stack_size {
543            size
544        } else {
545            //默认的线程堆栈大小
546            2 * 1024 * 1024
547        };
548        let try_count = try_count.unwrap_or(3);
549
550        runner.startup_with_poll(
551            thread_name,
552            thread_stack_size,
553            try_count,
554            timeout
555        )
556    }
557
558    /// 构建自定义的工作者异步运行时
559    pub fn custom_worker_thread<P, F0, F1>(pool: P,
560                                           worker_handle: Arc<AtomicBool>,
561                                           worker_condvar: Arc<(AtomicBool, Mutex<()>, Condvar)>,
562                                           thread_name: &str,
563                                           thread_stack_size: usize,
564                                           sleep_timeout: u64,
565                                           loop_interval: Option<u64>,
566                                           loop_func: F0,
567                                           get_queue_len: F1) -> WorkerRuntime<O, P>
568        where P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P>,
569              F0: Fn() -> (bool, Duration) + Send + 'static,
570              F1: Fn() -> usize + Send + 'static {
571        let runner = WorkerTaskRunner::new(pool,
572                                           worker_handle,
573                                           worker_condvar);
574
575        //创建线程并在线程中执行异步运行时
576        let rt_copy = runner.get_runtime();
577        let rt = runner.startup(
578            thread_name,
579            thread_stack_size,
580            sleep_timeout,
581            loop_interval,
582            loop_func,
583            move || {
584                rt_copy.wait_len() + get_queue_len()
585            },
586        );
587
588        rt
589    }
590}
591
592/// 绑定指定异步运行时到本地线程
593pub fn bind_local_thread<O: Default + 'static>(runtime: LocalAsyncRuntime<O>) {
594    match PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME.try_with(move |rt| {
595        let raw = Arc::into_raw(Arc::new(runtime)) as *mut LocalAsyncRuntime<O> as *mut ();
596        rt.store(raw, Ordering::Relaxed);
597    }) {
598        Err(e) => {
599            panic!("Bind single runtime to local thread failed, reason: {:?}", e);
600        },
601        Ok(_) => (),
602    }
603}
604
605/// 从本地线程解绑单线程异步任务执行器
606pub fn unbind_local_thread() {
607    let _ = PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME.try_with(move |rt| {
608        rt.store(null_mut(), Ordering::Relaxed);
609    });
610}
611
612///
613/// 本地线程绑定的异步运行时
614///
615pub struct LocalAsyncRuntime<O: Default + 'static> {
616    inner:              *const (),                                                          //内部运行时指针
617    get_id_func:        fn(*const ()) -> usize,                                             //获取本地运行时的id的函数
618    spawn_func:         fn(*const (), LocalBoxFuture<'static, O>) -> Result<()>,            //本地派发函数
619    spawn_local_func:   fn(*const (), LocalBoxFuture<'static, O>) -> Result<()>,            //本地派发函数
620    spawn_timing_func:  fn(*const (), LocalBoxFuture<'static, O>, usize) -> Result<()>,     //定时派发函数
621    timeout_func:       fn(*const (), usize) -> LocalBoxFuture<'static, ()>,                //超时函数
622}
623
624unsafe impl<O: Default + 'static> Send for LocalAsyncRuntime<O> {}
625unsafe impl<O: Default + 'static> Sync for LocalAsyncRuntime<O> {}
626
627impl<O: Default + 'static> LocalAsyncRuntime<O> {
628    /// 创建本地线程绑定的异步运行时
629    pub fn new(inner: *const (),
630               get_id_func: fn(*const ()) -> usize,
631               spawn_func: fn(*const (), LocalBoxFuture<'static, O>) -> Result<()>,
632               spawn_timing_func: fn(*const (), LocalBoxFuture<'static, O>, usize) -> Result<()>,
633               timeout_func: fn(*const (), usize) -> LocalBoxFuture<'static, ()>) -> Self {
634        LocalAsyncRuntime {
635            inner,
636            get_id_func,
637            spawn_func,
638            spawn_local_func: spawn_func,
639            spawn_timing_func,
640            timeout_func,
641        }
642    }
643
644    /// 获取本地运行时的id
645    #[inline]
646    pub fn get_id(&self) -> usize {
647        (self.get_id_func)(self.inner)
648    }
649
650    /// 派发一个指定的异步任务到本地线程绑定的异步运行时
651    #[inline]
652    pub fn spawn<F>(&self, future: F) -> Result<()>
653        where F: Future<Output = O> + 'static {
654        (self.spawn_func)(self.inner, async move {
655            future.await
656        }.boxed_local())
657    }
658
659    /// 派发一个指定的异步任务到本地线程绑定的异步运行时
660    #[inline]
661    pub fn spawn_local<F>(&self, future: F) -> Result<()>
662    where F: Future<Output = O> + 'static {
663        (self.spawn_local_func)(self.inner, async move {
664            future.await
665        }.boxed_local())
666    }
667
668    /// 定时派发一个指定的异步任务到本地线程绑定的异步运行时
669    #[inline]
670    pub fn sapwn_timing_func<F>(&self, future: F, timeout: usize) -> Result<()>
671        where F: Future<Output = O> + 'static {
672        (self.spawn_timing_func)(self.inner,
673                                 async move {
674                                     future.await
675                                 }.boxed_local(),
676                                 timeout)
677    }
678
679    /// 挂起本地线程绑定的异步运行时的当前任务,等待指定的时间后唤醒当前任务
680    #[inline]
681    pub fn timeout(&self, timeout: usize) -> LocalBoxFuture<'static, ()> {
682        (self.timeout_func)(self.inner, timeout)
683    }
684}
685
686///
687/// 获取本地线程绑定的顺序执行任务的异步运行时
688/// 注意:O如果与本地线程绑定的运行时的O不相同,则无法获取本地线程绑定的运行时
689///
690pub fn local_serial_async_runtime<O: Default + 'static>() -> Option<Arc<LocalAsyncRuntime<O>>> {
691    match PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME.try_with(move |ptr| {
692        let raw = ptr.load(Ordering::Relaxed) as *const LocalAsyncRuntime<O>;
693        unsafe {
694            if raw.is_null() {
695                //本地线程未绑定异步运行时
696                None
697            } else {
698                //本地线程已绑定异步运行时
699                let shared: Arc<LocalAsyncRuntime<O>> = unsafe { Arc::from_raw(raw) };
700                let result = shared.clone();
701                Arc::into_raw(shared); //避免提前释放
702                Some(result)
703            }
704        }
705    }) {
706        Err(_) => None, //本地线程没有绑定异步运行时
707        Ok(rt) => rt,
708    }
709}
710
711///
712/// 派发任务到本地线程绑定的异步运行时,如果本地线程没有异步运行时,则返回错误
713/// 注意:F::Output如果与本地线程绑定的运行时的O不相同,则无法执行指定任务
714///
715pub fn spawn_local<O, F>(future: F) -> Result<()>
716    where O: Default + 'static,
717          F: Future<Output = O> + 'static {
718    if let Some(rt) = local_serial_async_runtime::<O>() {
719        rt.spawn(future)
720    } else {
721        Err(Error::new(ErrorKind::Other, format!("Spawn task to local thread failed, reason: runtime not exist")))
722    }
723}
724
725///
726/// 获取本地线程绑定的异步运行时
727/// 注意:O如果与本地线程绑定的运行时的O不相同,则无法获取本地线程绑定的运行时
728///
729pub fn local_async_runtime<O: Default + 'static>() -> Option<Arc<LocalAsyncRuntime<O>>> {
730    match PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME.try_with(move |ptr| {
731        let raw = ptr.load(Ordering::Relaxed) as *const LocalAsyncRuntime<O>;
732        unsafe {
733            if raw.is_null() {
734                //本地线程未绑定异步运行时
735                None
736            } else {
737                //本地线程已绑定异步运行时
738                let shared: Arc<LocalAsyncRuntime<O>> = unsafe { Arc::from_raw(raw) };
739                let result = shared.clone();
740                Arc::into_raw(shared); //避免提前释放
741                Some(result)
742            }
743        }
744    }) {
745        Err(_) => None, //本地线程没有绑定异步运行时
746        Ok(rt) => rt,
747    }
748}
749
750/// 同步非阻塞的异步值,只允许被同步非阻塞设置一次值。
751///
752/// 说明:
753/// - `AsyncValue` 是一个 single-shot future,`set()` 成功一次后,等待方可通过
754///   `Future::poll` 取出该值。
755/// - 本类型允许 pending 后重复 poll;重复 poll 会更新最新 waker,并继续返回
756///   `Poll::Pending`。
757/// - `set()` 保持旧语义:首次设置成功,后续设置静默失败且不会覆盖已设置的值。
758/// - 当前 API 不表达 sender/receiver 拆分、关闭或取消语义;never set 的 future 会继续
759///   pending。
760/// - poll after ready 属于调用方违反 Future 契约,可能 panic。
761///
762/// 性能:
763/// - `poll` 和 `set` 均为 O(1),只在 CAS 竞争或极短取值窗口内有限重试。
764/// - 不执行阻塞等待,不持有互斥锁,不在热路径分配队列节点。
765///
766/// 安全性:
767/// - 内部 value 使用 `UnsafeCell<Option<V>>` 保存;只有成功进入 `SETTING` 的 setter
768///   可以写入,只有成功进入 `TAKING` 的 receiver 可以取出。
769/// - 状态转换使用原子 Acquire/Release/AcqRel 保证可见性。
770pub struct AsyncValue<V: 'static>(Arc<InnerAsyncValue<V>>);
771
772unsafe impl<V: 'static> Send for AsyncValue<V> {}
773unsafe impl<V: 'static> Sync for AsyncValue<V> {}
774
775impl<V: 'static> Clone for AsyncValue<V> {
776    fn clone(&self) -> Self {
777        AsyncValue(self.0.clone())
778    }
779}
780
781impl<V: Send + 'static> Debug for AsyncValue<V> {
782    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
783        write!(f,
784               "AsyncValue[status = {}]",
785               self.0.status.load(Ordering::Acquire))
786    }
787}
788
789impl<V: 'static> Future for AsyncValue<V> {
790    type Output = V;
791
792    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
793        let mut spin_len = 1;
794        loop {
795            match self.0.status.load(Ordering::Acquire) {
796                ASYNC_VALUE_EMPTY => {
797                    self.0.waker.register(cx.waker());
798                    match self.0.status.compare_exchange(ASYNC_VALUE_EMPTY,
799                                                         ASYNC_VALUE_WAITING,
800                                                         Ordering::AcqRel,
801                                                         Ordering::Acquire) {
802                        Ok(_) => {
803                            return Poll::Pending;
804                        },
805                        Err(ASYNC_VALUE_EMPTY) => {
806                            continue;
807                        },
808                        Err(ASYNC_VALUE_WAITING) | Err(ASYNC_VALUE_SETTING) => {
809                            return Poll::Pending;
810                        },
811                        Err(ASYNC_VALUE_READY) => {
812                            continue;
813                        },
814                        Err(ASYNC_VALUE_TAKING) => {
815                            spin_len = spin(spin_len);
816                            continue;
817                        },
818                        Err(ASYNC_VALUE_CONSUMED) => {
819                            panic!("AsyncValue polled after completion");
820                        },
821                        Err(_) => {
822                            panic!("AsyncValue entered invalid state");
823                        },
824                    }
825                },
826                ASYNC_VALUE_WAITING | ASYNC_VALUE_SETTING => {
827                    self.0.waker.register(cx.waker());
828                    match self.0.status.load(Ordering::Acquire) {
829                        ASYNC_VALUE_READY => {
830                            continue;
831                        },
832                        ASYNC_VALUE_TAKING => {
833                            spin_len = spin(spin_len);
834                            continue;
835                        },
836                        ASYNC_VALUE_CONSUMED => {
837                            panic!("AsyncValue polled after completion");
838                        },
839                        _ => {
840                            return Poll::Pending;
841                        },
842                    }
843                },
844                ASYNC_VALUE_READY => {
845                    match self.0.status.compare_exchange(ASYNC_VALUE_READY,
846                                                         ASYNC_VALUE_TAKING,
847                                                         Ordering::AcqRel,
848                                                         Ordering::Acquire) {
849                        Ok(_) => {
850                            let value = unsafe { (*self.0.value.get()).take().unwrap() };
851                            self.0.status.store(ASYNC_VALUE_CONSUMED, Ordering::Release);
852                            return Poll::Ready(value);
853                        },
854                        Err(ASYNC_VALUE_TAKING) => {
855                            spin_len = spin(spin_len);
856                            continue;
857                        },
858                        Err(ASYNC_VALUE_CONSUMED) => {
859                            panic!("AsyncValue polled after completion");
860                        },
861                        Err(_) => {
862                            continue;
863                        },
864                    }
865                },
866                ASYNC_VALUE_TAKING => {
867                    //其它 clone 已经获得取值权,等待其完成状态推进,避免同时访问 value。
868                    spin_len = spin(spin_len);
869                    continue;
870                },
871                ASYNC_VALUE_CONSUMED => {
872                    panic!("AsyncValue polled after completion");
873                },
874                _ => {
875                    panic!("AsyncValue entered invalid state");
876                },
877            }
878        }
879    }
880}
881
882/*
883* 同步非阻塞的异步值同步方法
884*/
885impl<V: 'static> AsyncValue<V> {
886    /// 构建异步值,默认值为未就绪
887    pub fn new() -> Self {
888        let inner = InnerAsyncValue {
889            value: UnsafeCell::new(None),
890            waker: AtomicWaker::new(),
891            status: AtomicU8::new(ASYNC_VALUE_EMPTY),
892        };
893
894        AsyncValue(Arc::new(inner))
895    }
896
897    /// 判断异步值是否已完成设置
898    pub fn is_complete(&self) -> bool {
899        match self.0.status.load(Ordering::Acquire) {
900            ASYNC_VALUE_READY | ASYNC_VALUE_TAKING | ASYNC_VALUE_CONSUMED => true,
901            _ => false,
902        }
903    }
904
905    /// 设置异步值
906    pub fn set(self, value: V) {
907        let mut value = Some(value);
908        loop {
909            match self.0.status.load(Ordering::Acquire) {
910                ASYNC_VALUE_EMPTY => {
911                    match self.0.status.compare_exchange(ASYNC_VALUE_EMPTY,
912                                                         ASYNC_VALUE_SETTING,
913                                                         Ordering::AcqRel,
914                                                         Ordering::Acquire) {
915                        Ok(_) => {
916                            unsafe { *self.0.value.get() = value.take(); }
917                            self.0.status.store(ASYNC_VALUE_READY, Ordering::Release);
918                            self.0.waker.wake();
919                            return;
920                        },
921                        Err(_) => {
922                            continue;
923                        },
924                    }
925                },
926                ASYNC_VALUE_WAITING => {
927                    match self.0.status.compare_exchange(ASYNC_VALUE_WAITING,
928                                                         ASYNC_VALUE_SETTING,
929                                                         Ordering::AcqRel,
930                                                         Ordering::Acquire) {
931                        Ok(_) => {
932                            unsafe { *self.0.value.get() = value.take(); }
933                            self.0.status.store(ASYNC_VALUE_READY, Ordering::Release);
934                            self.0.waker.wake();
935                            return;
936                        },
937                        Err(_) => {
938                            continue;
939                        },
940                    }
941                },
942                _ => {
943                    //异步值正在设置、已设置或已消费,则保持旧语义:重复 set 静默失败。
944                    return;
945                },
946            }
947        }
948    }
949}
950
951// 同步非阻塞的内部异步值,只允许被同步非阻塞的设置一次值
952pub struct InnerAsyncValue<V: 'static> {
953    value:  UnsafeCell<Option<V>>,  // 值,访问权由 status 的 SETTING/TAKING 状态独占保护。
954    waker:  AtomicWaker,            // 最近一次 pending poll 注册的唤醒器。
955    status: AtomicU8,               // 状态机,见 ASYNC_VALUE_* 常量。
956}
957
958///
959/// 异步非阻塞可变值的守护者
960///
961pub struct AsyncVariableGuard<'a, V: 'static> {
962    value:  &'a UnsafeCell<Option<V>>,      //值
963    waker:  &'a UnsafeCell<Option<Waker>>,  //唤醒器
964    status: &'a AtomicU8,                   //值状态
965}
966
967unsafe impl<V: 'static> Send for AsyncVariableGuard<'_, V> {}
968
969impl<V: 'static> Drop for AsyncVariableGuard<'_, V> {
970    fn drop(&mut self) {
971        //当前异步可变值已锁定,则解除锁定
972        //当前异步可变值的状态为2或6,表示当前异步可变值的唤醒器未就绪并已锁定,或当前异步可变值不需要唤醒并已完成所有修改
973        //当前异步可变值的状态为3或7,表示当前异步可变值的唤醒器已就绪并已锁定,或当前异步可变值已唤醒并已完成所有修改
974        self.status.fetch_sub(2, Ordering::Relaxed);
975    }
976}
977
978impl<V: 'static> Deref for AsyncVariableGuard<'_, V> {
979    type Target = Option<V>;
980
981    fn deref(&self) -> &Self::Target {
982        unsafe {
983            &*self.value.get()
984        }
985    }
986}
987
988impl<V: 'static> DerefMut for AsyncVariableGuard<'_, V> {
989    fn deref_mut(&mut self) -> &mut Self::Target {
990        unsafe {
991            &mut *self.value.get()
992        }
993    }
994}
995
996impl<V: 'static> AsyncVariableGuard<'_, V> {
997    /// 完成异步可变值的修改
998    pub fn finish(self) {
999        //设置异步可变值的状态为已完成修改
1000        if self.status.fetch_add(4, Ordering::Relaxed) == 3 {
1001            if let Some(waker) = unsafe { (&mut *self.waker.get()).take() } {
1002                //当前异步可变值需要唤醒,则立即唤醒异步可变值
1003                waker.wake();
1004            }
1005        }
1006    }
1007}
1008
1009///
1010/// 异步非阻塞可变值,在完成前允许被同步非阻塞的修改多次
1011///
1012pub struct AsyncVariable<V: 'static>(Arc<InnerAsyncVariable<V>>);
1013
1014unsafe impl<V: 'static> Send for AsyncVariable<V> {}
1015unsafe impl<V: 'static> Sync for AsyncVariable<V> {}
1016
1017impl<V: 'static> Clone for AsyncVariable<V> {
1018    fn clone(&self) -> Self {
1019        AsyncVariable(self.0.clone())
1020    }
1021}
1022
1023impl<V: 'static> Future for AsyncVariable<V> {
1024    type Output = V;
1025
1026    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1027        unsafe {
1028            *self.0.waker.get() = Some(cx.waker().clone()); //设置异步可变值的唤醒器准备就绪
1029        }
1030
1031        let mut spin_len = 1;
1032        loop {
1033            match self.0.status.compare_exchange(0,
1034                                                 1,
1035                                                 Ordering::Acquire,
1036                                                 Ordering::Relaxed) {
1037                Err(current) if current & 4 != 0 => {
1038                    //异步可变值已完成所有修改,则立即返回
1039                    unsafe {
1040                        let _ = (&mut *self.0.waker.get()).take(); //释放异步可变值的唤醒器
1041                        return Poll::Ready((&mut *(&self).0.value.get()).take().unwrap());
1042                    }
1043                },
1044                Err(_) => {
1045                    //还未完成值修改,则自旋等待
1046                    spin_len = spin(spin_len);
1047                },
1048                Ok(_) => {
1049                    //异步可变值已挂起
1050                    return Poll::Pending;
1051                },
1052            }
1053        }
1054    }
1055}
1056
1057impl<V: 'static> AsyncVariable<V> {
1058    /// 构建异步可变值,默认值为未就绪
1059    pub fn new() -> Self {
1060        let inner = InnerAsyncVariable {
1061            value: UnsafeCell::new(None),
1062            waker: UnsafeCell::new(None),
1063            status: AtomicU8::new(0),
1064        };
1065
1066        AsyncVariable(Arc::new(inner))
1067    }
1068
1069    /// 判断异步可变值是否已完成设置
1070    pub fn is_complete(&self) -> bool {
1071        self
1072            .0
1073            .status
1074            .load(Ordering::Acquire) & 4 != 0
1075    }
1076
1077    /// 锁住待修改的异步可变值,并返回当前异步可变值的守护者,如果异步可变值已完成修改则返回空
1078    pub fn lock(&self) -> Option<AsyncVariableGuard<V>> {
1079        let mut spin_len = 1;
1080        loop {
1081            match self
1082                .0
1083                .status
1084                .compare_exchange(1,
1085                                  3,
1086                                  Ordering::Acquire,
1087                                  Ordering::Relaxed) {
1088                Err(0) => {
1089                    //异步可变值还未就绪,则自旋等待
1090                    match self
1091                        .0
1092                        .status
1093                        .compare_exchange(0,
1094                                          2,
1095                                          Ordering::Acquire,
1096                                          Ordering::Relaxed) {
1097                        Err(1) => {
1098                            //异步可变值已就绪,则继续尝试获取锁
1099                            continue;
1100                        },
1101                        Err(2) => {
1102                            //异步可变值的唤醒器未就绪且已锁,但未获取到锁,则自旋等待
1103                            spin_len = spin(spin_len);
1104                        },
1105                        Err(3) => {
1106                            //异步可变值的唤醒器已就绪且已锁,但未获取到锁,则自旋等待
1107                            spin_len = spin(spin_len);
1108                        },
1109                        Err(_) => {
1110                            //已完成,则返回空
1111                            return None;
1112                        },
1113                        Ok(_) => {
1114                            //异步可变值的唤醒器未就绪且获取到锁,则返回异步可变值的守护者
1115                            let guard = AsyncVariableGuard {
1116                                value: &self.0.value,
1117                                waker: &self.0.waker,
1118                                status: &self.0.status,
1119                            };
1120
1121                            return Some(guard)
1122                        },
1123                    }
1124                },
1125                Err(2) => {
1126                    //异步可变值的唤醒器未就绪且已锁,但未获取到锁,则自旋等待
1127                    spin_len = spin(spin_len);
1128                },
1129                Err(3) => {
1130                    //异步可变值的唤醒器已就绪且已锁,但未获取到锁,则自旋等待
1131                    spin_len = spin(spin_len);
1132                },
1133                Err(_) => {
1134                    //已完成,则返回空
1135                    return None;
1136                }
1137                Ok(_) => {
1138                    //异步可变值的唤醒器已就绪且获取到锁,则返回异步可变值的守护者
1139                    let guard = AsyncVariableGuard {
1140                        value: &self.0.value,
1141                        waker: &self.0.waker,
1142                        status: &self.0.status,
1143                    };
1144
1145                    return Some(guard)
1146                },
1147            }
1148        }
1149    }
1150}
1151
1152// 内部异步非阻塞可变值,在完成前允许被同步非阻塞的修改多次
1153pub struct InnerAsyncVariable<V: 'static> {
1154    value:  UnsafeCell<Option<V>>,      //值
1155    waker:  UnsafeCell<Option<Waker>>,  //唤醒器
1156    status: AtomicU8,                   //状态
1157}
1158
1159///
1160/// 等待异步任务运行的结果
1161///
1162pub struct AsyncWaitResult<V: 'static>(pub Arc<RefCell<Option<Result<V>>>>);
1163
1164unsafe impl<V: 'static> Send for AsyncWaitResult<V> {}
1165unsafe impl<V: 'static> Sync for AsyncWaitResult<V> {}
1166
1167impl<V: 'static> Clone for AsyncWaitResult<V> {
1168    fn clone(&self) -> Self {
1169        AsyncWaitResult(self.0.clone())
1170    }
1171}
1172
1173///
1174/// 等待异步任务运行的结果集
1175///
1176pub struct AsyncWaitResults<V: 'static>(pub Arc<RefCell<Option<Vec<Result<V>>>>>);
1177
1178unsafe impl<V: 'static> Send for AsyncWaitResults<V> {}
1179unsafe impl<V: 'static> Sync for AsyncWaitResults<V> {}
1180
1181impl<V: 'static> Clone for AsyncWaitResults<V> {
1182    fn clone(&self) -> Self {
1183        AsyncWaitResults(self.0.clone())
1184    }
1185}
1186
1187///
1188/// 异步定时器任务
1189///
1190pub enum AsyncTimingTask<
1191    P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1192    O: Default + 'static = (),
1193> {
1194    Pended(TaskId),                     //已挂起的定时任务
1195    WaitRun(Arc<AsyncTask<P, O>>),      //等待执行的定时任务
1196    TimeoutWake(Arc<TimeoutWaiter>),    //等待timeout到期的唤醒句柄
1197}
1198
1199///
1200/// 异步任务本地定时器
1201///
1202pub struct AsyncTaskTimer<
1203    P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1204    O: Default + 'static = (),
1205> {
1206    producor:   Sender<(usize, AsyncTimingTask<P, O>)>,                     //定时任务生产者
1207    consumer:   Receiver<(usize, AsyncTimingTask<P, O>)>,                   //定时任务消费者
1208    timer:      Arc<RefCell<Timer<AsyncTimingTask<P, O>, 1000, 60, 3>>>,    //定时器
1209    clock:      Clock,                                                      //定时器时钟
1210    now:        QInstant,                                                   //当前时间
1211}
1212
1213unsafe impl<
1214    P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1215    O: Default + 'static,
1216> Send for AsyncTaskTimer<P, O> {}
1217unsafe impl<
1218    P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1219    O: Default + 'static,
1220> Sync for AsyncTaskTimer<P, O> {}
1221
1222impl<
1223    P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1224    O: Default + 'static,
1225> AsyncTaskTimer<P, O> {
1226    /// 构建异步任务本地定时器
1227    pub fn new() -> Self {
1228        let (producor, consumer) = unbounded();
1229        let clock = Clock::new();
1230        let now = clock.recent();
1231
1232        AsyncTaskTimer {
1233            producor,
1234            consumer,
1235            timer: Arc::new(RefCell::new(Timer::<AsyncTimingTask<P, O>, 1000, 60, 3>::default())),
1236            clock,
1237            now,
1238        }
1239    }
1240
1241    /// 获取定时任务生产者
1242    #[inline]
1243    pub fn get_producor(&self) -> &Sender<(usize, AsyncTimingTask<P, O>)> {
1244        &self.producor
1245    }
1246
1247    /// 获取剩余未到期的定时器任务数量
1248    #[inline]
1249    pub fn len(&self) -> usize {
1250        let timer = self.timer.as_ref().borrow();
1251        timer.add_count() - timer.remove_count()
1252    }
1253
1254    /// 设置定时器
1255    pub fn set_timer(&self, task: AsyncTimingTask<P, O>, timeout: usize) -> usize {
1256        let current_time = self
1257            .clock
1258            .recent()
1259            .duration_since(self.now)
1260            .as_millis() as u64;
1261        self
1262            .timer
1263            .borrow_mut()
1264            .push_time(current_time + timeout as u64, task)
1265            .data()
1266            .as_ffi() as usize
1267    }
1268
1269    /// 取消定时器
1270    pub fn cancel_timer(&self, timer_ref: usize) -> Option<AsyncTimingTask<P, O>> {
1271        if let Some(item) =self
1272            .timer
1273            .borrow_mut()
1274            .cancel(KeyData::from_ffi(timer_ref as u64).into()) {
1275            Some(item)
1276        } else {
1277            None
1278        }
1279    }
1280
1281    /// 消费所有定时任务,返回定时任务数量
1282    pub fn consume(&self) -> usize {
1283        let mut len = 0;
1284        let timer_tasks = self.consumer.try_iter().collect::<Vec<(usize, AsyncTimingTask<P, O>)>>();
1285        for (timeout, task) in timer_tasks {
1286            self.set_timer(task, timeout);
1287            len += 1;
1288        }
1289
1290        len
1291    }
1292
1293    /// 判断当前时间是否有可以弹出的任务,如果有可以弹出的任务,则返回当前时间,否则返回空
1294    pub fn is_require_pop(&self) -> Option<u64> {
1295        let current_time = self
1296            .clock
1297            .recent()
1298            .duration_since(self.now)
1299            .as_millis() as u64;
1300        if self.timer.borrow_mut().is_ok(current_time) {
1301            Some(current_time)
1302        } else {
1303            None
1304        }
1305    }
1306
1307    /// 从定时器中弹出指定时间的一个到期任务
1308    pub fn pop(&self, current_time: u64) -> Option<(usize, AsyncTimingTask<P, O>)> {
1309        if let Some((key, item)) = self.timer.borrow_mut().pop_kv(current_time) {
1310            Some((key.data().as_ffi() as usize, item))
1311        } else {
1312            None
1313        }
1314    }
1315}
1316
1317///
1318/// 等待指定超时
1319///
1320pub struct AsyncWaitTimeout<
1321    RT: AsyncRuntime<O>,
1322    P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1323    O: Default + 'static = (),
1324> {
1325    rt:         RT,                                     //当前运行时
1326    producor:   Sender<(usize, AsyncTimingTask<P, O>)>, //超时请求生产者
1327    timeout:    usize,                                  //超时时长,单位ms
1328    registered: AtomicBool,                             //是否已注册到定时器
1329    waiter:     Arc<TimeoutWaiter>,                     //timeout专用等待句柄
1330}
1331
1332unsafe impl<
1333    RT: AsyncRuntime<O>,
1334    P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1335    O: Default + 'static,
1336> Send for AsyncWaitTimeout<RT, P, O> {}
1337unsafe impl<
1338    RT: AsyncRuntime<O>,
1339    P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1340    O: Default + 'static,
1341> Sync for AsyncWaitTimeout<RT, P, O> {}
1342
1343impl<
1344    RT: AsyncRuntime<O>,
1345    P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1346    O: Default + 'static,
1347> Future for AsyncWaitTimeout<RT, P, O> {
1348    type Output = ();
1349
1350    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1351        if self.waiter.is_fired() {
1352            //已到期,则返回
1353            return Poll::Ready(());
1354        }
1355
1356        self.waiter.register(cx.waker());
1357
1358        if !self.registered.swap(true, Ordering::AcqRel) {
1359            //发送超时请求,并返回
1360            let _ = self
1361                .producor
1362                .send((self.timeout, AsyncTimingTask::TimeoutWake(self.waiter.clone())));
1363        }
1364
1365        if self.waiter.is_fired() {
1366            Poll::Ready(())
1367        } else {
1368            Poll::Pending
1369        }
1370    }
1371}
1372
1373impl<
1374    RT: AsyncRuntime<O>,
1375    P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1376    O: Default + 'static,
1377> Drop for AsyncWaitTimeout<RT, P, O> {
1378    fn drop(&mut self) {
1379        self.waiter.clear_waker();
1380    }
1381}
1382
1383impl<
1384    RT: AsyncRuntime<O>,
1385    P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1386    O: Default + 'static,
1387> AsyncWaitTimeout<RT, P, O> {
1388    /// 构建等待指定超时任务的方法
1389    pub fn new(rt: RT,
1390               producor: Sender<(usize, AsyncTimingTask<P, O>)>,
1391               timeout: usize) -> Self {
1392        AsyncWaitTimeout {
1393            rt,
1394            producor,
1395            timeout,
1396            registered: AtomicBool::new(false), //设置初始值
1397            waiter: Arc::new(TimeoutWaiter::new()),
1398        }
1399    }
1400}
1401
1402///
1403/// 等待异步任务执行完成
1404///
1405pub struct AsyncWait<V: 'static>(AsyncWaitAny<V>);
1406
1407unsafe impl<V: 'static> Send for AsyncWait<V> {}
1408unsafe impl<V: 'static> Sync for AsyncWait<V> {}
1409
1410/*
1411* 等待异步任务执行完成同步方法
1412*/
1413impl<V: 'static> AsyncWait<V> {
1414    /// 构建等待异步任务执行完成
1415    pub(crate) fn new(inner: AsyncWaitAny<V>) -> Self {
1416        AsyncWait(inner)
1417    }
1418
1419    /// 派发指定超时时间的指定任务到指定的运行时,并返回派发是否成功
1420    pub fn spawn<RT, O, F>(&self,
1421                           rt: RT,
1422                           timeout: Option<usize>,
1423                           future: F) -> Result<()>
1424        where RT: AsyncRuntime<O>,
1425              O: Default + 'static,
1426              F: Future<Output = Result<V>> + 'static {
1427        self.0.spawn(rt.clone(), future)?;
1428
1429        if let Some(timeout) = timeout {
1430            //设置了超时时间
1431            let rt_copy = rt.clone();
1432            self.0.spawn(rt, async move {
1433                rt_copy.timeout(timeout).await;
1434
1435                //返回超时错误
1436                Err(Error::new(ErrorKind::TimedOut, format!("Time out")))
1437            })
1438        } else {
1439            //未设置超时时间
1440            Ok(())
1441        }
1442    }
1443
1444    /// 派发指定超时时间的指定任务到本地运行时,并返回派发是否成功
1445    pub fn spawn_local<O, F>(&self,
1446                             timeout: Option<usize>,
1447                             future: F) -> Result<()>
1448        where O: Default + 'static,
1449              F: Future<Output = Result<V>> + 'static {
1450        if let Some(rt) = local_serial_async_runtime::<O>() {
1451            //当前线程有绑定运行时
1452            self.0.spawn_local(future)?;
1453
1454            if let Some(timeout) = timeout {
1455                //设置了超时时间
1456                let rt_copy = rt.clone();
1457                self.0.spawn_local(async move {
1458                    rt_copy.timeout(timeout).await;
1459
1460                    //返回超时错误
1461                    Err(Error::new(ErrorKind::TimedOut, format!("Time out")))
1462                })
1463            } else {
1464                //未设置超时时间
1465                Ok(())
1466            }
1467        } else {
1468            //当前线程未绑定运行时
1469            Err(Error::new(ErrorKind::Other, format!("Spawn wait task failed, reason: local async runtime not exist")))
1470        }
1471    }
1472}
1473
1474/*
1475* 等待异步任务执行完成异步方法
1476*/
1477impl<V: 'static> AsyncWait<V> {
1478    /// 异步等待已派发任务的结果
1479    pub async fn wait_result(self) -> Result<V> {
1480        self.0.wait_result().await
1481    }
1482}
1483
1484///
1485/// 等待任意异步任务执行完成
1486///
1487pub struct AsyncWaitAny<V: 'static> {
1488    capacity:       usize,                      //派发任务的容量
1489    producor:       AsyncSender<Result<V>>,     //异步返回值生成器
1490    consumer:       AsyncReceiver<Result<V>>,   //异步返回值接收器
1491}
1492
1493unsafe impl<V: 'static> Send for AsyncWaitAny<V> {}
1494unsafe impl<V: 'static> Sync for AsyncWaitAny<V> {}
1495
1496/*
1497* 等待任意异步任务执行完成同步方法
1498*/
1499impl<V: 'static> AsyncWaitAny<V> {
1500    /// 构建等待任意异步任务执行完成
1501    pub(crate) fn new(capacity: usize,
1502                      producor: AsyncSender<Result<V>>,
1503                      consumer: AsyncReceiver<Result<V>>) -> Self {
1504        AsyncWaitAny {
1505            capacity,
1506            producor,
1507            consumer,
1508        }
1509    }
1510
1511    /// 派发指定任务到指定的运行时,并返回派发是否成功
1512    pub fn spawn<RT, O, F>(&self,
1513                           rt: RT,
1514                           future: F) -> Result<()>
1515        where RT: AsyncRuntime<O>,
1516              O: Default + 'static,
1517              F: Future<Output = Result<V>> + 'static {
1518        let producor = self.producor.clone();
1519        rt.spawn_by_id(rt.alloc::<O>(), async move {
1520                    let value = future.await;
1521                    producor.into_send_async(value).await;
1522
1523                    //返回异步任务的默认值
1524                    Default::default()
1525                })
1526    }
1527
1528    /// 派发指定任务到本地运行时,并返回派发是否成功
1529    pub fn spawn_local<F>(&self,
1530                          future: F) -> Result<()>
1531        where F: Future<Output = Result<V>> + 'static {
1532        if let Some(rt) = local_serial_async_runtime() {
1533            //本地线程有绑定运行时
1534            let producor = self.producor.clone();
1535            rt.spawn(async move {
1536                let value = future.await;
1537                producor.into_send_async(value).await;
1538            })
1539        } else {
1540            //本地线程未绑定运行时
1541            Err(Error::new(ErrorKind::Other, format!("Spawn wait any task failed, reason: local async runtime not exist")))
1542        }
1543    }
1544}
1545
1546/*
1547* 等待任意异步任务执行完成异步方法
1548*/
1549impl<V: 'static> AsyncWaitAny<V> {
1550    /// 异步等待任意已派发任务的结果
1551    pub async fn wait_result(self) -> Result<V> {
1552        match self.consumer.recv_async().await {
1553            Err(e) => {
1554                //接收错误,则立即返回
1555                Err(Error::new(ErrorKind::Other, format!("Wait any result failed, reason: {:?}", e)))
1556            },
1557            Ok(result) => {
1558                //接收成功,则立即返回
1559                result
1560            },
1561        }
1562    }
1563}
1564
1565///
1566/// 等待任意异步任务执行完成
1567///
1568pub struct AsyncWaitAnyCallback<V: 'static> {
1569    capacity:   usize,                      //派发任务的容量
1570    producor:   AsyncSender<Result<V>>,     //异步返回值生成器
1571    consumer:   AsyncReceiver<Result<V>>,   //异步返回值接收器
1572}
1573
1574unsafe impl<V: 'static> Send for AsyncWaitAnyCallback<V> {}
1575unsafe impl<V: 'static> Sync for AsyncWaitAnyCallback<V> {}
1576
1577/*
1578* 等待任意异步任务执行完成同步方法
1579*/
1580impl<V: 'static> AsyncWaitAnyCallback<V> {
1581    /// 构建等待任意异步任务执行完成
1582    pub(crate) fn new(capacity: usize,
1583                      producor: AsyncSender<Result<V>>,
1584                      consumer: AsyncReceiver<Result<V>>) -> Self {
1585        AsyncWaitAnyCallback {
1586            capacity,
1587            producor,
1588            consumer,
1589        }
1590    }
1591
1592    /// 派发指定任务到指定的运行时,并返回派发是否成功
1593    pub fn spawn<RT, O, F>(&self,
1594                           rt: RT,
1595                           future: F) -> Result<()>
1596        where RT: AsyncRuntime<O>,
1597              O: Default + 'static,
1598              F: Future<Output = Result<V>> + 'static {
1599        let producor = self.producor.clone();
1600        rt.spawn_by_id(rt.alloc::<O>(), async move {
1601                    let value = future.await;
1602                    producor.into_send_async(value).await;
1603
1604                    //返回异步任务的默认值
1605                    Default::default()
1606                })
1607    }
1608
1609    /// 派发指定任务到本地运行时,并返回派发是否成功
1610    pub fn spawn_local<F>(&self,
1611                          future: F) -> Result<()>
1612        where F: Future<Output = Result<V>> + 'static {
1613        if let Some(rt) = local_serial_async_runtime() {
1614            //当前线程有绑定运行时
1615            let producor = self.producor.clone();
1616            rt.spawn(async move {
1617                let value = future.await;
1618                producor.into_send_async(value).await;
1619            })
1620        } else {
1621            //当前线程未绑定运行时
1622            Err(Error::new(ErrorKind::Other, format!("Spawn wait any task failed by callback, reason: current async runtime not exist")))
1623        }
1624    }
1625}
1626
1627/*
1628* 等待任意异步任务执行完成异步方法
1629*/
1630impl<V: 'static> AsyncWaitAnyCallback<V> {
1631    /// 异步等待满足用户回调需求的已派发任务的结果
1632    pub async fn wait_result(mut self,
1633                             callback: impl Fn(&Result<V>) -> bool + 'static) -> Result<V> {
1634        let checker = create_checker(self.capacity, callback);
1635        loop {
1636            match self.consumer.recv_async().await {
1637                Err(e) => {
1638                    //接收错误,则立即返回
1639                    return Err(Error::new(ErrorKind::Other, format!("Wait any result failed by callback, reason: {:?}", e)));
1640                },
1641                Ok(result) => {
1642                    //接收成功,则检查是否立即返回
1643                    if checker(&result) {
1644                        //检查通过,则立即唤醒等待的任务,否则等待其它任务唤醒
1645                        return result;
1646                    }
1647                },
1648            }
1649        }
1650    }
1651}
1652
1653// 根据用户提供的回调,生成检查器
1654fn create_checker<V, F>(len: usize,
1655                        callback: F) -> Arc<dyn Fn(&Result<V>) -> bool + 'static>
1656    where V: 'static,
1657          F: Fn(&Result<V>) -> bool + 'static {
1658    let mut check_counter = AtomicUsize::new(len); //初始化检查计数器
1659    Arc::new(move |result| {
1660        if check_counter.fetch_sub(1, Ordering::SeqCst) == 1 {
1661            //最后一个任务的检查,则忽略用户回调,并立即返回成功
1662            true
1663        } else {
1664            //不是最后一个任务的检查,则调用用户回调,并根据用户回调确定是否成功
1665            callback(result)
1666        }
1667    })
1668}
1669
1670///
1671/// 异步映射归并
1672///
1673pub struct AsyncMapReduce<V: 'static> {
1674    count:          usize,                              //派发的任务数量
1675    capacity:       usize,                              //派发任务的容量
1676    producor:       AsyncSender<(usize, Result<V>)>,    //异步返回值生成器
1677    consumer:       AsyncReceiver<(usize, Result<V>)>,  //异步返回值接收器
1678}
1679
1680unsafe impl<V: 'static> Send for AsyncMapReduce<V> {}
1681
1682/*
1683* 异步映射归并同步方法
1684*/
1685impl<V: 'static> AsyncMapReduce<V> {
1686    /// 构建异步映射归并
1687    pub(crate) fn new(count: usize,
1688                      capacity: usize,
1689                      producor: AsyncSender<(usize, Result<V>)>,
1690                      consumer: AsyncReceiver<(usize, Result<V>)>) -> Self {
1691        AsyncMapReduce {
1692            count,
1693            capacity,
1694            producor,
1695            consumer,
1696        }
1697    }
1698
1699    /// 映射指定任务到指定的运行时,并返回任务序号
1700    pub fn map<RT, O, F>(&mut self, rt: RT, future: F) -> Result<usize>
1701        where RT: AsyncRuntime<O>,
1702              O: Default + 'static,
1703              F: Future<Output = Result<V>> + 'static {
1704        if self.count >= self.capacity {
1705            //已派发任务已达可派发任务的限制,则返回错误
1706            return Err(Error::new(ErrorKind::Other, format!("Map task to runtime failed, capacity: {}, reason: out of capacity", self.capacity)));
1707        }
1708
1709        let index = self.count;
1710        let producor = self.producor.clone();
1711        rt.spawn(async move {
1712                    let value = future.await;
1713                    producor.into_send_async((index, value)).await;
1714
1715                    //返回异步任务的默认值
1716                    Default::default()
1717                })?;
1718
1719        self.count += 1; //派发任务成功,则计数
1720        Ok(index)
1721    }
1722}
1723
1724/*
1725* 异步映射归并异步方法
1726*/
1727impl<V: 'static> AsyncMapReduce<V> {
1728    /// 归并所有派发的任务
1729    pub async fn reduce(self, order: bool) -> Result<Vec<Result<V>>> {
1730        let mut count = self.count;
1731        let mut results = Vec::with_capacity(count);
1732        while count > 0 {
1733            match self.consumer.recv_async().await {
1734                Err(e) => {
1735                    //接收错误,则立即返回
1736                    return Err(Error::new(ErrorKind::Other, format!("Reduce result failed, reason: {:?}", e)));
1737                },
1738                Ok((index, result)) => {
1739                    //接收成功,则继续
1740                    results.push((index, result));
1741                    count -= 1;
1742                },
1743            }
1744        }
1745
1746        if order {
1747            //需要对结果集进行排序
1748            results.sort_by_key(|(key, _value)| {
1749                key.clone()
1750            });
1751        }
1752        let (_, values) = results
1753            .into_iter()
1754            .unzip::<usize, Result<V>, Vec<usize>, Vec<Result<V>>>();
1755
1756        Ok(values)
1757    }
1758}
1759
1760///
1761/// 派发一个工作线程
1762/// 返回线程的句柄,可以通过句柄关闭线程
1763/// 线程在没有任务可以执行时会休眠,当派发任务或唤醒任务时会自动唤醒线程
1764///
1765pub fn spawn_worker_thread<F0, F1>(thread_name: &str,
1766                                   thread_stack_size: usize,
1767                                   thread_handler: Arc<AtomicBool>,
1768                                   thread_waker: Arc<(AtomicBool, Mutex<()>, Condvar)>, //用于唤醒运行时所在线程的条件变量
1769                                   sleep_timeout: u64,                                  //休眠超时时长,单位毫秒
1770                                   loop_interval: Option<u64>,                          //工作者线程循环的间隔时长,None为无间隔,单位毫秒
1771                                   loop_func: F0,
1772                                   get_queue_len: F1) -> Arc<AtomicBool>
1773    where F0: Fn() -> (bool, Duration) + Send + 'static,
1774          F1: Fn() -> usize + Send + 'static {
1775    let thread_status_copy = thread_handler.clone();
1776
1777    thread::Builder::new()
1778        .name(thread_name.to_string())
1779        .stack_size(thread_stack_size)
1780        .spawn(move || {
1781            let mut sleep_count = 0;
1782
1783            while thread_handler.load(Ordering::Relaxed) {
1784                let (is_no_task, run_time) = loop_func();
1785
1786                if is_no_task {
1787                    //当前没有任务
1788                    if sleep_count > 1 {
1789                        //当前没有任务连续达到2次,则休眠线程
1790                        sleep_count = 0; //重置休眠计数
1791                        let (is_sleep, lock, condvar) = &*thread_waker;
1792                        if get_queue_len() > 0 {
1793                            //当前有任务,则继续工作
1794                            continue;
1795                        }
1796
1797                        {
1798                            let _locked = lock.lock();
1799                            if !is_sleep.load(Ordering::Acquire) {
1800                                //发布休眠状态,外部唤醒端会在同一把锁内确认后再notify
1801                                is_sleep.store(true, Ordering::Release);
1802                            }
1803                        }
1804
1805                        if get_queue_len() > 0 {
1806                            //发布休眠后再次检查任务,避免外部唤醒落在发布窗口内
1807                            is_sleep.store(false, Ordering::Release);
1808                            continue;
1809                        }
1810
1811                        let mut locked = lock.lock();
1812                        if is_sleep.load(Ordering::Acquire) {
1813                            let _ = condvar.wait_for(
1814                                &mut locked,
1815                                Duration::from_millis(sleep_timeout),
1816                            );
1817                        }
1818                        is_sleep.store(false, Ordering::Release);
1819
1820                        continue; //唤醒后立即尝试执行任务
1821                    }
1822
1823                    sleep_count += 1; //休眠计数
1824                    if let Some(interval) = &loop_interval {
1825                        //设置了循环间隔时长
1826                        if let Some(remaining_interval) = Duration::from_millis(*interval).checked_sub(run_time){
1827                            //本次运行少于循环间隔,则休眠剩余的循环间隔,并继续执行任务
1828                            thread::sleep(remaining_interval);
1829                        }
1830                    }
1831                } else {
1832                    //当前有任务
1833                    sleep_count = 0; //重置休眠计数
1834                    if let Some(interval) = &loop_interval {
1835                        //设置了循环间隔时长
1836                        if let Some(remaining_interval) = Duration::from_millis(*interval).checked_sub(run_time){
1837                            //本次运行少于循环间隔,则休眠剩余的循环间隔,并继续执行任务
1838                            thread::sleep(remaining_interval);
1839                        }
1840                    }
1841                }
1842            }
1843    });
1844
1845    thread_status_copy
1846}
1847
1848/// 唤醒工作者所在线程,如果线程当前正在运行,则忽略
1849pub fn wakeup_worker_thread<O, P>(worker_waker: &Arc<(AtomicBool, Mutex<()>, Condvar)>,
1850                                  rt: &SingleTaskRuntime<O, P>)
1851    where O: Default + 'static,
1852          P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P> {
1853    //检查工作者所在线程是否需要唤醒
1854    if worker_waker.0.load(Ordering::Relaxed) && rt.len() > 0 {
1855        let _ = wake_thread_waker(worker_waker);
1856    }
1857}