1use std::thread;
5use std::pin::Pin;
6use std::sync::Arc;
7use std::ptr::null_mut;
8use std::vec::IntoIter;
9use std::future::Future;
10use std::panic::set_hook;
11use std::any::{Any, TypeId};
12use std::marker::PhantomData;
13use std::ops::{Deref, DerefMut};
14use std::cell::{RefCell, UnsafeCell};
15use std::task::{Waker, Context, Poll};
16use std::time::{Duration, SystemTime};
17use std::io::{Error, Result, ErrorKind};
18use std::alloc::{Layout, set_alloc_error_hook};
19use std::fmt::{Debug, Formatter, Result as FmtResult};
20use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, AtomicPtr, Ordering};
21
22pub mod single_thread;
23pub mod multi_thread;
24pub mod worker_thread;
25pub mod serial;
26pub mod serial_local_thread;
27pub mod serial_single_thread;
28pub mod serial_worker_thread;
29pub mod serial_local_compatible_wasm_runtime;
30
31use libc;
32use futures::{future::{FutureExt, BoxFuture},
33 stream::{Stream, BoxStream},
34 task::{ArcWake, AtomicWaker}};
35use parking_lot::{Mutex, Condvar};
36use crossbeam_channel::{Sender, Receiver, unbounded};
37use crossbeam_queue::ArrayQueue;
38use crossbeam_utils::atomic::AtomicCell;
39use flume::{Sender as AsyncSender, Receiver as AsyncReceiver};
40use num_cpus;
41use backtrace::Backtrace;
42use slotmap::{Key, KeyData};
43use quanta::{Clock, Upkeep, Handle, Instant as QInstant};
44
45use pi_hash::XHashMap;
46use pi_cancel_timer::Timer;
47use pi_timer::Timer as NotCancelTimer;
48
49use single_thread::SingleTaskRuntime;
50use worker_thread::{WorkerTaskRunner, WorkerRuntime};
51use multi_thread::{MultiTaskRuntimeBuilder, MultiTaskRuntime, StealableTaskPool};
52
53use crate::lock::spin;
54
55thread_local! {
59 static PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME: AtomicPtr<()> = AtomicPtr::new(null_mut());
60 static PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME_DICT: UnsafeCell<XHashMap<TypeId, Box<dyn Any + 'static>>> = UnsafeCell::new(XHashMap::default());
61}
62
63thread_local! {
67 static PI_ASYNC_THREAD_LOCAL_ID: UnsafeCell<usize> = UnsafeCell::new(usize::MAX);
68}
69
70const DEFAULT_MAX_HIGH_PRIORITY_BOUNDED: usize = 10;
74
75const DEFAULT_HIGH_PRIORITY_BOUNDED: usize = 5;
79
80const DEFAULT_MAX_LOW_PRIORITY_BOUNDED: usize = 0;
84
85static RUNTIME_UID_GEN: AtomicUsize = AtomicUsize::new(1);
89
90static GLOBAL_TIME_LOOP_STATUS: AtomicBool = AtomicBool::new(false);
94
95pub fn startup_global_time_loop(interval: u64) -> Option<GlobalTimeLoopHandle> {
100 if let Err(_) = GLOBAL_TIME_LOOP_STATUS.compare_exchange(false,
101 true,
102 Ordering::AcqRel,
103 Ordering::Relaxed) {
104 None
106 } else {
107 let timer = Upkeep::new_with_clock(Duration::from_millis(interval), Clock::new());
109 let handle = timer.start().unwrap();
110 let clock = Clock::new();
111 let _now = clock.recent();
112
113 Some(GlobalTimeLoopHandle(handle))
114 }
115}
116
117pub struct GlobalTimeLoopHandle(Handle);
121
122impl Drop for GlobalTimeLoopHandle {
123 fn drop(&mut self) {
124 GLOBAL_TIME_LOOP_STATUS.store(false, Ordering::Release);
125 }
126}
127
128pub fn alloc_rt_uid() -> usize {
132 RUNTIME_UID_GEN.fetch_add(1, Ordering::Relaxed)
133}
134
135pub struct TaskId(UnsafeCell<u128>);
139
140impl Debug for TaskId {
141 fn fmt(&self, f: &mut Formatter) -> FmtResult {
142 write!(f, "TaskId[inner = {}]", unsafe { *self.0.get() })
143 }
144}
145
146impl Clone for TaskId {
147 fn clone(&self) -> Self {
148 unsafe {
149 TaskId(UnsafeCell::new(*self.0.get()))
150 }
151 }
152}
153
154impl TaskId {
155 #[inline]
157 pub fn exist_waker<R: 'static>(&self) -> bool {
158 unsafe {
159 let handle = unsafe { TaskHandle::<R>::from_raw((*self.0.get() >> 64) as *const ()) };
160 let inner = &*handle.0;
161 let r = if let Some(waker) = inner.0.swap(None) {
162 inner.0.swap(Some(waker));
163 true
164 } else {
165 false
166 };
167
168 handle.into_raw();
170
171 r
172 }
173 }
174
175 #[inline]
177 pub fn wakeup<R: 'static>(&self) {
178 unsafe {
179 let handle = unsafe { TaskHandle::<R>::from_raw((*self.0.get() >> 64) as *const ()) };
180 let inner = &*handle.0;
181 if let Some(waker) = inner.0.swap(None) {
182 waker.wake();
184 }
185
186 handle.into_raw();
188 }
189 }
190
191 #[inline]
193 pub fn set_waker<R: 'static>(&self, waker: Waker) -> Option<Waker> {
194 unsafe {
195 let handle = unsafe { TaskHandle::<R>::from_raw((*self.0.get() >> 64) as *const ()) };
196 let inner = &*handle.0;
197 let r = inner.0.swap(Some(waker));
198
199 handle.into_raw();
201
202 r
203 }
204 }
205
206 #[inline]
208 pub fn result<R: 'static>(&self) -> Option<R> {
209 unsafe {
210 let handle = unsafe { TaskHandle::<R>::from_raw((*self.0.get() >> 64) as *const ()) };
211 let inner = &*handle.0;
212 let r = inner.1.swap(None);
213
214 handle.into_raw();
216
217 r
218 }
219 }
220
221 #[inline]
223 pub fn set_result<R: 'static>(&self, result: R) -> Option<R> {
224 unsafe {
225 let handle = unsafe { TaskHandle::<R>::from_raw((*self.0.get() >> 64) as *const ()) };
226 let inner = &*handle.0;
227 let r = inner.1.swap(Some(result));
228
229 handle.into_raw();
231
232 r
233 }
234 }
235}
236
237pub(crate) struct TaskHandle<R: 'static>(Box<(
239 AtomicCell<Option<Waker>>, AtomicCell<Option<R>>, )>);
242
243impl<R: 'static> Default for TaskHandle<R> {
244 fn default() -> Self {
245 TaskHandle(Box::new((AtomicCell::new(None), AtomicCell::new(None))))
246 }
247}
248
249impl<R: 'static> TaskHandle<R> {
250 pub unsafe fn from_raw(raw: *const ()) -> TaskHandle<R> {
252 let inner
253 = Box::from_raw(raw as *const (AtomicCell<Option<Waker>>, AtomicCell<Option<R>>) as *mut (AtomicCell<Option<Waker>>, AtomicCell<Option<R>>));
254 TaskHandle(inner)
255 }
256
257 pub fn into_raw(self) -> *const () {
259 Box::into_raw(self.0)
260 as *mut (AtomicCell<Option<Waker>>, AtomicCell<Option<R>>)
261 as *const (AtomicCell<Option<Waker>>, AtomicCell<Option<R>>)
262 as *const ()
263 }
264}
265
266pub(crate) struct TimeoutWaiter {
268 fired: AtomicBool,
269 waker: AtomicWaker,
270}
271
272impl TimeoutWaiter {
273 #[inline]
274 pub fn new() -> Self {
275 TimeoutWaiter {
276 fired: AtomicBool::new(false),
277 waker: AtomicWaker::new(),
278 }
279 }
280
281 #[inline]
282 pub fn is_fired(&self) -> bool {
283 self.fired.load(Ordering::Acquire)
284 }
285
286 #[inline]
287 pub fn register(&self, waker: &Waker) {
288 self.waker.register(waker);
289 }
290
291 #[inline]
292 pub fn fire(&self) {
293 if !self.fired.swap(true, Ordering::AcqRel) {
294 self.waker.wake();
295 }
296 }
297
298 #[inline]
299 pub fn clear_waker(&self) {
300 let _ = self.waker.take();
301 }
302}
303
304#[inline]
345pub(crate) fn wake_registered_thread_waker(worker_waker: &Arc<(AtomicBool, Mutex<()>, Condvar)>) -> bool {
346 let (is_sleep, lock, condvar) = &**worker_waker;
347 let _locked = lock.lock();
348 if is_sleep
349 .compare_exchange(true, false, Ordering::AcqRel, Ordering::Acquire)
350 .is_ok()
351 {
352 condvar.notify_one();
353 return true;
354 }
355
356 false
357}
358
359#[inline]
383pub(crate) fn wake_thread_waker(worker_waker: &Arc<(AtomicBool, Mutex<()>, Condvar)>) -> bool {
384 if !worker_waker.0.load(Ordering::Acquire) {
385 return false;
386 }
387
388 wake_registered_thread_waker(worker_waker)
389}
390
391#[inline]
432pub(crate) fn wake_waiting_worker(
433 waits: &ArrayQueue<Arc<(AtomicBool, Mutex<()>, Condvar)>>,
434) -> bool {
435 let scan_len = waits.capacity();
436 for _ in 0..scan_len {
437 match waits.pop() {
438 Some(worker_waker) => {
439 if wake_registered_thread_waker(&worker_waker) {
440 return true;
441 }
442 },
443 None => {
444 return false;
445 },
446 }
447 }
448
449 false
450}
451
452#[inline]
488pub(crate) fn prune_stale_waiting_workers(
489 waits: &ArrayQueue<Arc<(AtomicBool, Mutex<()>, Condvar)>>,
490) -> usize {
491 let scan_len = waits.len();
492 let mut pruned = 0;
493
494 for _ in 0..scan_len {
495 let Some(worker_waker) = waits.pop() else {
496 break;
497 };
498
499 let is_live = {
500 let _locked = worker_waker.1.lock();
501 worker_waker.0.load(Ordering::Acquire)
502 };
503
504 if is_live {
505 match waits.push(worker_waker) {
506 Ok(()) => (),
507 Err(worker_waker) => {
508 let _ = wake_registered_thread_waker(&worker_waker);
509 },
510 }
511 } else {
512 pruned += 1;
513 }
514 }
515
516 pruned
517}
518
519#[inline]
555pub(crate) fn register_waiting_worker(
556 waits: &ArrayQueue<Arc<(AtomicBool, Mutex<()>, Condvar)>>,
557 worker_waker: &Arc<(AtomicBool, Mutex<()>, Condvar)>,
558) -> bool {
559 waits.push(worker_waker.clone()).is_ok()
560}
561
562#[cfg(test)]
563mod timeout_waiter_tests {
564 use super::{
565 prune_stale_waiting_workers, register_waiting_worker, wake_thread_waker,
566 wake_waiting_worker, TimeoutWaiter,
567 };
568 use crossbeam_queue::ArrayQueue;
569 use futures::task::{waker_ref, ArcWake};
570 use parking_lot::{Condvar, Mutex};
571 use std::sync::{
572 atomic::{AtomicBool, AtomicUsize, Ordering},
573 Arc,
574 };
575
576 struct WakeCounter(AtomicUsize);
577
578 impl ArcWake for WakeCounter {
579 fn wake_by_ref(arc_self: &Arc<Self>) {
580 arc_self.0.fetch_add(1, Ordering::SeqCst);
581 }
582 }
583
584 #[test]
585 fn test_timeout_waiter_fire_wakes_once() {
586 let waiter = TimeoutWaiter::new();
587 let counter = Arc::new(WakeCounter(AtomicUsize::new(0)));
588 let waker = waker_ref(&counter);
589
590 waiter.register(&waker);
591 waiter.fire();
592 waiter.fire();
593
594 assert!(waiter.is_fired());
595 assert_eq!(counter.0.load(Ordering::SeqCst), 1);
596 }
597
598 #[test]
599 fn test_timeout_waiter_clear_waker_before_fire() {
600 let waiter = TimeoutWaiter::new();
601 let counter = Arc::new(WakeCounter(AtomicUsize::new(0)));
602 let waker = waker_ref(&counter);
603
604 waiter.register(&waker);
605 waiter.clear_waker();
606 waiter.fire();
607
608 assert!(waiter.is_fired());
609 assert_eq!(counter.0.load(Ordering::SeqCst), 0);
610 }
611
612 #[test]
613 fn test_timeout_waiter_replaces_waker() {
614 let waiter = TimeoutWaiter::new();
615 let old_counter = Arc::new(WakeCounter(AtomicUsize::new(0)));
616 let new_counter = Arc::new(WakeCounter(AtomicUsize::new(0)));
617 let old_waker = waker_ref(&old_counter);
618 let new_waker = waker_ref(&new_counter);
619
620 waiter.register(&old_waker);
621 waiter.register(&new_waker);
622 waiter.fire();
623
624 assert!(waiter.is_fired());
625 assert_eq!(old_counter.0.load(Ordering::SeqCst), 0);
626 assert_eq!(new_counter.0.load(Ordering::SeqCst), 1);
627 }
628
629 #[test]
630 fn test_worker_waker_wakes_once() {
631 let worker_waker = Arc::new((AtomicBool::new(true), Mutex::new(()), Condvar::new()));
632
633 assert!(wake_thread_waker(&worker_waker));
634 assert!(!worker_waker.0.load(Ordering::SeqCst));
635 assert!(!wake_thread_waker(&worker_waker));
636 }
637
638 #[test]
639 fn test_worker_waker_wait_queue_skips_stale_and_wakes_one_sleeping_worker() {
640 let waits = ArrayQueue::new(4);
641 let stale = Arc::new((AtomicBool::new(false), Mutex::new(()), Condvar::new()));
642 let sleeping = Arc::new((AtomicBool::new(true), Mutex::new(()), Condvar::new()));
643
644 waits.push(stale).unwrap();
645 waits.push(sleeping.clone()).unwrap();
646
647 assert!(wake_waiting_worker(&waits));
648 assert!(!sleeping.0.load(Ordering::SeqCst));
649 assert!(!wake_waiting_worker(&waits));
650 }
651
652 #[test]
653 fn test_worker_waker_register_and_prune_stale_waiter() {
654 let waits = ArrayQueue::new(1);
655 let stale = Arc::new((AtomicBool::new(false), Mutex::new(()), Condvar::new()));
656 let current = Arc::new((AtomicBool::new(false), Mutex::new(()), Condvar::new()));
657
658 waits.push(stale).unwrap();
659 assert!(!register_waiting_worker(&waits, ¤t));
660 assert_eq!(prune_stale_waiting_workers(&waits), 1);
661 assert!(register_waiting_worker(&waits, ¤t));
662 }
663
664 #[test]
665 fn test_worker_waker_prune_keeps_live_waiter() {
666 let waits = ArrayQueue::new(1);
667 let sleeping = Arc::new((AtomicBool::new(true), Mutex::new(()), Condvar::new()));
668
669 waits.push(sleeping.clone()).unwrap();
670 assert_eq!(prune_stale_waiting_workers(&waits), 0);
671 assert!(wake_waiting_worker(&waits));
672 assert!(!sleeping.0.load(Ordering::SeqCst));
673 }
674}
675
676const ASYNC_TASK_STATE_SCHEDULED: u8 = 0b0000_0001;
684const ASYNC_TASK_STATE_RUNNING: u8 = 0b0000_0010;
685const ASYNC_TASK_STATE_COMPLETED: u8 = 0b0000_0100;
686const ASYNC_TASK_STATE_MANAGED: u8 = 0b1000_0000;
687const ASYNC_TASK_STATE_INITIAL: u8 =
688 ASYNC_TASK_STATE_MANAGED | ASYNC_TASK_STATE_SCHEDULED;
689
690pub(crate) enum AsyncTaskPollClaim {
697 Legacy,
698 Managed,
699 Discard,
700}
701
702enum AsyncTaskWakeAction {
703 LegacyEnqueue,
704 ManagedEnqueue,
705 Coalesced,
706}
707
708pub(crate) struct AsyncTaskPollGuard<
715 'a,
716 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P>,
717 O: Default + 'static = (),
718> {
719 task: &'a AsyncTask<P, O>,
720 armed: bool,
721}
722
723impl<
724 'a,
725 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P>,
726 O: Default + 'static,
727> AsyncTaskPollGuard<'a, P, O> {
728 #[inline]
730 pub(crate) fn new(task: &'a AsyncTask<P, O>) -> Self {
731 AsyncTaskPollGuard {
732 task,
733 armed: true,
734 }
735 }
736
737 #[inline]
742 pub(crate) fn finish_pending(mut self) -> bool {
743 let should_enqueue = self.task.finish_runtime_poll_pending();
744 self.armed = false;
745 should_enqueue
746 }
747
748 #[inline]
753 pub(crate) fn finish_ready(mut self) {
754 self.task.finish_runtime_poll_ready();
755 self.armed = false;
756 }
757}
758
759impl<
760 'a,
761 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P>,
762 O: Default + 'static,
763> Drop for AsyncTaskPollGuard<'a, P, O> {
764 fn drop(&mut self) {
765 if self.armed {
766 self.task.finish_runtime_poll_ready();
767 }
768 }
769}
770
771pub struct AsyncTask<
831 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
832 O: Default + 'static = (),
833> {
834 uid: TaskId, future: Mutex<Option<BoxFuture<'static, O>>>, pool: Arc<P>, priority: usize, context: Option<UnsafeCell<Box<dyn Any>>>, state: AtomicU8, }
841
842impl<
843 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
844 O: Default + 'static,
845> Drop for AsyncTask<P, O> {
846 fn drop(&mut self) {
847 let _ = unsafe { TaskHandle::<O>::from_raw((*self.uid.0.get() >> 64) as usize as *const ()) };
848 }
849}
850
851unsafe impl<
852 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
853 O: Default + 'static,
854> Send for AsyncTask<P, O> {}
855unsafe impl<
856 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
857 O: Default + 'static,
858> Sync for AsyncTask<P, O> {}
859
860impl<
861 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P>,
862 O: Default + 'static,
863> ArcWake for AsyncTask<P, O> {
864 fn wake_by_ref(arc_self: &Arc<Self>) {
876 let notify_on_push_error = match arc_self.prepare_wake() {
877 AsyncTaskWakeAction::Coalesced => return,
878 AsyncTaskWakeAction::LegacyEnqueue => true,
879 AsyncTaskWakeAction::ManagedEnqueue => false,
880 };
881
882 let pool = arc_self.get_pool();
883 let pushed = pool.push_keep(arc_self.clone()).is_ok();
884 if pushed || notify_on_push_error {
885 notify_runtime_task_pool(pool);
886 }
887 }
888}
889
890#[inline]
898pub(crate) fn notify_runtime_task_pool<
899 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P>,
900 O: Default + 'static,
901>(pool: &P) {
902 if let Some(waits) = pool.get_waits() {
903 let _ = wake_waiting_worker(waits);
904 } else if let Some(thread_waker) = pool.get_thread_waker() {
905 let _ = wake_thread_waker(thread_waker);
906 }
907}
908
909#[inline]
917pub(crate) fn requeue_runtime_task<
918 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P>,
919 O: Default + 'static,
920>(pool: &P, task: &Arc<AsyncTask<P, O>>) {
921 if pool.push_keep(task.clone()).is_ok() {
922 notify_runtime_task_pool(pool);
923 }
924}
925
926impl<
927 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P>,
928 O: Default + 'static,
929> AsyncTask<P, O> {
930 pub fn new(uid: TaskId,
939 pool: Arc<P>,
940 priority: usize,
941 future: Option<BoxFuture<'static, O>>) -> AsyncTask<P, O> {
942 AsyncTask {
943 uid,
944 future: Mutex::new(future),
945 pool,
946 priority,
947 context: None,
948 state: AtomicU8::new(ASYNC_TASK_STATE_INITIAL),
949 }
950 }
951
952 pub fn with_context<C: 'static>(uid: TaskId,
959 pool: Arc<P>,
960 priority: usize,
961 future: Option<BoxFuture<'static, O>>,
962 context: C) -> AsyncTask<P, O> {
963 let any = Box::new(context);
964
965 AsyncTask {
966 uid,
967 future: Mutex::new(future),
968 pool,
969 priority,
970 context: Some(UnsafeCell::new(any)),
971 state: AtomicU8::new(ASYNC_TASK_STATE_INITIAL),
972 }
973 }
974
975 pub fn with_runtime_and_context<RT, C>(runtime: &RT,
983 priority: usize,
984 future: Option<BoxFuture<'static, O>>,
985 context: C) -> AsyncTask<P, O>
986 where RT: AsyncRuntime<O, Pool = P>,
987 C: Send + 'static {
988 let any = Box::new(context);
989
990 AsyncTask {
991 uid: runtime.alloc::<O>(),
992 future: Mutex::new(future),
993 pool: runtime.shared_pool(),
994 priority,
995 context: Some(UnsafeCell::new(any)),
996 state: AtomicU8::new(ASYNC_TASK_STATE_INITIAL),
997 }
998 }
999
1000 #[inline]
1007 fn prepare_wake(&self) -> AsyncTaskWakeAction {
1008 let mut current = self.state.load(Ordering::Acquire);
1009 loop {
1010 if current & ASYNC_TASK_STATE_MANAGED == 0 {
1011 return AsyncTaskWakeAction::LegacyEnqueue;
1012 }
1013 if current & ASYNC_TASK_STATE_COMPLETED != 0 {
1014 return AsyncTaskWakeAction::Coalesced;
1015 }
1016
1017 let next = current | ASYNC_TASK_STATE_SCHEDULED;
1018 match self.state.compare_exchange_weak(
1019 current,
1020 next,
1021 Ordering::AcqRel,
1022 Ordering::Acquire,
1023 ) {
1024 Ok(_) => {
1025 if current & (ASYNC_TASK_STATE_SCHEDULED | ASYNC_TASK_STATE_RUNNING) != 0 {
1026 return AsyncTaskWakeAction::Coalesced;
1027 }
1028 return AsyncTaskWakeAction::ManagedEnqueue;
1029 },
1030 Err(actual) => current = actual,
1031 }
1032 }
1033 }
1034
1035 #[inline]
1045 pub(crate) fn try_begin_runtime_poll(&self) -> AsyncTaskPollClaim {
1046 let mut current = self.state.load(Ordering::Acquire);
1047 loop {
1048 if current & ASYNC_TASK_STATE_MANAGED == 0 {
1049 return AsyncTaskPollClaim::Legacy;
1050 }
1051 if current & ASYNC_TASK_STATE_COMPLETED != 0
1052 || current & ASYNC_TASK_STATE_SCHEDULED == 0
1053 || current & ASYNC_TASK_STATE_RUNNING != 0
1054 {
1055 return AsyncTaskPollClaim::Discard;
1056 }
1057
1058 let next =
1059 (current & !ASYNC_TASK_STATE_SCHEDULED) | ASYNC_TASK_STATE_RUNNING;
1060 match self.state.compare_exchange_weak(
1061 current,
1062 next,
1063 Ordering::AcqRel,
1064 Ordering::Acquire,
1065 ) {
1066 Ok(_) => return AsyncTaskPollClaim::Managed,
1067 Err(actual) => current = actual,
1068 }
1069 }
1070 }
1071
1072 #[inline]
1078 pub(crate) fn take_inner_for_runtime_poll(&self) -> Option<BoxFuture<'static, O>> {
1079 self.future.lock().take()
1080 }
1081
1082 #[inline]
1089 pub(crate) fn restore_inner_after_runtime_poll(
1090 &self,
1091 inner: BoxFuture<'static, O>,
1092 ) {
1093 let replaced = {
1094 let mut future = self.future.lock();
1095 future.replace(inner)
1096 };
1097 drop(replaced);
1098 }
1099
1100 #[inline]
1106 fn finish_runtime_poll_pending(&self) -> bool {
1107 let mut current = self.state.load(Ordering::Acquire);
1108 loop {
1109 if current & ASYNC_TASK_STATE_MANAGED == 0
1110 || current & ASYNC_TASK_STATE_COMPLETED != 0
1111 || current & ASYNC_TASK_STATE_RUNNING == 0
1112 {
1113 return false;
1114 }
1115
1116 let next = current & !ASYNC_TASK_STATE_RUNNING;
1117 match self.state.compare_exchange_weak(
1118 current,
1119 next,
1120 Ordering::AcqRel,
1121 Ordering::Acquire,
1122 ) {
1123 Ok(_) => return current & ASYNC_TASK_STATE_SCHEDULED != 0,
1124 Err(actual) => current = actual,
1125 }
1126 }
1127 }
1128
1129 #[inline]
1135 fn finish_runtime_poll_ready(&self) {
1136 self.state.store(
1137 ASYNC_TASK_STATE_MANAGED | ASYNC_TASK_STATE_COMPLETED,
1138 Ordering::Release,
1139 );
1140 }
1141
1142 #[inline]
1152 fn select_legacy_manual_driver(&self, allow_completed: bool) {
1153 let mut current = self.state.load(Ordering::Acquire);
1154 loop {
1155 if current & ASYNC_TASK_STATE_MANAGED == 0
1156 || current & ASYNC_TASK_STATE_RUNNING != 0
1157 || (!allow_completed && current & ASYNC_TASK_STATE_COMPLETED != 0)
1158 {
1159 return;
1160 }
1161
1162 match self.state.compare_exchange_weak(
1163 current,
1164 0,
1165 Ordering::AcqRel,
1166 Ordering::Acquire,
1167 ) {
1168 Ok(_) => return,
1169 Err(actual) => current = actual,
1170 }
1171 }
1172 }
1173
1174 pub fn is_enable_wakeup(&self) -> bool {
1176 self.uid.exist_waker::<O>()
1177 }
1178
1179 pub fn get_inner(&self) -> Option<BoxFuture<'static, O>> {
1189 self.select_legacy_manual_driver(false);
1190 self.future.lock().take()
1191 }
1192
1193 pub fn set_inner(&self, inner: Option<BoxFuture<'static, O>>) {
1204 self.select_legacy_manual_driver(true);
1205 let replaced = {
1206 let mut future = self.future.lock();
1207 std::mem::replace(&mut *future, inner)
1208 };
1209 drop(replaced);
1210 }
1211
1212 #[inline]
1214 pub fn owner(&self) -> usize {
1215 unsafe {
1216 *self.uid.0.get() as usize
1217 }
1218 }
1219
1220 #[inline]
1222 pub fn priority(&self) -> usize {
1223 self.priority
1224 }
1225
1226 pub fn exist_context(&self) -> bool {
1228 self.context.is_some()
1229 }
1230
1231 pub fn get_context<C: Send + 'static>(&self) -> Option<&C> {
1233 if let Some(context) = &self.context {
1234 let any = unsafe { &*context.get() };
1236 return <dyn Any>::downcast_ref::<C>(&**any);
1237 }
1238
1239 None
1240 }
1241
1242 pub fn get_context_mut<C: Send + 'static>(&self) -> Option<&mut C> {
1244 if let Some(context) = &self.context {
1245 let any = unsafe { &mut *context.get() };
1247 return <dyn Any>::downcast_mut::<C>(&mut **any);
1248 }
1249
1250 None
1251 }
1252
1253 pub fn set_context<C: Send + 'static>(&self, new: C) {
1255 if let Some(context) = &self.context {
1256 let _ = unsafe { &*context.get() };
1258
1259 let any: Box<dyn Any + 'static> = Box::new(new);
1261 unsafe { *context.get() = any; }
1262 }
1263 }
1264
1265 pub fn get_pool(&self) -> &P {
1267 self.pool.as_ref()
1268 }
1269}
1270
1271pub trait AsyncTaskPool<O: Default + 'static = ()>: Default + Send + Sync + 'static {
1275 type Pool: AsyncTaskPoolExt<O> + AsyncTaskPool<O>;
1276
1277 fn get_thread_id(&self) -> usize;
1279
1280 fn len(&self) -> usize;
1282
1283 fn push(&self, task: Arc<AsyncTask<Self::Pool, O>>) -> Result<()>;
1285
1286 fn push_local(&self, task: Arc<AsyncTask<Self::Pool, O>>) -> Result<()>;
1288
1289 fn push_priority(&self,
1291 priority: usize,
1292 task: Arc<AsyncTask<Self::Pool, O>>) -> Result<()>;
1293
1294 fn push_keep(&self, task: Arc<AsyncTask<Self::Pool, O>>) -> Result<()>;
1304
1305 fn try_pop(&self) -> Option<Arc<AsyncTask<Self::Pool, O>>>;
1307
1308 fn try_pop_all(&self) -> IntoIter<Arc<AsyncTask<Self::Pool, O>>>;
1310
1311 fn get_thread_waker(&self) -> Option<&Arc<(AtomicBool, Mutex<()>, Condvar)>>;
1313}
1314
1315pub trait AsyncTaskPoolExt<O: Default + 'static = ()>: Send + Sync + 'static {
1319 fn set_waits(&mut self,
1321 _waits: Arc<ArrayQueue<Arc<(AtomicBool, Mutex<()>, Condvar)>>>) {}
1322
1323 fn get_waits(&self) -> Option<&Arc<ArrayQueue<Arc<(AtomicBool, Mutex<()>, Condvar)>>>> {
1325 None
1327 }
1328
1329 fn idler_len(&self) -> usize {
1331 0
1333 }
1334
1335 fn spawn_worker(&self) -> Option<usize> {
1337 None
1339 }
1340
1341 fn worker_len(&self) -> usize {
1343 #[cfg(not(target_arch = "wasm32"))]
1345 return num_cpus::get();
1346 #[cfg(target_arch = "wasm32")]
1347 return 1;
1348 }
1349
1350 fn buffer_len(&self) -> usize {
1352 0
1354 }
1355
1356 fn set_thread_waker(&mut self, _thread_waker: Arc<(AtomicBool, Mutex<()>, Condvar)>) {
1358 }
1360
1361 fn clone_thread_waker(&self) -> Option<Arc<(AtomicBool, Mutex<()>, Condvar)>> {
1363 None
1365 }
1366
1367 fn close_worker(&self) {
1369 }
1371}
1372
1373pub trait AsyncRuntime<O: Default + 'static = ()>: Clone + Send + Sync + 'static {
1377 type Pool: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = Self::Pool>;
1378
1379 fn shared_pool(&self) -> Arc<Self::Pool>;
1381
1382 fn get_id(&self) -> usize;
1384
1385 fn wait_len(&self) -> usize;
1387
1388 fn len(&self) -> usize;
1390
1391 fn alloc<R: 'static>(&self) -> TaskId;
1393
1394 fn spawn<F>(&self, future: F) -> Result<TaskId>
1396 where F: Future<Output = O> + Send + 'static;
1397
1398 fn spawn_local<F>(&self, future: F) -> Result<TaskId>
1400 where F: Future<Output = O> + Send + 'static;
1401
1402 fn spawn_priority<F>(&self, priority: usize, future: F) -> Result<TaskId>
1404 where F: Future<Output = O> + Send + 'static;
1405
1406 fn spawn_yield<F>(&self, future: F) -> Result<TaskId>
1408 where F: Future<Output = O> + Send + 'static;
1409
1410 fn spawn_timing<F>(&self, future: F, time: usize) -> Result<TaskId>
1412 where F: Future<Output = O> + Send + 'static;
1413
1414 fn spawn_by_id<F>(&self, task_id: TaskId, future: F) -> Result<()>
1416 where F: Future<Output = O> + Send + 'static;
1417
1418 fn spawn_local_by_id<F>(&self, task_id: TaskId, future: F) -> Result<()>
1420 where F: Future<Output = O> + Send + 'static;
1421
1422 fn spawn_priority_by_id<F>(&self,
1424 task_id: TaskId,
1425 priority: usize,
1426 future: F) -> Result<()>
1427 where F: Future<Output = O> + Send + 'static;
1428
1429 fn spawn_yield_by_id<F>(&self, task_id: TaskId, future: F) -> Result<()>
1431 where F: Future<Output = O> + Send + 'static;
1432
1433 fn spawn_timing_by_id<F>(&self,
1435 task_id: TaskId,
1436 future: F,
1437 time: usize) -> Result<()>
1438 where F: Future<Output = O> + Send + 'static;
1439
1440 fn pending<Output: 'static>(&self, task_id: &TaskId, waker: Waker) -> Poll<Output>;
1442
1443 fn wakeup<Output: 'static>(&self, task_id: &TaskId);
1445
1446 fn wait<V: Send + 'static>(&self) -> AsyncWait<V>;
1448
1449 fn wait_any<V: Send + 'static>(&self, capacity: usize) -> AsyncWaitAny<V>;
1451
1452 fn wait_any_callback<V: Send + 'static>(&self, capacity: usize) -> AsyncWaitAnyCallback<V>;
1454
1455 fn map_reduce<V: Send + 'static>(&self, capacity: usize) -> AsyncMapReduce<V>;
1457
1458 fn timeout(&self, timeout: usize) -> BoxFuture<'static, ()>;
1460
1461 fn yield_now(&self) -> BoxFuture<'static, ()>;
1463
1464 fn pipeline<S, SO, F, FO>(&self, input: S, filter: F) -> BoxStream<'static, FO>
1466 where S: Stream<Item = SO> + Send + 'static,
1467 SO: Send + 'static,
1468 F: FnMut(SO) -> AsyncPipelineResult<FO> + Send + 'static,
1469 FO: Send + 'static;
1470
1471 fn close(&self) -> bool;
1473}
1474
1475pub trait AsyncRuntimeExt<O: Default + 'static = ()> {
1479 fn spawn_with_context<F, C>(&self,
1481 task_id: TaskId,
1482 future: F,
1483 context: C) -> Result<()>
1484 where F: Future<Output = O> + Send + 'static,
1485 C: 'static;
1486
1487 fn spawn_timing_with_context<F, C>(&self,
1489 task_id: TaskId,
1490 future: F,
1491 context: C,
1492 time: usize) -> Result<()>
1493 where F: Future<Output = O> + Send + 'static,
1494 C: Send + 'static;
1495
1496 fn block_on<F>(&self, future: F) -> Result<F::Output>
1498 where F: Future + Send + 'static,
1499 <F as Future>::Output: Default + Send + 'static;
1500}
1501
1502pub struct AsyncRuntimeBuilder<O: Default + 'static = ()>(PhantomData<O>);
1506
1507impl<O: Default + 'static> AsyncRuntimeBuilder<O> {
1508 pub fn default_worker_thread(worker_name: Option<&str>,
1510 worker_stack_size: Option<usize>,
1511 worker_sleep_timeout: Option<u64>,
1512 worker_loop_interval: Option<Option<u64>>) -> WorkerRuntime<O> {
1513 let runner = WorkerTaskRunner::default();
1514
1515 let thread_name = if let Some(name) = worker_name {
1516 name
1517 } else {
1518 "Default-Single-Worker"
1520 };
1521 let thread_stack_size = if let Some(size) = worker_stack_size {
1522 size
1523 } else {
1524 2 * 1024 * 1024
1526 };
1527 let sleep_timeout = if let Some(timeout) = worker_sleep_timeout {
1528 timeout
1529 } else {
1530 1
1532 };
1533 let loop_interval = if let Some(interval) = worker_loop_interval {
1534 interval
1535 } else {
1536 None
1538 };
1539
1540 let clock = Clock::new();
1542 let runner_copy = runner.clone();
1543 let rt_copy = runner.get_runtime();
1544 let rt = runner.startup(
1545 thread_name,
1546 thread_stack_size,
1547 sleep_timeout,
1548 loop_interval,
1549 move || {
1550 let last = clock.recent();
1551 match runner_copy.run_once() {
1552 Err(e) => {
1553 panic!("Run runner failed, reason: {:?}", e);
1554 },
1555 Ok(len) => {
1556 (len == 0,
1557 clock
1558 .recent()
1559 .duration_since(last))
1560 },
1561 }
1562 },
1563 move || {
1564 rt_copy.wait_len() + rt_copy.len()
1565 },
1566 );
1567
1568 rt
1569 }
1570
1571 pub fn custom_worker_thread<P, F0, F1>(pool: P,
1573 worker_handle: Arc<AtomicBool>,
1574 worker_condvar: Arc<(AtomicBool, Mutex<()>, Condvar)>,
1575 thread_name: &str,
1576 thread_stack_size: usize,
1577 sleep_timeout: u64,
1578 loop_interval: Option<u64>,
1579 loop_func: F0,
1580 get_queue_len: F1) -> WorkerRuntime<O, P>
1581 where P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P>,
1582 F0: Fn() -> (bool, Duration) + Send + 'static,
1583 F1: Fn() -> usize + Send + 'static {
1584 let runner = WorkerTaskRunner::new(pool,
1585 worker_handle,
1586 worker_condvar);
1587
1588 let rt_copy = runner.get_runtime();
1590 let rt = runner.startup(
1591 thread_name,
1592 thread_stack_size,
1593 sleep_timeout,
1594 loop_interval,
1595 loop_func,
1596 move || {
1597 rt_copy.wait_len() + get_queue_len()
1598 },
1599 );
1600
1601 rt
1602 }
1603
1604 pub fn default_multi_thread(worker_prefix: Option<&str>,
1639 worker_stack_size: Option<usize>,
1640 worker_size: Option<usize>,
1641 worker_sleep_timeout: Option<u64>) -> MultiTaskRuntime<O> {
1642 let mut builder = if let Some(size) = worker_size.filter(|size| *size > 0) {
1643 let pool = StealableTaskPool::with(size,
1644 65535,
1645 [1, 1],
1646 3000);
1647 MultiTaskRuntimeBuilder::new(pool)
1648 .thread_stack_size(2 * 1024 * 1024)
1649 .set_timer_interval(1)
1650 } else {
1651 MultiTaskRuntimeBuilder::default()
1652 };
1653
1654 if let Some(size) = worker_size {
1655 builder = builder
1656 .init_worker_size(size)
1657 .set_worker_limit(size, size);
1658 }
1659 if let Some(thread_prefix) = worker_prefix {
1660 builder = builder.thread_prefix(thread_prefix);
1661 }
1662 if let Some(thread_stack_size) = worker_stack_size {
1663 builder = builder.thread_stack_size(thread_stack_size);
1664 }
1665 if let Some(sleep_timeout) = worker_sleep_timeout {
1666 builder = builder.set_timeout(sleep_timeout);
1667 }
1668
1669 builder.build()
1670 }
1671
1672 pub fn custom_multi_thread<P>(pool: P,
1674 worker_prefix: &str,
1675 worker_stack_size: usize,
1676 worker_size: usize,
1677 worker_sleep_timeout: u64,
1678 worker_timer_interval: usize) -> MultiTaskRuntime<O, P>
1679 where P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P> {
1680 MultiTaskRuntimeBuilder::new(pool)
1681 .thread_prefix(worker_prefix)
1682 .thread_stack_size(worker_stack_size)
1683 .init_worker_size(worker_size)
1684 .set_worker_limit(worker_size, worker_size)
1685 .set_timeout(worker_sleep_timeout)
1686 .set_timer_interval(worker_timer_interval)
1687 .build()
1688 }
1689}
1690
1691pub fn bind_local_thread<O: Default + 'static>(runtime: LocalAsyncRuntime<O>) {
1693 match PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME.try_with(move |rt| {
1694 let raw = Arc::into_raw(Arc::new(runtime)) as *mut LocalAsyncRuntime<O> as *mut ();
1695 rt.store(raw, Ordering::Relaxed);
1696 }) {
1697 Err(e) => {
1698 panic!("Bind single runtime to local thread failed, reason: {:?}", e);
1699 },
1700 Ok(_) => (),
1701 }
1702}
1703
1704pub fn unbind_local_thread() {
1706 let _ = PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME.try_with(move |rt| {
1707 rt.store(null_mut(), Ordering::Relaxed);
1708 });
1709}
1710
1711pub struct LocalAsyncRuntime<O: Default + 'static> {
1715 inner: *const (), get_id_func: fn(*const ()) -> usize, spawn_func: fn(*const (), BoxFuture<'static, O>) -> Result<()>, spawn_local_func: fn(*const (), BoxFuture<'static, O>) -> Result<()>, spawn_timing_func: fn(*const (), BoxFuture<'static, O>, usize) -> Result<()>, timeout_func: fn(*const (), usize) -> BoxFuture<'static, ()>, }
1722
1723unsafe impl<O: Default + 'static> Send for LocalAsyncRuntime<O> {}
1724unsafe impl<O: Default + 'static> Sync for LocalAsyncRuntime<O> {}
1725
1726impl<O: Default + 'static> LocalAsyncRuntime<O> {
1727 pub fn new(inner: *const (),
1729 get_id_func: fn(*const ()) -> usize,
1730 spawn_func: fn(*const (), BoxFuture<'static, O>) -> Result<()>,
1731 spawn_local_func: fn(*const (), BoxFuture<'static, O>) -> Result<()>,
1732 spawn_timing_func: fn(*const (), BoxFuture<'static, O>, usize) -> Result<()>,
1733 timeout_func: fn(*const (), usize) -> BoxFuture<'static, ()>) -> Self {
1734 LocalAsyncRuntime {
1735 inner,
1736 get_id_func,
1737 spawn_func,
1738 spawn_local_func,
1739 spawn_timing_func,
1740 timeout_func,
1741 }
1742 }
1743
1744 #[inline]
1746 pub fn get_id(&self) -> usize {
1747 (self.get_id_func)(self.inner)
1748 }
1749
1750 #[inline]
1752 pub fn spawn<F>(&self, future: F) -> Result<()>
1753 where F: Future<Output = O> + Send + 'static {
1754 (self.spawn_func)(self.inner, async move {
1755 future.await
1756 }.boxed())
1757 }
1758
1759 #[inline]
1761 pub fn spawn_local<F>(&self, future: F) -> Result<()>
1762 where F: Future<Output = O> + Send + 'static {
1763 (self.spawn_local_func)(self.inner, async move {
1764 future.await
1765 }.boxed())
1766 }
1767
1768 #[inline]
1770 pub fn sapwn_timing_func<F>(&self, future: F, timeout: usize) -> Result<()>
1771 where F: Future<Output = O> + Send + 'static {
1772 (self.spawn_timing_func)(self.inner,
1773 async move {
1774 future.await
1775 }.boxed(),
1776 timeout)
1777 }
1778
1779 #[inline]
1781 pub fn timeout(&self, timeout: usize) -> BoxFuture<'static, ()> {
1782 (self.timeout_func)(self.inner, timeout)
1783 }
1784}
1785
1786pub fn local_async_runtime<O: Default + 'static>() -> Option<Arc<LocalAsyncRuntime<O>>> {
1791 match PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME.try_with(move |ptr| {
1792 let raw = ptr.load(Ordering::Relaxed) as *const LocalAsyncRuntime<O>;
1793 unsafe {
1794 if raw.is_null() {
1795 None
1797 } else {
1798 let shared: Arc<LocalAsyncRuntime<O>> = unsafe { Arc::from_raw(raw) };
1800 let result = shared.clone();
1801 Arc::into_raw(shared); Some(result)
1803 }
1804 }
1805 }) {
1806 Err(_) => None, Ok(rt) => rt,
1808 }
1809}
1810
1811pub fn spawn_local<O, F>(future: F) -> Result<()>
1816 where O: Default + 'static,
1817 F: Future<Output = O> + Send + 'static {
1818 if let Some(rt) = local_async_runtime::<O>() {
1819 rt.spawn(future)
1820 } else {
1821 Err(Error::new(ErrorKind::Other, format!("Spawn task to local thread failed, reason: runtime not exist")))
1822 }
1823}
1824
1825pub fn get_local_dict<T: 'static>() -> Option<&'static T> {
1829 match PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME_DICT.try_with(move |dict| {
1830 unsafe {
1831 if let Some(any) = (&*dict.get()).get(&TypeId::of::<T>()) {
1832 <dyn Any>::downcast_ref::<T>(&**any)
1834 } else {
1835 None
1837 }
1838 }
1839 }) {
1840 Err(_) => {
1841 None
1842 },
1843 Ok(result) => {
1844 result
1845 }
1846 }
1847}
1848
1849pub fn get_local_dict_mut<T: 'static>() -> Option<&'static mut T> {
1853 match PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME_DICT.try_with(move |dict| {
1854 unsafe {
1855 if let Some(any) = (&mut *dict.get()).get_mut(&TypeId::of::<T>()) {
1856 <dyn Any>::downcast_mut::<T>(&mut **any)
1858 } else {
1859 None
1861 }
1862 }
1863 }) {
1864 Err(_) => {
1865 None
1866 },
1867 Ok(result) => {
1868 result
1869 }
1870 }
1871}
1872
1873pub fn set_local_dict<T: 'static>(value: T) -> Option<T> {
1877 match PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME_DICT.try_with(move |dict| {
1878 unsafe {
1879 let result = if let Some(any) = (&mut *dict.get()).remove(&TypeId::of::<T>()) {
1880 if let Ok(r) = any.downcast() {
1882 Some(*r)
1884 } else {
1885 None
1886 }
1887 } else {
1888 None
1890 };
1891
1892 (&mut *dict.get()).insert(TypeId::of::<T>(), Box::new(value) as Box<dyn Any>);
1894
1895 result
1896 }
1897 }) {
1898 Err(_) => {
1899 None
1900 },
1901 Ok(result) => {
1902 result
1903 }
1904 }
1905}
1906
1907pub fn remove_local_dict<T: 'static>() -> Option<T> {
1911 match PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME_DICT.try_with(move |dict| {
1912 unsafe {
1913 if let Some(any) = (&mut *dict.get()).remove(&TypeId::of::<T>()) {
1914 if let Ok(r) = any.downcast() {
1916 Some(*r)
1918 } else {
1919 None
1920 }
1921 } else {
1922 None
1924 }
1925 }
1926 }) {
1927 Err(_) => {
1928 None
1929 },
1930 Ok(result) => {
1931 result
1932 }
1933 }
1934}
1935
1936pub fn clear_local_dict() -> Result<()> {
1940 match PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME_DICT.try_with(move |dict| {
1941 unsafe {
1942 (&mut *dict.get()).clear();
1943 }
1944 }) {
1945 Err(e) => {
1946 Err(Error::new(ErrorKind::Other, format!("Clear local dict failed, reason: {:?}", e)))
1947 },
1948 Ok(_) => {
1949 Ok(())
1950 }
1951 }
1952}
1953
1954const ASYNC_VALUE_EMPTY: u8 = 0;
1955const ASYNC_VALUE_WAITING: u8 = 1;
1956const ASYNC_VALUE_SETTING: u8 = 2;
1957const ASYNC_VALUE_READY: u8 = 3;
1958const ASYNC_VALUE_TAKING: u8 = 4;
1959const ASYNC_VALUE_CONSUMED: u8 = 5;
1960
1961pub struct AsyncValue<V: Send + 'static>(Arc<InnerAsyncValue<V>>);
1982
1983unsafe impl<V: Send + 'static> Send for AsyncValue<V> {}
1984unsafe impl<V: Send + 'static> Sync for AsyncValue<V> {}
1985
1986impl<V: Send + 'static> Clone for AsyncValue<V> {
1987 fn clone(&self) -> Self {
1988 AsyncValue(self.0.clone())
1989 }
1990}
1991
1992impl<V: Send + 'static> Debug for AsyncValue<V> {
1993 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
1994 write!(f,
1995 "AsyncValue[status = {}]",
1996 self.0.status.load(Ordering::Acquire))
1997 }
1998}
1999
2000impl<V: Send + 'static> Future for AsyncValue<V> {
2001 type Output = V;
2002
2003 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2004 let mut spin_len = 1;
2005 loop {
2006 match self.0.status.load(Ordering::Acquire) {
2007 ASYNC_VALUE_EMPTY => {
2008 self.0.waker.register(cx.waker());
2009 match self.0.status.compare_exchange(ASYNC_VALUE_EMPTY,
2010 ASYNC_VALUE_WAITING,
2011 Ordering::AcqRel,
2012 Ordering::Acquire) {
2013 Ok(_) => {
2014 return Poll::Pending;
2015 },
2016 Err(ASYNC_VALUE_EMPTY) => {
2017 continue;
2018 },
2019 Err(ASYNC_VALUE_WAITING) | Err(ASYNC_VALUE_SETTING) => {
2020 return Poll::Pending;
2021 },
2022 Err(ASYNC_VALUE_READY) => {
2023 continue;
2024 },
2025 Err(ASYNC_VALUE_TAKING) => {
2026 spin_len = spin(spin_len);
2027 continue;
2028 },
2029 Err(ASYNC_VALUE_CONSUMED) => {
2030 panic!("AsyncValue polled after completion");
2031 },
2032 Err(_) => {
2033 panic!("AsyncValue entered invalid state");
2034 },
2035 }
2036 },
2037 ASYNC_VALUE_WAITING | ASYNC_VALUE_SETTING => {
2038 self.0.waker.register(cx.waker());
2039 match self.0.status.load(Ordering::Acquire) {
2040 ASYNC_VALUE_READY => {
2041 continue;
2042 },
2043 ASYNC_VALUE_TAKING => {
2044 spin_len = spin(spin_len);
2045 continue;
2046 },
2047 ASYNC_VALUE_CONSUMED => {
2048 panic!("AsyncValue polled after completion");
2049 },
2050 _ => {
2051 return Poll::Pending;
2052 },
2053 }
2054 },
2055 ASYNC_VALUE_READY => {
2056 match self.0.status.compare_exchange(ASYNC_VALUE_READY,
2057 ASYNC_VALUE_TAKING,
2058 Ordering::AcqRel,
2059 Ordering::Acquire) {
2060 Ok(_) => {
2061 let value = unsafe { (*self.0.value.get()).take().unwrap() };
2062 self.0.status.store(ASYNC_VALUE_CONSUMED, Ordering::Release);
2063 return Poll::Ready(value);
2064 },
2065 Err(ASYNC_VALUE_TAKING) => {
2066 spin_len = spin(spin_len);
2067 continue;
2068 },
2069 Err(ASYNC_VALUE_CONSUMED) => {
2070 panic!("AsyncValue polled after completion");
2071 },
2072 Err(_) => {
2073 continue;
2074 },
2075 }
2076 },
2077 ASYNC_VALUE_TAKING => {
2078 spin_len = spin(spin_len);
2080 continue;
2081 },
2082 ASYNC_VALUE_CONSUMED => {
2083 panic!("AsyncValue polled after completion");
2084 },
2085 _ => {
2086 panic!("AsyncValue entered invalid state");
2087 },
2088 }
2089 }
2090 }
2091}
2092
2093impl<V: Send + 'static> AsyncValue<V> {
2097 pub fn new() -> Self {
2099 let inner = InnerAsyncValue {
2100 value: UnsafeCell::new(None),
2101 waker: AtomicWaker::new(),
2102 status: AtomicU8::new(ASYNC_VALUE_EMPTY),
2103 };
2104
2105 AsyncValue(Arc::new(inner))
2106 }
2107
2108 pub fn is_complete(&self) -> bool {
2110 match self.0.status.load(Ordering::Acquire) {
2111 ASYNC_VALUE_READY | ASYNC_VALUE_TAKING | ASYNC_VALUE_CONSUMED => true,
2112 _ => false,
2113 }
2114 }
2115
2116 pub fn set(self, value: V) {
2118 let mut value = Some(value);
2119 loop {
2120 match self.0.status.load(Ordering::Acquire) {
2121 ASYNC_VALUE_EMPTY => {
2122 match self.0.status.compare_exchange(ASYNC_VALUE_EMPTY,
2123 ASYNC_VALUE_SETTING,
2124 Ordering::AcqRel,
2125 Ordering::Acquire) {
2126 Ok(_) => {
2127 unsafe { *self.0.value.get() = value.take(); }
2128 self.0.status.store(ASYNC_VALUE_READY, Ordering::Release);
2129 self.0.waker.wake();
2130 return;
2131 },
2132 Err(_) => {
2133 continue;
2134 },
2135 }
2136 },
2137 ASYNC_VALUE_WAITING => {
2138 match self.0.status.compare_exchange(ASYNC_VALUE_WAITING,
2139 ASYNC_VALUE_SETTING,
2140 Ordering::AcqRel,
2141 Ordering::Acquire) {
2142 Ok(_) => {
2143 unsafe { *self.0.value.get() = value.take(); }
2144 self.0.status.store(ASYNC_VALUE_READY, Ordering::Release);
2145 self.0.waker.wake();
2146 return;
2147 },
2148 Err(_) => {
2149 continue;
2150 },
2151 }
2152 },
2153 _ => {
2154 return;
2156 }
2157 }
2158 }
2159 }
2160}
2161
2162pub struct InnerAsyncValue<V: Send + 'static> {
2164 value: UnsafeCell<Option<V>>, waker: AtomicWaker, status: AtomicU8, }
2168
2169pub struct AsyncVariableGuard<'a, V: Send + 'static> {
2173 value: &'a UnsafeCell<Option<V>>, waker: &'a UnsafeCell<Option<Waker>>, status: &'a AtomicU8, }
2177
2178unsafe impl<V: Send + 'static> Send for AsyncVariableGuard<'_, V> {}
2179
2180impl<V: Send + 'static> Drop for AsyncVariableGuard<'_, V> {
2181 fn drop(&mut self) {
2182 self.status.fetch_sub(2, Ordering::Relaxed);
2186 }
2187}
2188
2189impl<V: Send + 'static> Deref for AsyncVariableGuard<'_, V> {
2190 type Target = Option<V>;
2191
2192 fn deref(&self) -> &Self::Target {
2193 unsafe {
2194 &*self.value.get()
2195 }
2196 }
2197}
2198
2199impl<V: Send + 'static> DerefMut for AsyncVariableGuard<'_, V> {
2200 fn deref_mut(&mut self) -> &mut Self::Target {
2201 unsafe {
2202 &mut *self.value.get()
2203 }
2204 }
2205}
2206
2207impl<V: Send + 'static> AsyncVariableGuard<'_, V> {
2208 pub fn finish(self) {
2210 if self.status.fetch_add(4, Ordering::Relaxed) == 3 {
2212 if let Some(waker) = unsafe { (&mut *self.waker.get()).take() } {
2213 waker.wake();
2215 }
2216 }
2217 }
2218}
2219
2220pub struct AsyncVariable<V: Send + 'static>(Arc<InnerAsyncVariable<V>>);
2224
2225unsafe impl<V: Send + 'static> Send for AsyncVariable<V> {}
2226unsafe impl<V: Send + 'static> Sync for AsyncVariable<V> {}
2227
2228impl<V: Send + 'static> Clone for AsyncVariable<V> {
2229 fn clone(&self) -> Self {
2230 AsyncVariable(self.0.clone())
2231 }
2232}
2233
2234impl<V: Send + 'static> Future for AsyncVariable<V> {
2235 type Output = V;
2236
2237 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2238 unsafe {
2239 *self.0.waker.get() = Some(cx.waker().clone()); }
2241
2242 let mut spin_len = 1;
2243 loop {
2244 match self.0.status.compare_exchange(0,
2245 1,
2246 Ordering::Acquire,
2247 Ordering::Relaxed) {
2248 Err(current) if current & 4 != 0 => {
2249 unsafe {
2251 let _ = (&mut *self.0.waker.get()).take(); return Poll::Ready((&mut *(&self).0.value.get()).take().unwrap());
2253 }
2254 },
2255 Err(_) => {
2256 spin_len = spin(spin_len);
2258 },
2259 Ok(_) => {
2260 return Poll::Pending;
2262 },
2263 }
2264 }
2265 }
2266}
2267
2268impl<V: Send + 'static> AsyncVariable<V> {
2269 pub fn new() -> Self {
2271 let inner = InnerAsyncVariable {
2272 value: UnsafeCell::new(None),
2273 waker: UnsafeCell::new(None),
2274 status: AtomicU8::new(0),
2275 };
2276
2277 AsyncVariable(Arc::new(inner))
2278 }
2279
2280 pub fn is_complete(&self) -> bool {
2282 self
2283 .0
2284 .status
2285 .load(Ordering::Acquire) & 4 != 0
2286 }
2287
2288 pub fn lock(&self) -> Option<AsyncVariableGuard<V>> {
2290 let mut spin_len = 1;
2291 loop {
2292 match self
2293 .0
2294 .status
2295 .compare_exchange(1,
2296 3,
2297 Ordering::Acquire,
2298 Ordering::Relaxed) {
2299 Err(0) => {
2300 match self
2302 .0
2303 .status
2304 .compare_exchange(0,
2305 2,
2306 Ordering::Acquire,
2307 Ordering::Relaxed) {
2308 Err(1) => {
2309 continue;
2311 },
2312 Err(2) => {
2313 spin_len = spin(spin_len);
2315 },
2316 Err(3) => {
2317 spin_len = spin(spin_len);
2319 },
2320 Err(_) => {
2321 return None;
2323 },
2324 Ok(_) => {
2325 let guard = AsyncVariableGuard {
2327 value: &self.0.value,
2328 waker: &self.0.waker,
2329 status: &self.0.status,
2330 };
2331
2332 return Some(guard)
2333 },
2334 }
2335 },
2336 Err(2) => {
2337 spin_len = spin(spin_len);
2339 },
2340 Err(3) => {
2341 spin_len = spin(spin_len);
2343 },
2344 Err(_) => {
2345 return None;
2347 }
2348 Ok(_) => {
2349 let guard = AsyncVariableGuard {
2351 value: &self.0.value,
2352 waker: &self.0.waker,
2353 status: &self.0.status,
2354 };
2355
2356 return Some(guard)
2357 },
2358 }
2359 }
2360 }
2361}
2362
2363pub struct InnerAsyncVariable<V: Send + 'static> {
2365 value: UnsafeCell<Option<V>>, waker: UnsafeCell<Option<Waker>>, status: AtomicU8, }
2369
2370pub struct AsyncWaitResult<V: Send + 'static>(pub Arc<RefCell<Option<Result<V>>>>);
2374
2375unsafe impl<V: Send + 'static> Send for AsyncWaitResult<V> {}
2376unsafe impl<V: Send + 'static> Sync for AsyncWaitResult<V> {}
2377
2378impl<V: Send + 'static> Clone for AsyncWaitResult<V> {
2379 fn clone(&self) -> Self {
2380 AsyncWaitResult(self.0.clone())
2381 }
2382}
2383
2384pub struct AsyncWaitResults<V: Send + 'static>(pub Arc<RefCell<Option<Vec<Result<V>>>>>);
2388
2389unsafe impl<V: Send + 'static> Send for AsyncWaitResults<V> {}
2390unsafe impl<V: Send + 'static> Sync for AsyncWaitResults<V> {}
2391
2392impl<V: Send + 'static> Clone for AsyncWaitResults<V> {
2393 fn clone(&self) -> Self {
2394 AsyncWaitResults(self.0.clone())
2395 }
2396}
2397
2398pub enum AsyncTimingTask<
2402 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2403 O: Default + 'static = (),
2404> {
2405 Pended(TaskId), WaitRun(Arc<AsyncTask<P, O>>), TimeoutWake(Arc<TimeoutWaiter>), }
2409
2410pub struct AsyncTaskTimer<
2414 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2415 O: Default + 'static = (),
2416> {
2417 producor: Sender<(usize, AsyncTimingTask<P, O>)>, consumer: Receiver<(usize, AsyncTimingTask<P, O>)>, timer: Arc<RefCell<Timer<AsyncTimingTask<P, O>, 1000, 60, 3>>>, clock: Clock, now: QInstant, }
2423
2424unsafe impl<
2425 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2426 O: Default + 'static,
2427> Send for AsyncTaskTimer<P, O> {}
2428unsafe impl<
2429 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2430 O: Default + 'static,
2431> Sync for AsyncTaskTimer<P, O> {}
2432
2433impl<
2434 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2435 O: Default + 'static,
2436> AsyncTaskTimer<P, O> {
2437 pub fn new() -> Self {
2439 let (producor, consumer) = unbounded();
2440 let clock = Clock::new();
2441 let now = clock.recent();
2442
2443 AsyncTaskTimer {
2444 producor,
2445 consumer,
2446 timer: Arc::new(RefCell::new(Timer::<AsyncTimingTask<P, O>, 1000, 60, 3>::default())),
2447 clock,
2448 now,
2449 }
2450 }
2451
2452 #[inline]
2454 pub fn get_producor(&self) -> &Sender<(usize, AsyncTimingTask<P, O>)> {
2455 &self.producor
2456 }
2457
2458 #[inline]
2460 pub fn len(&self) -> usize {
2461 let timer = self.timer.as_ref().borrow();
2462 timer.add_count() - timer.remove_count()
2463 }
2464
2465 pub fn set_timer(&self, task: AsyncTimingTask<P, O>, timeout: usize) -> usize {
2467 let current_time = self
2468 .clock
2469 .recent()
2470 .duration_since(self.now)
2471 .as_millis() as u64;
2472 self
2473 .timer
2474 .borrow_mut()
2475 .push_time(current_time + timeout as u64, task)
2476 .data()
2477 .as_ffi() as usize
2478 }
2479
2480 pub fn cancel_timer(&self, timer_ref: usize) -> Option<AsyncTimingTask<P, O>> {
2482 if let Some(item) = self
2483 .timer
2484 .borrow_mut()
2485 .cancel(KeyData::from_ffi(timer_ref as u64).into()) {
2486 Some(item)
2487 } else {
2488 None
2489 }
2490 }
2491
2492 pub fn consume(&self) -> usize {
2494 let timer_tasks = self.consumer.try_iter().collect::<Vec<(usize, AsyncTimingTask<P, O>)>>();
2495 let len = timer_tasks.len();
2496 for (timeout, task) in timer_tasks {
2497 self.set_timer(task, timeout);
2498 }
2499
2500 len
2501 }
2502
2503 pub fn is_require_pop(&self) -> Option<u64> {
2505 let current_time = self
2506 .clock
2507 .recent()
2508 .duration_since(self.now)
2509 .as_millis() as u64;
2510 if self.timer.borrow_mut().is_ok(current_time) {
2511 Some(current_time)
2512 } else {
2513 None
2514 }
2515 }
2516
2517 pub fn pop(&self, current_time: u64) -> Option<(usize, AsyncTimingTask<P, O>)> {
2519 if let Some((key, item)) = self.timer.borrow_mut().pop_kv(current_time) {
2520 Some((key.data().as_ffi() as usize, item))
2521 } else {
2522 None
2523 }
2524 }
2525}
2526
2527pub struct AsyncTaskTimerByNotCancel<
2531 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2532 O: Default + 'static = (),
2533> {
2534 producor: Sender<(usize, AsyncTimingTask<P, O>)>, consumer: Receiver<(usize, AsyncTimingTask<P, O>)>, timer: Arc<RefCell<NotCancelTimer<AsyncTimingTask<P, O>, 1000, 60, 3>>>, clock: Clock, now: QInstant, }
2540
2541unsafe impl<
2542 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2543 O: Default + 'static,
2544> Send for AsyncTaskTimerByNotCancel<P, O> {}
2545unsafe impl<
2546 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2547 O: Default + 'static,
2548> Sync for AsyncTaskTimerByNotCancel<P, O> {}
2549
2550impl<
2551 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2552 O: Default + 'static,
2553> AsyncTaskTimerByNotCancel<P, O> {
2554 pub fn new() -> Self {
2556 let (producor, consumer) = unbounded();
2557 let clock = Clock::new();
2558 let now = clock.recent();
2559
2560 AsyncTaskTimerByNotCancel {
2561 producor,
2562 consumer,
2563 timer: Arc::new(RefCell::new(NotCancelTimer::<AsyncTimingTask<P, O>, 1000, 60, 3>::default())),
2564 clock,
2565 now,
2566 }
2567 }
2568
2569 #[inline]
2571 pub fn get_producor(&self) -> &Sender<(usize, AsyncTimingTask<P, O>)> {
2572 &self.producor
2573 }
2574
2575 #[inline]
2577 pub fn len(&self) -> usize {
2578 let timer = self.timer.as_ref().borrow();
2579 timer.add_count() - timer.remove_count()
2580 }
2581
2582 pub fn set_timer(&self, task: AsyncTimingTask<P, O>, timeout: usize) {
2584 self
2585 .timer
2586 .borrow_mut()
2587 .push(timeout, task);
2588 }
2589
2590 pub fn consume(&self) -> usize {
2592 let timer_tasks = self.consumer.try_iter().collect::<Vec<(usize, AsyncTimingTask<P, O>)>>();
2593 let len = timer_tasks.len();
2594 for (timeout, task) in timer_tasks {
2595 self.set_timer(task, timeout);
2596 }
2597
2598 len
2599 }
2600
2601 pub fn is_require_pop(&self) -> Option<u64> {
2603 let current_time = self
2604 .clock
2605 .recent()
2606 .duration_since(self.now)
2607 .as_millis() as u64;
2608 if self.timer.borrow_mut().is_ok(current_time) {
2609 Some(current_time)
2610 } else {
2611 None
2612 }
2613 }
2614
2615 pub fn pop(&self, current_time: u64) -> Option<AsyncTimingTask<P, O>> {
2617 if let Some(item) = self.timer.borrow_mut().pop(current_time) {
2618 Some(item)
2619 } else {
2620 None
2621 }
2622 }
2623}
2624
2625pub struct AsyncWaitTimeout<
2629 RT: AsyncRuntime<O>,
2630 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2631 O: Default + 'static = (),
2632> {
2633 rt: RT, producor: Sender<(usize, AsyncTimingTask<P, O>)>, timeout: usize, registered: AtomicBool, waiter: Arc<TimeoutWaiter>, }
2639
2640unsafe impl<
2641 RT: AsyncRuntime<O>,
2642 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2643 O: Default + 'static,
2644> Send for AsyncWaitTimeout<RT, P, O> {}
2645unsafe impl<
2646 RT: AsyncRuntime<O>,
2647 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2648 O: Default + 'static,
2649> Sync for AsyncWaitTimeout<RT, P, O> {}
2650
2651impl<
2652 RT: AsyncRuntime<O>,
2653 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2654 O: Default + 'static,
2655> Future for AsyncWaitTimeout<RT, P, O> {
2656 type Output = ();
2657
2658 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2659 if self.waiter.is_fired() {
2660 return Poll::Ready(());
2662 }
2663
2664 self.waiter.register(cx.waker());
2665
2666 if !self.registered.swap(true, Ordering::AcqRel) {
2667 let _ = self
2669 .producor
2670 .send((self.timeout, AsyncTimingTask::TimeoutWake(self.waiter.clone())));
2671 }
2672
2673 if self.waiter.is_fired() {
2674 Poll::Ready(())
2675 } else {
2676 Poll::Pending
2677 }
2678 }
2679}
2680
2681impl<
2682 RT: AsyncRuntime<O>,
2683 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2684 O: Default + 'static,
2685> Drop for AsyncWaitTimeout<RT, P, O> {
2686 fn drop(&mut self) {
2687 self.waiter.clear_waker();
2688 }
2689}
2690
2691impl<
2692 RT: AsyncRuntime<O>,
2693 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2694 O: Default + 'static,
2695> AsyncWaitTimeout<RT, P, O> {
2696 pub fn new(rt: RT,
2698 producor: Sender<(usize, AsyncTimingTask<P, O>)>,
2699 timeout: usize) -> Self {
2700 AsyncWaitTimeout {
2701 rt,
2702 producor,
2703 timeout,
2704 registered: AtomicBool::new(false), waiter: Arc::new(TimeoutWaiter::new()),
2706 }
2707 }
2708}
2709
2710pub struct LocalAsyncWaitTimeout<
2714 RT: AsyncRuntime<O>,
2715 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2716 O: Default + 'static = (),
2717> {
2718 rt: RT, timer: Arc<AsyncTaskTimerByNotCancel<P, O>>, timeout: usize, registered: AtomicBool, waiter: Arc<TimeoutWaiter>, }
2724
2725unsafe impl<
2726 RT: AsyncRuntime<O>,
2727 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2728 O: Default + 'static,
2729> Send for LocalAsyncWaitTimeout<RT, P, O> {}
2730unsafe impl<
2731 RT: AsyncRuntime<O>,
2732 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2733 O: Default + 'static,
2734> Sync for LocalAsyncWaitTimeout<RT, P, O> {}
2735
2736impl<
2737 RT: AsyncRuntime<O>,
2738 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2739 O: Default + 'static,
2740> Future for LocalAsyncWaitTimeout<RT, P, O> {
2741 type Output = ();
2742
2743 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2744 if self.waiter.is_fired() {
2745 return Poll::Ready(());
2747 }
2748
2749 self.waiter.register(cx.waker());
2750
2751 if !self.registered.swap(true, Ordering::AcqRel) {
2752 self
2754 .timer
2755 .set_timer(AsyncTimingTask::TimeoutWake(self.waiter.clone()),
2756 self.timeout);
2757 }
2758
2759 if self.waiter.is_fired() {
2760 Poll::Ready(())
2761 } else {
2762 Poll::Pending
2763 }
2764 }
2765}
2766
2767impl<
2768 RT: AsyncRuntime<O>,
2769 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2770 O: Default + 'static,
2771> Drop for LocalAsyncWaitTimeout<RT, P, O> {
2772 fn drop(&mut self) {
2773 self.waiter.clear_waker();
2774 }
2775}
2776
2777impl<
2778 RT: AsyncRuntime<O>,
2779 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2780 O: Default + 'static,
2781> LocalAsyncWaitTimeout<RT, P, O> {
2782 pub fn new(rt: RT,
2784 timer: Arc<AsyncTaskTimerByNotCancel<P, O>>,
2785 timeout: usize) -> Self {
2786 LocalAsyncWaitTimeout {
2787 rt,
2788 timer,
2789 timeout,
2790 registered: AtomicBool::new(false), waiter: Arc::new(TimeoutWaiter::new()),
2792 }
2793 }
2794}
2795
2796pub struct AsyncWait<V: Send + 'static>(AsyncWaitAny<V>);
2800
2801unsafe impl<V: Send + 'static> Send for AsyncWait<V> {}
2802unsafe impl<V: Send + 'static> Sync for AsyncWait<V> {}
2803
2804impl<V: Send + 'static> AsyncWait<V> {
2808 pub fn spawn<RT, O, F>(&self,
2810 rt: RT,
2811 timeout: Option<usize>,
2812 future: F) -> Result<()>
2813 where RT: AsyncRuntime<O>,
2814 O: Default + 'static,
2815 F: Future<Output = Result<V>> + Send + 'static {
2816 self.0.spawn(rt.clone(), future)?;
2817
2818 if let Some(timeout) = timeout {
2819 let rt_copy = rt.clone();
2821 self.0.spawn(rt, async move {
2822 rt_copy.timeout(timeout).await;
2823
2824 Err(Error::new(ErrorKind::TimedOut, format!("Time out")))
2826 })
2827 } else {
2828 Ok(())
2830 }
2831 }
2832
2833 pub fn spawn_local<O, F>(&self,
2835 timeout: Option<usize>,
2836 future: F) -> Result<()>
2837 where O: Default + 'static,
2838 F: Future<Output = Result<V>> + Send + 'static {
2839 if let Some(rt) = local_async_runtime::<O>() {
2840 self.0.spawn_local(future)?;
2842
2843 if let Some(timeout) = timeout {
2844 let rt_copy = rt.clone();
2846 self.0.spawn_local(async move {
2847 rt_copy.timeout(timeout).await;
2848
2849 Err(Error::new(ErrorKind::TimedOut, format!("Time out")))
2851 })
2852 } else {
2853 Ok(())
2855 }
2856 } else {
2857 Err(Error::new(ErrorKind::Other, format!("Spawn wait task failed, reason: local async runtime not exist")))
2859 }
2860 }
2861}
2862
2863impl<V: Send + 'static> AsyncWait<V> {
2867 pub async fn wait_result(self) -> Result<V> {
2869 self.0.wait_result().await
2870 }
2871}
2872
2873pub struct AsyncWaitAny<V: Send + 'static> {
2877 capacity: usize, producor: AsyncSender<Result<V>>, consumer: AsyncReceiver<Result<V>>, }
2881
2882unsafe impl<V: Send + 'static> Send for AsyncWaitAny<V> {}
2883unsafe impl<V: Send + 'static> Sync for AsyncWaitAny<V> {}
2884
2885impl<V: Send + 'static> AsyncWaitAny<V> {
2889 pub fn spawn<RT, O, F>(&self,
2891 rt: RT,
2892 future: F) -> Result<()>
2893 where RT: AsyncRuntime<O>,
2894 O: Default + 'static,
2895 F: Future<Output = Result<V>> + Send + 'static {
2896 let producor = self.producor.clone();
2897 rt.spawn_by_id(rt.alloc::<O>(), async move {
2898 let value = future.await;
2899 producor.into_send_async(value).await;
2900
2901 Default::default()
2903 })
2904 }
2905
2906 pub fn spawn_local<F>(&self,
2908 future: F) -> Result<()>
2909 where F: Future<Output = Result<V>> + Send + 'static {
2910 if let Some(rt) = local_async_runtime() {
2911 let producor = self.producor.clone();
2913 rt.spawn(async move {
2914 let value = future.await;
2915 producor.into_send_async(value).await;
2916 })
2917 } else {
2918 Err(Error::new(ErrorKind::Other, format!("Spawn wait any task failed, reason: local async runtime not exist")))
2920 }
2921 }
2922}
2923
2924impl<V: Send + 'static> AsyncWaitAny<V> {
2928 pub async fn wait_result(self) -> Result<V> {
2930 match self.consumer.recv_async().await {
2931 Err(e) => {
2932 Err(Error::new(ErrorKind::Other, format!("Wait any result failed, reason: {:?}", e)))
2934 },
2935 Ok(result) => {
2936 result
2938 },
2939 }
2940 }
2941}
2942
2943pub struct AsyncWaitAnyCallback<V: Send + 'static> {
2947 capacity: usize, producor: AsyncSender<Result<V>>, consumer: AsyncReceiver<Result<V>>, }
2951
2952unsafe impl<V: Send + 'static> Send for AsyncWaitAnyCallback<V> {}
2953unsafe impl<V: Send + 'static> Sync for AsyncWaitAnyCallback<V> {}
2954
2955impl<V: Send + 'static> AsyncWaitAnyCallback<V> {
2959 pub fn spawn<RT, O, F>(&self,
2961 rt: RT,
2962 future: F) -> Result<()>
2963 where RT: AsyncRuntime<O>,
2964 O: Default + 'static,
2965 F: Future<Output = Result<V>> + Send + 'static {
2966 let producor = self.producor.clone();
2967 rt.spawn_by_id(rt.alloc::<O>(), async move {
2968 let value = future.await;
2969 producor.into_send_async(value).await;
2970
2971 Default::default()
2973 })
2974 }
2975
2976 pub fn spawn_local<F>(&self,
2978 future: F) -> Result<()>
2979 where F: Future<Output = Result<V>> + Send + 'static {
2980 if let Some(rt) = local_async_runtime() {
2981 let producor = self.producor.clone();
2983 rt.spawn(async move {
2984 let value = future.await;
2985 producor.into_send_async(value).await;
2986 })
2987 } else {
2988 Err(Error::new(ErrorKind::Other, format!("Spawn wait any task failed by callback, reason: current async runtime not exist")))
2990 }
2991 }
2992}
2993
2994impl<V: Send + 'static> AsyncWaitAnyCallback<V> {
2998 pub async fn wait_result(mut self,
3000 callback: impl Fn(&Result<V>) -> bool + Send + Sync + 'static) -> Result<V> {
3001 let checker = create_checker(self.capacity, callback);
3002 loop {
3003 match self.consumer.recv_async().await {
3004 Err(e) => {
3005 return Err(Error::new(ErrorKind::Other, format!("Wait any result failed by callback, reason: {:?}", e)));
3007 },
3008 Ok(result) => {
3009 if checker(&result) {
3011 return result;
3013 }
3014 },
3015 }
3016 }
3017 }
3018}
3019
3020fn create_checker<V, F>(len: usize,
3022 callback: F) -> Arc<dyn Fn(&Result<V>) -> bool + Send + Sync + 'static>
3023 where V: Send + 'static,
3024 F: Fn(&Result<V>) -> bool + Send + Sync + 'static {
3025 let mut check_counter = AtomicUsize::new(len); Arc::new(move |result| {
3027 if check_counter.fetch_sub(1, Ordering::SeqCst) == 1 {
3028 true
3030 } else {
3031 callback(result)
3033 }
3034 })
3035}
3036
3037pub struct AsyncMapReduce<V: Send + 'static> {
3041 count: usize, capacity: usize, producor: AsyncSender<(usize, Result<V>)>, consumer: AsyncReceiver<(usize, Result<V>)>, }
3046
3047unsafe impl<V: Send + 'static> Send for AsyncMapReduce<V> {}
3048
3049impl<V: Send + 'static> AsyncMapReduce<V> {
3053 pub fn map<RT, O, F>(&mut self, rt: RT, future: F) -> Result<usize>
3055 where RT: AsyncRuntime<O>,
3056 O: Default + 'static,
3057 F: Future<Output = Result<V>> + Send + 'static {
3058 if self.count >= self.capacity {
3059 return Err(Error::new(ErrorKind::Other, format!("Map task to runtime failed, capacity: {}, reason: out of capacity", self.capacity)));
3061 }
3062
3063 let index = self.count;
3064 let producor = self.producor.clone();
3065 rt.spawn_by_id(rt.alloc::<O>(), async move {
3066 let value = future.await;
3067 producor.into_send_async((index, value)).await;
3068
3069 Default::default()
3071 })?;
3072
3073 self.count += 1; Ok(index)
3075 }
3076}
3077
3078impl<V: Send + 'static> AsyncMapReduce<V> {
3082 pub async fn reduce(self, order: bool) -> Result<Vec<Result<V>>> {
3084 let mut count = self.count;
3085 let mut results = Vec::with_capacity(count);
3086 while count > 0 {
3087 match self.consumer.recv_async().await {
3088 Err(e) => {
3089 return Err(Error::new(ErrorKind::Other, format!("Reduce result failed, reason: {:?}", e)));
3091 },
3092 Ok((index, result)) => {
3093 results.push((index, result));
3095 count -= 1;
3096 },
3097 }
3098 }
3099
3100 if order {
3101 results.sort_by_key(|(key, _value)| {
3103 key.clone()
3104 });
3105 }
3106 let (_, values) = results
3107 .into_iter()
3108 .unzip::<usize, Result<V>, Vec<usize>, Vec<Result<V>>>();
3109
3110 Ok(values)
3111 }
3112}
3113
3114pub enum AsyncPipelineResult<O: 'static> {
3118 Disconnect, Filtered(O), }
3121
3122pub fn spawn_worker_thread<F0, F1>(thread_name: &str,
3128 thread_stack_size: usize,
3129 thread_handler: Arc<AtomicBool>,
3130 thread_waker: Arc<(AtomicBool, Mutex<()>, Condvar)>, sleep_timeout: u64, loop_interval: Option<u64>, loop_func: F0,
3134 get_queue_len: F1) -> Arc<AtomicBool>
3135 where F0: Fn() -> (bool, Duration) + Send + 'static,
3136 F1: Fn() -> usize + Send + 'static {
3137 let thread_status_copy = thread_handler.clone();
3138
3139 thread::Builder::new()
3140 .name(thread_name.to_string())
3141 .stack_size(thread_stack_size).spawn(move || {
3142 let mut sleep_count = 0;
3143
3144 while thread_handler.load(Ordering::Relaxed) {
3145 let (is_no_task, run_time) = loop_func();
3146
3147 if is_no_task {
3148 if sleep_count > 1 {
3150 sleep_count = 0; let (is_sleep, lock, condvar) = &*thread_waker;
3153 if get_queue_len() > 0 {
3154 continue;
3156 }
3157
3158 {
3159 let _locked = lock.lock();
3160 if !is_sleep.load(Ordering::Acquire) {
3161 is_sleep.store(true, Ordering::Release);
3163 }
3164 }
3165
3166 if get_queue_len() > 0 {
3167 is_sleep.store(false, Ordering::Release);
3169 continue;
3170 }
3171
3172 let mut locked = lock.lock();
3173 if is_sleep.load(Ordering::Acquire) {
3174 let _ = condvar.wait_for(
3175 &mut locked,
3176 Duration::from_millis(sleep_timeout),
3177 );
3178 }
3179 is_sleep.store(false, Ordering::Release);
3180
3181 continue; }
3183
3184 sleep_count += 1; if let Some(interval) = &loop_interval {
3186 if let Some(remaining_interval) = Duration::from_millis(*interval).checked_sub(run_time){
3188 thread::sleep(remaining_interval);
3190 }
3191 }
3192 } else {
3193 sleep_count = 0; if let Some(interval) = &loop_interval {
3196 if let Some(remaining_interval) = Duration::from_millis(*interval).checked_sub(run_time){
3198 thread::sleep(remaining_interval);
3200 }
3201 }
3202 }
3203 }
3204 });
3205
3206 thread_status_copy
3207}
3208
3209pub fn wakeup_worker_thread<O: Default + 'static, P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P>>(worker_waker: &Arc<(AtomicBool, Mutex<()>, Condvar)>, rt: &SingleTaskRuntime<O, P>) {
3211 if worker_waker.0.load(Ordering::Relaxed) && rt.len() > 0 {
3213 let _ = wake_thread_waker(worker_waker);
3214 }
3215}
3216
3217pub fn register_global_panic_handler<Handler>(handler: Handler)
3219 where Handler: Fn(thread::Thread, String, Option<String>, Option<(String, u32, u32)>) -> Option<i32> + Send + Sync + 'static {
3220 set_hook(Box::new(move |panic_info| {
3221 let thread_info = thread::current();
3222
3223 let payload = panic_info.payload();
3224 let payload_info = match payload.downcast_ref::<&str>() {
3225 None => {
3226 match payload.downcast_ref::<String>() {
3228 None => {
3229 "Unknow panic".to_string()
3231 },
3232 Some(info) => {
3233 info.clone()
3234 }
3235 }
3236 },
3237 Some(info) => {
3238 info.to_string()
3239 }
3240 };
3241
3242 let other_info = if let Some(arg) = panic_info.payload_as_str() {
3243 Some(arg.to_string())
3244 } else {
3245 None
3246 };
3247
3248 let location = if let Some(location) = panic_info.location() {
3249 Some((location.file().to_string(), location.line(), location.column()))
3250 } else {
3251 None
3252 };
3253
3254 if let Some(exit_code) = handler(thread_info, payload_info, other_info, location) {
3255 std::process::exit(exit_code);
3257 }
3258 }));
3259}
3260
3261pub fn replace_global_alloc_error_handler() {
3263 set_alloc_error_hook(global_alloc_error_handle);
3264}
3265
3266fn global_alloc_error_handle(layout: Layout) {
3267 let bt = Backtrace::new();
3268 eprintln!("[UTC: {}][Thread: {}]Global memory allocation of {:?} bytes failed, stacktrace: \n{:?}",
3269 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_millis(),
3270 thread::current().name().unwrap_or(""),
3271 layout.size(),
3272 bt);
3273}
3274
3275pub(crate) struct YieldNow(bool);
3277
3278impl Future for YieldNow {
3279 type Output = ();
3280
3281 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
3282 if self.0 {
3283 Poll::Ready(())
3284 } else {
3285 self.0 = true;
3286 cx.waker().wake_by_ref();
3287 Poll::Pending
3288 }
3289 }
3290}