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
676pub struct AsyncTask<
680 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
681 O: Default + 'static = (),
682> {
683 uid: TaskId, future: Mutex<Option<BoxFuture<'static, O>>>, pool: Arc<P>, priority: usize, context: Option<UnsafeCell<Box<dyn Any>>>, }
689
690impl<
691 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
692 O: Default + 'static,
693> Drop for AsyncTask<P, O> {
694 fn drop(&mut self) {
695 let _ = unsafe { TaskHandle::<O>::from_raw((*self.uid.0.get() >> 64) as usize as *const ()) };
696 }
697}
698
699unsafe impl<
700 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
701 O: Default + 'static,
702> Send for AsyncTask<P, O> {}
703unsafe impl<
704 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
705 O: Default + 'static,
706> Sync for AsyncTask<P, O> {}
707
708impl<
709 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P>,
710 O: Default + 'static,
711> ArcWake for AsyncTask<P, O> {
712 fn wake_by_ref(arc_self: &Arc<Self>) {
713 let pool = arc_self.get_pool();
714 let _ = pool.push_keep(arc_self.clone());
715
716 if let Some(waits) = pool.get_waits() {
717 let _ = wake_waiting_worker(waits);
719 } else {
720 if let Some(thread_waker) = pool.get_thread_waker() {
722 let _ = wake_thread_waker(thread_waker);
723 }
724 }
725 }
726}
727
728impl<
729 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P>,
730 O: Default + 'static,
731> AsyncTask<P, O> {
732 pub fn new(uid: TaskId,
734 pool: Arc<P>,
735 priority: usize,
736 future: Option<BoxFuture<'static, O>>) -> AsyncTask<P, O> {
737 AsyncTask {
738 uid,
739 future: Mutex::new(future),
740 pool,
741 priority,
742 context: None,
743 }
744 }
745
746 pub fn with_context<C: 'static>(uid: TaskId,
748 pool: Arc<P>,
749 priority: usize,
750 future: Option<BoxFuture<'static, O>>,
751 context: C) -> AsyncTask<P, O> {
752 let any = Box::new(context);
753
754 AsyncTask {
755 uid,
756 future: Mutex::new(future),
757 pool,
758 priority,
759 context: Some(UnsafeCell::new(any)),
760 }
761 }
762
763 pub fn with_runtime_and_context<RT, C>(runtime: &RT,
765 priority: usize,
766 future: Option<BoxFuture<'static, O>>,
767 context: C) -> AsyncTask<P, O>
768 where RT: AsyncRuntime<O, Pool = P>,
769 C: Send + 'static {
770 let any = Box::new(context);
771
772 AsyncTask {
773 uid: runtime.alloc::<O>(),
774 future: Mutex::new(future),
775 pool: runtime.shared_pool(),
776 priority,
777 context: Some(UnsafeCell::new(any)),
778 }
779 }
780
781 pub fn is_enable_wakeup(&self) -> bool {
783 self.uid.exist_waker::<O>()
784 }
785
786 pub fn get_inner(&self) -> Option<BoxFuture<'static, O>> {
788 self.future.lock().take()
789 }
790
791 pub fn set_inner(&self, inner: Option<BoxFuture<'static, O>>) {
793 *self.future.lock() = inner;
794 }
795
796 #[inline]
798 pub fn owner(&self) -> usize {
799 unsafe {
800 *self.uid.0.get() as usize
801 }
802 }
803
804 #[inline]
806 pub fn priority(&self) -> usize {
807 self.priority
808 }
809
810 pub fn exist_context(&self) -> bool {
812 self.context.is_some()
813 }
814
815 pub fn get_context<C: Send + 'static>(&self) -> Option<&C> {
817 if let Some(context) = &self.context {
818 let any = unsafe { &*context.get() };
820 return <dyn Any>::downcast_ref::<C>(&**any);
821 }
822
823 None
824 }
825
826 pub fn get_context_mut<C: Send + 'static>(&self) -> Option<&mut C> {
828 if let Some(context) = &self.context {
829 let any = unsafe { &mut *context.get() };
831 return <dyn Any>::downcast_mut::<C>(&mut **any);
832 }
833
834 None
835 }
836
837 pub fn set_context<C: Send + 'static>(&self, new: C) {
839 if let Some(context) = &self.context {
840 let _ = unsafe { &*context.get() };
842
843 let any: Box<dyn Any + 'static> = Box::new(new);
845 unsafe { *context.get() = any; }
846 }
847 }
848
849 pub fn get_pool(&self) -> &P {
851 self.pool.as_ref()
852 }
853}
854
855pub trait AsyncTaskPool<O: Default + 'static = ()>: Default + Send + Sync + 'static {
859 type Pool: AsyncTaskPoolExt<O> + AsyncTaskPool<O>;
860
861 fn get_thread_id(&self) -> usize;
863
864 fn len(&self) -> usize;
866
867 fn push(&self, task: Arc<AsyncTask<Self::Pool, O>>) -> Result<()>;
869
870 fn push_local(&self, task: Arc<AsyncTask<Self::Pool, O>>) -> Result<()>;
872
873 fn push_priority(&self,
875 priority: usize,
876 task: Arc<AsyncTask<Self::Pool, O>>) -> Result<()>;
877
878 fn push_keep(&self, task: Arc<AsyncTask<Self::Pool, O>>) -> Result<()>;
880
881 fn try_pop(&self) -> Option<Arc<AsyncTask<Self::Pool, O>>>;
883
884 fn try_pop_all(&self) -> IntoIter<Arc<AsyncTask<Self::Pool, O>>>;
886
887 fn get_thread_waker(&self) -> Option<&Arc<(AtomicBool, Mutex<()>, Condvar)>>;
889}
890
891pub trait AsyncTaskPoolExt<O: Default + 'static = ()>: Send + Sync + 'static {
895 fn set_waits(&mut self,
897 _waits: Arc<ArrayQueue<Arc<(AtomicBool, Mutex<()>, Condvar)>>>) {}
898
899 fn get_waits(&self) -> Option<&Arc<ArrayQueue<Arc<(AtomicBool, Mutex<()>, Condvar)>>>> {
901 None
903 }
904
905 fn idler_len(&self) -> usize {
907 0
909 }
910
911 fn spawn_worker(&self) -> Option<usize> {
913 None
915 }
916
917 fn worker_len(&self) -> usize {
919 #[cfg(not(target_arch = "wasm32"))]
921 return num_cpus::get();
922 #[cfg(target_arch = "wasm32")]
923 return 1;
924 }
925
926 fn buffer_len(&self) -> usize {
928 0
930 }
931
932 fn set_thread_waker(&mut self, _thread_waker: Arc<(AtomicBool, Mutex<()>, Condvar)>) {
934 }
936
937 fn clone_thread_waker(&self) -> Option<Arc<(AtomicBool, Mutex<()>, Condvar)>> {
939 None
941 }
942
943 fn close_worker(&self) {
945 }
947}
948
949pub trait AsyncRuntime<O: Default + 'static = ()>: Clone + Send + Sync + 'static {
953 type Pool: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = Self::Pool>;
954
955 fn shared_pool(&self) -> Arc<Self::Pool>;
957
958 fn get_id(&self) -> usize;
960
961 fn wait_len(&self) -> usize;
963
964 fn len(&self) -> usize;
966
967 fn alloc<R: 'static>(&self) -> TaskId;
969
970 fn spawn<F>(&self, future: F) -> Result<TaskId>
972 where F: Future<Output = O> + Send + 'static;
973
974 fn spawn_local<F>(&self, future: F) -> Result<TaskId>
976 where F: Future<Output = O> + Send + 'static;
977
978 fn spawn_priority<F>(&self, priority: usize, future: F) -> Result<TaskId>
980 where F: Future<Output = O> + Send + 'static;
981
982 fn spawn_yield<F>(&self, future: F) -> Result<TaskId>
984 where F: Future<Output = O> + Send + 'static;
985
986 fn spawn_timing<F>(&self, future: F, time: usize) -> Result<TaskId>
988 where F: Future<Output = O> + Send + 'static;
989
990 fn spawn_by_id<F>(&self, task_id: TaskId, future: F) -> Result<()>
992 where F: Future<Output = O> + Send + 'static;
993
994 fn spawn_local_by_id<F>(&self, task_id: TaskId, future: F) -> Result<()>
996 where F: Future<Output = O> + Send + 'static;
997
998 fn spawn_priority_by_id<F>(&self,
1000 task_id: TaskId,
1001 priority: usize,
1002 future: F) -> Result<()>
1003 where F: Future<Output = O> + Send + 'static;
1004
1005 fn spawn_yield_by_id<F>(&self, task_id: TaskId, future: F) -> Result<()>
1007 where F: Future<Output = O> + Send + 'static;
1008
1009 fn spawn_timing_by_id<F>(&self,
1011 task_id: TaskId,
1012 future: F,
1013 time: usize) -> Result<()>
1014 where F: Future<Output = O> + Send + 'static;
1015
1016 fn pending<Output: 'static>(&self, task_id: &TaskId, waker: Waker) -> Poll<Output>;
1018
1019 fn wakeup<Output: 'static>(&self, task_id: &TaskId);
1021
1022 fn wait<V: Send + 'static>(&self) -> AsyncWait<V>;
1024
1025 fn wait_any<V: Send + 'static>(&self, capacity: usize) -> AsyncWaitAny<V>;
1027
1028 fn wait_any_callback<V: Send + 'static>(&self, capacity: usize) -> AsyncWaitAnyCallback<V>;
1030
1031 fn map_reduce<V: Send + 'static>(&self, capacity: usize) -> AsyncMapReduce<V>;
1033
1034 fn timeout(&self, timeout: usize) -> BoxFuture<'static, ()>;
1036
1037 fn yield_now(&self) -> BoxFuture<'static, ()>;
1039
1040 fn pipeline<S, SO, F, FO>(&self, input: S, filter: F) -> BoxStream<'static, FO>
1042 where S: Stream<Item = SO> + Send + 'static,
1043 SO: Send + 'static,
1044 F: FnMut(SO) -> AsyncPipelineResult<FO> + Send + 'static,
1045 FO: Send + 'static;
1046
1047 fn close(&self) -> bool;
1049}
1050
1051pub trait AsyncRuntimeExt<O: Default + 'static = ()> {
1055 fn spawn_with_context<F, C>(&self,
1057 task_id: TaskId,
1058 future: F,
1059 context: C) -> Result<()>
1060 where F: Future<Output = O> + Send + 'static,
1061 C: 'static;
1062
1063 fn spawn_timing_with_context<F, C>(&self,
1065 task_id: TaskId,
1066 future: F,
1067 context: C,
1068 time: usize) -> Result<()>
1069 where F: Future<Output = O> + Send + 'static,
1070 C: Send + 'static;
1071
1072 fn block_on<F>(&self, future: F) -> Result<F::Output>
1074 where F: Future + Send + 'static,
1075 <F as Future>::Output: Default + Send + 'static;
1076}
1077
1078pub struct AsyncRuntimeBuilder<O: Default + 'static = ()>(PhantomData<O>);
1082
1083impl<O: Default + 'static> AsyncRuntimeBuilder<O> {
1084 pub fn default_worker_thread(worker_name: Option<&str>,
1086 worker_stack_size: Option<usize>,
1087 worker_sleep_timeout: Option<u64>,
1088 worker_loop_interval: Option<Option<u64>>) -> WorkerRuntime<O> {
1089 let runner = WorkerTaskRunner::default();
1090
1091 let thread_name = if let Some(name) = worker_name {
1092 name
1093 } else {
1094 "Default-Single-Worker"
1096 };
1097 let thread_stack_size = if let Some(size) = worker_stack_size {
1098 size
1099 } else {
1100 2 * 1024 * 1024
1102 };
1103 let sleep_timeout = if let Some(timeout) = worker_sleep_timeout {
1104 timeout
1105 } else {
1106 1
1108 };
1109 let loop_interval = if let Some(interval) = worker_loop_interval {
1110 interval
1111 } else {
1112 None
1114 };
1115
1116 let clock = Clock::new();
1118 let runner_copy = runner.clone();
1119 let rt_copy = runner.get_runtime();
1120 let rt = runner.startup(
1121 thread_name,
1122 thread_stack_size,
1123 sleep_timeout,
1124 loop_interval,
1125 move || {
1126 let last = clock.recent();
1127 match runner_copy.run_once() {
1128 Err(e) => {
1129 panic!("Run runner failed, reason: {:?}", e);
1130 },
1131 Ok(len) => {
1132 (len == 0,
1133 clock
1134 .recent()
1135 .duration_since(last))
1136 },
1137 }
1138 },
1139 move || {
1140 rt_copy.wait_len() + rt_copy.len()
1141 },
1142 );
1143
1144 rt
1145 }
1146
1147 pub fn custom_worker_thread<P, F0, F1>(pool: P,
1149 worker_handle: Arc<AtomicBool>,
1150 worker_condvar: Arc<(AtomicBool, Mutex<()>, Condvar)>,
1151 thread_name: &str,
1152 thread_stack_size: usize,
1153 sleep_timeout: u64,
1154 loop_interval: Option<u64>,
1155 loop_func: F0,
1156 get_queue_len: F1) -> WorkerRuntime<O, P>
1157 where P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P>,
1158 F0: Fn() -> (bool, Duration) + Send + 'static,
1159 F1: Fn() -> usize + Send + 'static {
1160 let runner = WorkerTaskRunner::new(pool,
1161 worker_handle,
1162 worker_condvar);
1163
1164 let rt_copy = runner.get_runtime();
1166 let rt = runner.startup(
1167 thread_name,
1168 thread_stack_size,
1169 sleep_timeout,
1170 loop_interval,
1171 loop_func,
1172 move || {
1173 rt_copy.wait_len() + get_queue_len()
1174 },
1175 );
1176
1177 rt
1178 }
1179
1180 pub fn default_multi_thread(worker_prefix: Option<&str>,
1215 worker_stack_size: Option<usize>,
1216 worker_size: Option<usize>,
1217 worker_sleep_timeout: Option<u64>) -> MultiTaskRuntime<O> {
1218 let mut builder = if let Some(size) = worker_size.filter(|size| *size > 0) {
1219 let pool = StealableTaskPool::with(size,
1220 65535,
1221 [1, 1],
1222 3000);
1223 MultiTaskRuntimeBuilder::new(pool)
1224 .thread_stack_size(2 * 1024 * 1024)
1225 .set_timer_interval(1)
1226 } else {
1227 MultiTaskRuntimeBuilder::default()
1228 };
1229
1230 if let Some(size) = worker_size {
1231 builder = builder
1232 .init_worker_size(size)
1233 .set_worker_limit(size, size);
1234 }
1235 if let Some(thread_prefix) = worker_prefix {
1236 builder = builder.thread_prefix(thread_prefix);
1237 }
1238 if let Some(thread_stack_size) = worker_stack_size {
1239 builder = builder.thread_stack_size(thread_stack_size);
1240 }
1241 if let Some(sleep_timeout) = worker_sleep_timeout {
1242 builder = builder.set_timeout(sleep_timeout);
1243 }
1244
1245 builder.build()
1246 }
1247
1248 pub fn custom_multi_thread<P>(pool: P,
1250 worker_prefix: &str,
1251 worker_stack_size: usize,
1252 worker_size: usize,
1253 worker_sleep_timeout: u64,
1254 worker_timer_interval: usize) -> MultiTaskRuntime<O, P>
1255 where P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P> {
1256 MultiTaskRuntimeBuilder::new(pool)
1257 .thread_prefix(worker_prefix)
1258 .thread_stack_size(worker_stack_size)
1259 .init_worker_size(worker_size)
1260 .set_worker_limit(worker_size, worker_size)
1261 .set_timeout(worker_sleep_timeout)
1262 .set_timer_interval(worker_timer_interval)
1263 .build()
1264 }
1265}
1266
1267pub fn bind_local_thread<O: Default + 'static>(runtime: LocalAsyncRuntime<O>) {
1269 match PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME.try_with(move |rt| {
1270 let raw = Arc::into_raw(Arc::new(runtime)) as *mut LocalAsyncRuntime<O> as *mut ();
1271 rt.store(raw, Ordering::Relaxed);
1272 }) {
1273 Err(e) => {
1274 panic!("Bind single runtime to local thread failed, reason: {:?}", e);
1275 },
1276 Ok(_) => (),
1277 }
1278}
1279
1280pub fn unbind_local_thread() {
1282 let _ = PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME.try_with(move |rt| {
1283 rt.store(null_mut(), Ordering::Relaxed);
1284 });
1285}
1286
1287pub struct LocalAsyncRuntime<O: Default + 'static> {
1291 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, ()>, }
1298
1299unsafe impl<O: Default + 'static> Send for LocalAsyncRuntime<O> {}
1300unsafe impl<O: Default + 'static> Sync for LocalAsyncRuntime<O> {}
1301
1302impl<O: Default + 'static> LocalAsyncRuntime<O> {
1303 pub fn new(inner: *const (),
1305 get_id_func: fn(*const ()) -> usize,
1306 spawn_func: fn(*const (), BoxFuture<'static, O>) -> Result<()>,
1307 spawn_local_func: fn(*const (), BoxFuture<'static, O>) -> Result<()>,
1308 spawn_timing_func: fn(*const (), BoxFuture<'static, O>, usize) -> Result<()>,
1309 timeout_func: fn(*const (), usize) -> BoxFuture<'static, ()>) -> Self {
1310 LocalAsyncRuntime {
1311 inner,
1312 get_id_func,
1313 spawn_func,
1314 spawn_local_func,
1315 spawn_timing_func,
1316 timeout_func,
1317 }
1318 }
1319
1320 #[inline]
1322 pub fn get_id(&self) -> usize {
1323 (self.get_id_func)(self.inner)
1324 }
1325
1326 #[inline]
1328 pub fn spawn<F>(&self, future: F) -> Result<()>
1329 where F: Future<Output = O> + Send + 'static {
1330 (self.spawn_func)(self.inner, async move {
1331 future.await
1332 }.boxed())
1333 }
1334
1335 #[inline]
1337 pub fn spawn_local<F>(&self, future: F) -> Result<()>
1338 where F: Future<Output = O> + Send + 'static {
1339 (self.spawn_local_func)(self.inner, async move {
1340 future.await
1341 }.boxed())
1342 }
1343
1344 #[inline]
1346 pub fn sapwn_timing_func<F>(&self, future: F, timeout: usize) -> Result<()>
1347 where F: Future<Output = O> + Send + 'static {
1348 (self.spawn_timing_func)(self.inner,
1349 async move {
1350 future.await
1351 }.boxed(),
1352 timeout)
1353 }
1354
1355 #[inline]
1357 pub fn timeout(&self, timeout: usize) -> BoxFuture<'static, ()> {
1358 (self.timeout_func)(self.inner, timeout)
1359 }
1360}
1361
1362pub fn local_async_runtime<O: Default + 'static>() -> Option<Arc<LocalAsyncRuntime<O>>> {
1367 match PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME.try_with(move |ptr| {
1368 let raw = ptr.load(Ordering::Relaxed) as *const LocalAsyncRuntime<O>;
1369 unsafe {
1370 if raw.is_null() {
1371 None
1373 } else {
1374 let shared: Arc<LocalAsyncRuntime<O>> = unsafe { Arc::from_raw(raw) };
1376 let result = shared.clone();
1377 Arc::into_raw(shared); Some(result)
1379 }
1380 }
1381 }) {
1382 Err(_) => None, Ok(rt) => rt,
1384 }
1385}
1386
1387pub fn spawn_local<O, F>(future: F) -> Result<()>
1392 where O: Default + 'static,
1393 F: Future<Output = O> + Send + 'static {
1394 if let Some(rt) = local_async_runtime::<O>() {
1395 rt.spawn(future)
1396 } else {
1397 Err(Error::new(ErrorKind::Other, format!("Spawn task to local thread failed, reason: runtime not exist")))
1398 }
1399}
1400
1401pub fn get_local_dict<T: 'static>() -> Option<&'static T> {
1405 match PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME_DICT.try_with(move |dict| {
1406 unsafe {
1407 if let Some(any) = (&*dict.get()).get(&TypeId::of::<T>()) {
1408 <dyn Any>::downcast_ref::<T>(&**any)
1410 } else {
1411 None
1413 }
1414 }
1415 }) {
1416 Err(_) => {
1417 None
1418 },
1419 Ok(result) => {
1420 result
1421 }
1422 }
1423}
1424
1425pub fn get_local_dict_mut<T: 'static>() -> Option<&'static mut T> {
1429 match PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME_DICT.try_with(move |dict| {
1430 unsafe {
1431 if let Some(any) = (&mut *dict.get()).get_mut(&TypeId::of::<T>()) {
1432 <dyn Any>::downcast_mut::<T>(&mut **any)
1434 } else {
1435 None
1437 }
1438 }
1439 }) {
1440 Err(_) => {
1441 None
1442 },
1443 Ok(result) => {
1444 result
1445 }
1446 }
1447}
1448
1449pub fn set_local_dict<T: 'static>(value: T) -> Option<T> {
1453 match PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME_DICT.try_with(move |dict| {
1454 unsafe {
1455 let result = if let Some(any) = (&mut *dict.get()).remove(&TypeId::of::<T>()) {
1456 if let Ok(r) = any.downcast() {
1458 Some(*r)
1460 } else {
1461 None
1462 }
1463 } else {
1464 None
1466 };
1467
1468 (&mut *dict.get()).insert(TypeId::of::<T>(), Box::new(value) as Box<dyn Any>);
1470
1471 result
1472 }
1473 }) {
1474 Err(_) => {
1475 None
1476 },
1477 Ok(result) => {
1478 result
1479 }
1480 }
1481}
1482
1483pub fn remove_local_dict<T: 'static>() -> Option<T> {
1487 match PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME_DICT.try_with(move |dict| {
1488 unsafe {
1489 if let Some(any) = (&mut *dict.get()).remove(&TypeId::of::<T>()) {
1490 if let Ok(r) = any.downcast() {
1492 Some(*r)
1494 } else {
1495 None
1496 }
1497 } else {
1498 None
1500 }
1501 }
1502 }) {
1503 Err(_) => {
1504 None
1505 },
1506 Ok(result) => {
1507 result
1508 }
1509 }
1510}
1511
1512pub fn clear_local_dict() -> Result<()> {
1516 match PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME_DICT.try_with(move |dict| {
1517 unsafe {
1518 (&mut *dict.get()).clear();
1519 }
1520 }) {
1521 Err(e) => {
1522 Err(Error::new(ErrorKind::Other, format!("Clear local dict failed, reason: {:?}", e)))
1523 },
1524 Ok(_) => {
1525 Ok(())
1526 }
1527 }
1528}
1529
1530pub struct AsyncValue<V: Send + 'static>(Arc<InnerAsyncValue<V>>);
1534
1535unsafe impl<V: Send + 'static> Send for AsyncValue<V> {}
1536unsafe impl<V: Send + 'static> Sync for AsyncValue<V> {}
1537
1538impl<V: Send + 'static> Clone for AsyncValue<V> {
1539 fn clone(&self) -> Self {
1540 AsyncValue(self.0.clone())
1541 }
1542}
1543
1544impl<V: Send + 'static> Debug for AsyncValue<V> {
1545 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
1546 write!(f,
1547 "AsyncValue[status = {}]",
1548 self.0.status.load(Ordering::Acquire))
1549 }
1550}
1551
1552impl<V: Send + 'static> Future for AsyncValue<V> {
1553 type Output = V;
1554
1555 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1556 let mut spin_len = 1;
1557 while self.0.status.load(Ordering::Acquire) == 2 {
1558 spin_len = spin(spin_len);
1560 }
1561
1562 if self.0.status.load(Ordering::Acquire) == 3 {
1563 if let Some(value) = unsafe { (*(&self).0.value.get()).take() } {
1564 return Poll::Ready(value);
1566 }
1567 }
1568
1569 unsafe {
1570 *self.0.waker.get() = Some(cx.waker().clone()); }
1572
1573 let mut spin_len = 1;
1574 loop {
1575 match self.0.status.compare_exchange(0,
1576 1, Ordering::Acquire,
1577 Ordering::Relaxed) {
1578 Err(2) => {
1579 spin_len = spin(spin_len);
1581 continue;
1582 },
1583 Err(3) => {
1584 let value = unsafe { (*(&self).0.value.get()).take().unwrap() };
1586 return Poll::Ready(value);
1587 },
1588 Err(_) => {
1589 unimplemented!();
1590 },
1591 Ok(_) => {
1592 return Poll::Pending;
1594 },
1595 }
1596 }
1597 }
1598}
1599
1600impl<V: Send + 'static> AsyncValue<V> {
1604 pub fn new() -> Self {
1606 let inner = InnerAsyncValue {
1607 value: UnsafeCell::new(None),
1608 waker: UnsafeCell::new(None),
1609 status: AtomicU8::new(0),
1610 };
1611
1612 AsyncValue(Arc::new(inner))
1613 }
1614
1615 pub fn is_complete(&self) -> bool {
1617 self
1618 .0
1619 .status
1620 .load(Ordering::Relaxed) == 3
1621 }
1622
1623 pub fn set(self, value: V) {
1625 loop {
1626 match self.0.status.compare_exchange(1,
1627 2,
1628 Ordering::Acquire,
1629 Ordering::Relaxed) {
1630 Err(0) => {
1631 match self.0.status.compare_exchange(0,
1632 2,
1633 Ordering::Acquire,
1634 Ordering::Relaxed) {
1635 Err(1) => {
1636 continue;
1638 },
1639 Err(_) => {
1640 return;
1642 },
1643 Ok(_) => {
1644 unsafe { *self.0.value.get() = Some(value); }
1646 self.0.status.store(3, Ordering::Release);
1647 return;
1648 }
1649 }
1650 },
1651 Err(_) => {
1652 return;
1654 },
1655 Ok(_) => {
1656 break;
1658 }
1659 }
1660 }
1661
1662 unsafe { *self.0.value.get() = Some(value); }
1664 self.0.status.store(3, Ordering::Release);
1665 let waker = unsafe { (*self.0.waker.get()).take().unwrap() };
1666 waker.wake();
1667 }
1668}
1669
1670pub struct InnerAsyncValue<V: Send + 'static> {
1672 value: UnsafeCell<Option<V>>, waker: UnsafeCell<Option<Waker>>, status: AtomicU8, }
1676
1677pub struct AsyncVariableGuard<'a, V: Send + 'static> {
1681 value: &'a UnsafeCell<Option<V>>, waker: &'a UnsafeCell<Option<Waker>>, status: &'a AtomicU8, }
1685
1686unsafe impl<V: Send + 'static> Send for AsyncVariableGuard<'_, V> {}
1687
1688impl<V: Send + 'static> Drop for AsyncVariableGuard<'_, V> {
1689 fn drop(&mut self) {
1690 self.status.fetch_sub(2, Ordering::Relaxed);
1694 }
1695}
1696
1697impl<V: Send + 'static> Deref for AsyncVariableGuard<'_, V> {
1698 type Target = Option<V>;
1699
1700 fn deref(&self) -> &Self::Target {
1701 unsafe {
1702 &*self.value.get()
1703 }
1704 }
1705}
1706
1707impl<V: Send + 'static> DerefMut for AsyncVariableGuard<'_, V> {
1708 fn deref_mut(&mut self) -> &mut Self::Target {
1709 unsafe {
1710 &mut *self.value.get()
1711 }
1712 }
1713}
1714
1715impl<V: Send + 'static> AsyncVariableGuard<'_, V> {
1716 pub fn finish(self) {
1718 if self.status.fetch_add(4, Ordering::Relaxed) == 3 {
1720 if let Some(waker) = unsafe { (&mut *self.waker.get()).take() } {
1721 waker.wake();
1723 }
1724 }
1725 }
1726}
1727
1728pub struct AsyncVariable<V: Send + 'static>(Arc<InnerAsyncVariable<V>>);
1732
1733unsafe impl<V: Send + 'static> Send for AsyncVariable<V> {}
1734unsafe impl<V: Send + 'static> Sync for AsyncVariable<V> {}
1735
1736impl<V: Send + 'static> Clone for AsyncVariable<V> {
1737 fn clone(&self) -> Self {
1738 AsyncVariable(self.0.clone())
1739 }
1740}
1741
1742impl<V: Send + 'static> Future for AsyncVariable<V> {
1743 type Output = V;
1744
1745 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1746 unsafe {
1747 *self.0.waker.get() = Some(cx.waker().clone()); }
1749
1750 let mut spin_len = 1;
1751 loop {
1752 match self.0.status.compare_exchange(0,
1753 1,
1754 Ordering::Acquire,
1755 Ordering::Relaxed) {
1756 Err(current) if current & 4 != 0 => {
1757 unsafe {
1759 let _ = (&mut *self.0.waker.get()).take(); return Poll::Ready((&mut *(&self).0.value.get()).take().unwrap());
1761 }
1762 },
1763 Err(_) => {
1764 spin_len = spin(spin_len);
1766 },
1767 Ok(_) => {
1768 return Poll::Pending;
1770 },
1771 }
1772 }
1773 }
1774}
1775
1776impl<V: Send + 'static> AsyncVariable<V> {
1777 pub fn new() -> Self {
1779 let inner = InnerAsyncVariable {
1780 value: UnsafeCell::new(None),
1781 waker: UnsafeCell::new(None),
1782 status: AtomicU8::new(0),
1783 };
1784
1785 AsyncVariable(Arc::new(inner))
1786 }
1787
1788 pub fn is_complete(&self) -> bool {
1790 self
1791 .0
1792 .status
1793 .load(Ordering::Acquire) & 4 != 0
1794 }
1795
1796 pub fn lock(&self) -> Option<AsyncVariableGuard<V>> {
1798 let mut spin_len = 1;
1799 loop {
1800 match self
1801 .0
1802 .status
1803 .compare_exchange(1,
1804 3,
1805 Ordering::Acquire,
1806 Ordering::Relaxed) {
1807 Err(0) => {
1808 match self
1810 .0
1811 .status
1812 .compare_exchange(0,
1813 2,
1814 Ordering::Acquire,
1815 Ordering::Relaxed) {
1816 Err(1) => {
1817 continue;
1819 },
1820 Err(2) => {
1821 spin_len = spin(spin_len);
1823 },
1824 Err(3) => {
1825 spin_len = spin(spin_len);
1827 },
1828 Err(_) => {
1829 return None;
1831 },
1832 Ok(_) => {
1833 let guard = AsyncVariableGuard {
1835 value: &self.0.value,
1836 waker: &self.0.waker,
1837 status: &self.0.status,
1838 };
1839
1840 return Some(guard)
1841 },
1842 }
1843 },
1844 Err(2) => {
1845 spin_len = spin(spin_len);
1847 },
1848 Err(3) => {
1849 spin_len = spin(spin_len);
1851 },
1852 Err(_) => {
1853 return None;
1855 }
1856 Ok(_) => {
1857 let guard = AsyncVariableGuard {
1859 value: &self.0.value,
1860 waker: &self.0.waker,
1861 status: &self.0.status,
1862 };
1863
1864 return Some(guard)
1865 },
1866 }
1867 }
1868 }
1869}
1870
1871pub struct InnerAsyncVariable<V: Send + 'static> {
1873 value: UnsafeCell<Option<V>>, waker: UnsafeCell<Option<Waker>>, status: AtomicU8, }
1877
1878pub struct AsyncWaitResult<V: Send + 'static>(pub Arc<RefCell<Option<Result<V>>>>);
1882
1883unsafe impl<V: Send + 'static> Send for AsyncWaitResult<V> {}
1884unsafe impl<V: Send + 'static> Sync for AsyncWaitResult<V> {}
1885
1886impl<V: Send + 'static> Clone for AsyncWaitResult<V> {
1887 fn clone(&self) -> Self {
1888 AsyncWaitResult(self.0.clone())
1889 }
1890}
1891
1892pub struct AsyncWaitResults<V: Send + 'static>(pub Arc<RefCell<Option<Vec<Result<V>>>>>);
1896
1897unsafe impl<V: Send + 'static> Send for AsyncWaitResults<V> {}
1898unsafe impl<V: Send + 'static> Sync for AsyncWaitResults<V> {}
1899
1900impl<V: Send + 'static> Clone for AsyncWaitResults<V> {
1901 fn clone(&self) -> Self {
1902 AsyncWaitResults(self.0.clone())
1903 }
1904}
1905
1906pub enum AsyncTimingTask<
1910 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1911 O: Default + 'static = (),
1912> {
1913 Pended(TaskId), WaitRun(Arc<AsyncTask<P, O>>), TimeoutWake(Arc<TimeoutWaiter>), }
1917
1918pub struct AsyncTaskTimer<
1922 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1923 O: Default + 'static = (),
1924> {
1925 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, }
1931
1932unsafe impl<
1933 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1934 O: Default + 'static,
1935> Send for AsyncTaskTimer<P, O> {}
1936unsafe impl<
1937 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1938 O: Default + 'static,
1939> Sync for AsyncTaskTimer<P, O> {}
1940
1941impl<
1942 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1943 O: Default + 'static,
1944> AsyncTaskTimer<P, O> {
1945 pub fn new() -> Self {
1947 let (producor, consumer) = unbounded();
1948 let clock = Clock::new();
1949 let now = clock.recent();
1950
1951 AsyncTaskTimer {
1952 producor,
1953 consumer,
1954 timer: Arc::new(RefCell::new(Timer::<AsyncTimingTask<P, O>, 1000, 60, 3>::default())),
1955 clock,
1956 now,
1957 }
1958 }
1959
1960 #[inline]
1962 pub fn get_producor(&self) -> &Sender<(usize, AsyncTimingTask<P, O>)> {
1963 &self.producor
1964 }
1965
1966 #[inline]
1968 pub fn len(&self) -> usize {
1969 let timer = self.timer.as_ref().borrow();
1970 timer.add_count() - timer.remove_count()
1971 }
1972
1973 pub fn set_timer(&self, task: AsyncTimingTask<P, O>, timeout: usize) -> usize {
1975 let current_time = self
1976 .clock
1977 .recent()
1978 .duration_since(self.now)
1979 .as_millis() as u64;
1980 self
1981 .timer
1982 .borrow_mut()
1983 .push_time(current_time + timeout as u64, task)
1984 .data()
1985 .as_ffi() as usize
1986 }
1987
1988 pub fn cancel_timer(&self, timer_ref: usize) -> Option<AsyncTimingTask<P, O>> {
1990 if let Some(item) = self
1991 .timer
1992 .borrow_mut()
1993 .cancel(KeyData::from_ffi(timer_ref as u64).into()) {
1994 Some(item)
1995 } else {
1996 None
1997 }
1998 }
1999
2000 pub fn consume(&self) -> usize {
2002 let timer_tasks = self.consumer.try_iter().collect::<Vec<(usize, AsyncTimingTask<P, O>)>>();
2003 let len = timer_tasks.len();
2004 for (timeout, task) in timer_tasks {
2005 self.set_timer(task, timeout);
2006 }
2007
2008 len
2009 }
2010
2011 pub fn is_require_pop(&self) -> Option<u64> {
2013 let current_time = self
2014 .clock
2015 .recent()
2016 .duration_since(self.now)
2017 .as_millis() as u64;
2018 if self.timer.borrow_mut().is_ok(current_time) {
2019 Some(current_time)
2020 } else {
2021 None
2022 }
2023 }
2024
2025 pub fn pop(&self, current_time: u64) -> Option<(usize, AsyncTimingTask<P, O>)> {
2027 if let Some((key, item)) = self.timer.borrow_mut().pop_kv(current_time) {
2028 Some((key.data().as_ffi() as usize, item))
2029 } else {
2030 None
2031 }
2032 }
2033}
2034
2035pub struct AsyncTaskTimerByNotCancel<
2039 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2040 O: Default + 'static = (),
2041> {
2042 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, }
2048
2049unsafe impl<
2050 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2051 O: Default + 'static,
2052> Send for AsyncTaskTimerByNotCancel<P, O> {}
2053unsafe impl<
2054 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2055 O: Default + 'static,
2056> Sync for AsyncTaskTimerByNotCancel<P, O> {}
2057
2058impl<
2059 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2060 O: Default + 'static,
2061> AsyncTaskTimerByNotCancel<P, O> {
2062 pub fn new() -> Self {
2064 let (producor, consumer) = unbounded();
2065 let clock = Clock::new();
2066 let now = clock.recent();
2067
2068 AsyncTaskTimerByNotCancel {
2069 producor,
2070 consumer,
2071 timer: Arc::new(RefCell::new(NotCancelTimer::<AsyncTimingTask<P, O>, 1000, 60, 3>::default())),
2072 clock,
2073 now,
2074 }
2075 }
2076
2077 #[inline]
2079 pub fn get_producor(&self) -> &Sender<(usize, AsyncTimingTask<P, O>)> {
2080 &self.producor
2081 }
2082
2083 #[inline]
2085 pub fn len(&self) -> usize {
2086 let timer = self.timer.as_ref().borrow();
2087 timer.add_count() - timer.remove_count()
2088 }
2089
2090 pub fn set_timer(&self, task: AsyncTimingTask<P, O>, timeout: usize) {
2092 self
2093 .timer
2094 .borrow_mut()
2095 .push(timeout, task);
2096 }
2097
2098 pub fn consume(&self) -> usize {
2100 let timer_tasks = self.consumer.try_iter().collect::<Vec<(usize, AsyncTimingTask<P, O>)>>();
2101 let len = timer_tasks.len();
2102 for (timeout, task) in timer_tasks {
2103 self.set_timer(task, timeout);
2104 }
2105
2106 len
2107 }
2108
2109 pub fn is_require_pop(&self) -> Option<u64> {
2111 let current_time = self
2112 .clock
2113 .recent()
2114 .duration_since(self.now)
2115 .as_millis() as u64;
2116 if self.timer.borrow_mut().is_ok(current_time) {
2117 Some(current_time)
2118 } else {
2119 None
2120 }
2121 }
2122
2123 pub fn pop(&self, current_time: u64) -> Option<AsyncTimingTask<P, O>> {
2125 if let Some(item) = self.timer.borrow_mut().pop(current_time) {
2126 Some(item)
2127 } else {
2128 None
2129 }
2130 }
2131}
2132
2133pub struct AsyncWaitTimeout<
2137 RT: AsyncRuntime<O>,
2138 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2139 O: Default + 'static = (),
2140> {
2141 rt: RT, producor: Sender<(usize, AsyncTimingTask<P, O>)>, timeout: usize, registered: AtomicBool, waiter: Arc<TimeoutWaiter>, }
2147
2148unsafe impl<
2149 RT: AsyncRuntime<O>,
2150 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2151 O: Default + 'static,
2152> Send for AsyncWaitTimeout<RT, P, O> {}
2153unsafe impl<
2154 RT: AsyncRuntime<O>,
2155 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2156 O: Default + 'static,
2157> Sync for AsyncWaitTimeout<RT, P, O> {}
2158
2159impl<
2160 RT: AsyncRuntime<O>,
2161 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2162 O: Default + 'static,
2163> Future for AsyncWaitTimeout<RT, P, O> {
2164 type Output = ();
2165
2166 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2167 if self.waiter.is_fired() {
2168 return Poll::Ready(());
2170 }
2171
2172 self.waiter.register(cx.waker());
2173
2174 if !self.registered.swap(true, Ordering::AcqRel) {
2175 let _ = self
2177 .producor
2178 .send((self.timeout, AsyncTimingTask::TimeoutWake(self.waiter.clone())));
2179 }
2180
2181 if self.waiter.is_fired() {
2182 Poll::Ready(())
2183 } else {
2184 Poll::Pending
2185 }
2186 }
2187}
2188
2189impl<
2190 RT: AsyncRuntime<O>,
2191 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2192 O: Default + 'static,
2193> Drop for AsyncWaitTimeout<RT, P, O> {
2194 fn drop(&mut self) {
2195 self.waiter.clear_waker();
2196 }
2197}
2198
2199impl<
2200 RT: AsyncRuntime<O>,
2201 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2202 O: Default + 'static,
2203> AsyncWaitTimeout<RT, P, O> {
2204 pub fn new(rt: RT,
2206 producor: Sender<(usize, AsyncTimingTask<P, O>)>,
2207 timeout: usize) -> Self {
2208 AsyncWaitTimeout {
2209 rt,
2210 producor,
2211 timeout,
2212 registered: AtomicBool::new(false), waiter: Arc::new(TimeoutWaiter::new()),
2214 }
2215 }
2216}
2217
2218pub struct LocalAsyncWaitTimeout<
2222 RT: AsyncRuntime<O>,
2223 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2224 O: Default + 'static = (),
2225> {
2226 rt: RT, timer: Arc<AsyncTaskTimerByNotCancel<P, O>>, timeout: usize, registered: AtomicBool, waiter: Arc<TimeoutWaiter>, }
2232
2233unsafe impl<
2234 RT: AsyncRuntime<O>,
2235 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2236 O: Default + 'static,
2237> Send for LocalAsyncWaitTimeout<RT, P, O> {}
2238unsafe impl<
2239 RT: AsyncRuntime<O>,
2240 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2241 O: Default + 'static,
2242> Sync for LocalAsyncWaitTimeout<RT, P, O> {}
2243
2244impl<
2245 RT: AsyncRuntime<O>,
2246 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2247 O: Default + 'static,
2248> Future for LocalAsyncWaitTimeout<RT, P, O> {
2249 type Output = ();
2250
2251 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2252 if self.waiter.is_fired() {
2253 return Poll::Ready(());
2255 }
2256
2257 self.waiter.register(cx.waker());
2258
2259 if !self.registered.swap(true, Ordering::AcqRel) {
2260 self
2262 .timer
2263 .set_timer(AsyncTimingTask::TimeoutWake(self.waiter.clone()),
2264 self.timeout);
2265 }
2266
2267 if self.waiter.is_fired() {
2268 Poll::Ready(())
2269 } else {
2270 Poll::Pending
2271 }
2272 }
2273}
2274
2275impl<
2276 RT: AsyncRuntime<O>,
2277 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2278 O: Default + 'static,
2279> Drop for LocalAsyncWaitTimeout<RT, P, O> {
2280 fn drop(&mut self) {
2281 self.waiter.clear_waker();
2282 }
2283}
2284
2285impl<
2286 RT: AsyncRuntime<O>,
2287 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
2288 O: Default + 'static,
2289> LocalAsyncWaitTimeout<RT, P, O> {
2290 pub fn new(rt: RT,
2292 timer: Arc<AsyncTaskTimerByNotCancel<P, O>>,
2293 timeout: usize) -> Self {
2294 LocalAsyncWaitTimeout {
2295 rt,
2296 timer,
2297 timeout,
2298 registered: AtomicBool::new(false), waiter: Arc::new(TimeoutWaiter::new()),
2300 }
2301 }
2302}
2303
2304pub struct AsyncWait<V: Send + 'static>(AsyncWaitAny<V>);
2308
2309unsafe impl<V: Send + 'static> Send for AsyncWait<V> {}
2310unsafe impl<V: Send + 'static> Sync for AsyncWait<V> {}
2311
2312impl<V: Send + 'static> AsyncWait<V> {
2316 pub fn spawn<RT, O, F>(&self,
2318 rt: RT,
2319 timeout: Option<usize>,
2320 future: F) -> Result<()>
2321 where RT: AsyncRuntime<O>,
2322 O: Default + 'static,
2323 F: Future<Output = Result<V>> + Send + 'static {
2324 self.0.spawn(rt.clone(), future)?;
2325
2326 if let Some(timeout) = timeout {
2327 let rt_copy = rt.clone();
2329 self.0.spawn(rt, async move {
2330 rt_copy.timeout(timeout).await;
2331
2332 Err(Error::new(ErrorKind::TimedOut, format!("Time out")))
2334 })
2335 } else {
2336 Ok(())
2338 }
2339 }
2340
2341 pub fn spawn_local<O, F>(&self,
2343 timeout: Option<usize>,
2344 future: F) -> Result<()>
2345 where O: Default + 'static,
2346 F: Future<Output = Result<V>> + Send + 'static {
2347 if let Some(rt) = local_async_runtime::<O>() {
2348 self.0.spawn_local(future)?;
2350
2351 if let Some(timeout) = timeout {
2352 let rt_copy = rt.clone();
2354 self.0.spawn_local(async move {
2355 rt_copy.timeout(timeout).await;
2356
2357 Err(Error::new(ErrorKind::TimedOut, format!("Time out")))
2359 })
2360 } else {
2361 Ok(())
2363 }
2364 } else {
2365 Err(Error::new(ErrorKind::Other, format!("Spawn wait task failed, reason: local async runtime not exist")))
2367 }
2368 }
2369}
2370
2371impl<V: Send + 'static> AsyncWait<V> {
2375 pub async fn wait_result(self) -> Result<V> {
2377 self.0.wait_result().await
2378 }
2379}
2380
2381pub struct AsyncWaitAny<V: Send + 'static> {
2385 capacity: usize, producor: AsyncSender<Result<V>>, consumer: AsyncReceiver<Result<V>>, }
2389
2390unsafe impl<V: Send + 'static> Send for AsyncWaitAny<V> {}
2391unsafe impl<V: Send + 'static> Sync for AsyncWaitAny<V> {}
2392
2393impl<V: Send + 'static> AsyncWaitAny<V> {
2397 pub fn spawn<RT, O, F>(&self,
2399 rt: RT,
2400 future: F) -> Result<()>
2401 where RT: AsyncRuntime<O>,
2402 O: Default + 'static,
2403 F: Future<Output = Result<V>> + Send + 'static {
2404 let producor = self.producor.clone();
2405 rt.spawn_by_id(rt.alloc::<O>(), async move {
2406 let value = future.await;
2407 producor.into_send_async(value).await;
2408
2409 Default::default()
2411 })
2412 }
2413
2414 pub fn spawn_local<F>(&self,
2416 future: F) -> Result<()>
2417 where F: Future<Output = Result<V>> + Send + 'static {
2418 if let Some(rt) = local_async_runtime() {
2419 let producor = self.producor.clone();
2421 rt.spawn(async move {
2422 let value = future.await;
2423 producor.into_send_async(value).await;
2424 })
2425 } else {
2426 Err(Error::new(ErrorKind::Other, format!("Spawn wait any task failed, reason: local async runtime not exist")))
2428 }
2429 }
2430}
2431
2432impl<V: Send + 'static> AsyncWaitAny<V> {
2436 pub async fn wait_result(self) -> Result<V> {
2438 match self.consumer.recv_async().await {
2439 Err(e) => {
2440 Err(Error::new(ErrorKind::Other, format!("Wait any result failed, reason: {:?}", e)))
2442 },
2443 Ok(result) => {
2444 result
2446 },
2447 }
2448 }
2449}
2450
2451pub struct AsyncWaitAnyCallback<V: Send + 'static> {
2455 capacity: usize, producor: AsyncSender<Result<V>>, consumer: AsyncReceiver<Result<V>>, }
2459
2460unsafe impl<V: Send + 'static> Send for AsyncWaitAnyCallback<V> {}
2461unsafe impl<V: Send + 'static> Sync for AsyncWaitAnyCallback<V> {}
2462
2463impl<V: Send + 'static> AsyncWaitAnyCallback<V> {
2467 pub fn spawn<RT, O, F>(&self,
2469 rt: RT,
2470 future: F) -> Result<()>
2471 where RT: AsyncRuntime<O>,
2472 O: Default + 'static,
2473 F: Future<Output = Result<V>> + Send + 'static {
2474 let producor = self.producor.clone();
2475 rt.spawn_by_id(rt.alloc::<O>(), async move {
2476 let value = future.await;
2477 producor.into_send_async(value).await;
2478
2479 Default::default()
2481 })
2482 }
2483
2484 pub fn spawn_local<F>(&self,
2486 future: F) -> Result<()>
2487 where F: Future<Output = Result<V>> + Send + 'static {
2488 if let Some(rt) = local_async_runtime() {
2489 let producor = self.producor.clone();
2491 rt.spawn(async move {
2492 let value = future.await;
2493 producor.into_send_async(value).await;
2494 })
2495 } else {
2496 Err(Error::new(ErrorKind::Other, format!("Spawn wait any task failed by callback, reason: current async runtime not exist")))
2498 }
2499 }
2500}
2501
2502impl<V: Send + 'static> AsyncWaitAnyCallback<V> {
2506 pub async fn wait_result(mut self,
2508 callback: impl Fn(&Result<V>) -> bool + Send + Sync + 'static) -> Result<V> {
2509 let checker = create_checker(self.capacity, callback);
2510 loop {
2511 match self.consumer.recv_async().await {
2512 Err(e) => {
2513 return Err(Error::new(ErrorKind::Other, format!("Wait any result failed by callback, reason: {:?}", e)));
2515 },
2516 Ok(result) => {
2517 if checker(&result) {
2519 return result;
2521 }
2522 },
2523 }
2524 }
2525 }
2526}
2527
2528fn create_checker<V, F>(len: usize,
2530 callback: F) -> Arc<dyn Fn(&Result<V>) -> bool + Send + Sync + 'static>
2531 where V: Send + 'static,
2532 F: Fn(&Result<V>) -> bool + Send + Sync + 'static {
2533 let mut check_counter = AtomicUsize::new(len); Arc::new(move |result| {
2535 if check_counter.fetch_sub(1, Ordering::SeqCst) == 1 {
2536 true
2538 } else {
2539 callback(result)
2541 }
2542 })
2543}
2544
2545pub struct AsyncMapReduce<V: Send + 'static> {
2549 count: usize, capacity: usize, producor: AsyncSender<(usize, Result<V>)>, consumer: AsyncReceiver<(usize, Result<V>)>, }
2554
2555unsafe impl<V: Send + 'static> Send for AsyncMapReduce<V> {}
2556
2557impl<V: Send + 'static> AsyncMapReduce<V> {
2561 pub fn map<RT, O, F>(&mut self, rt: RT, future: F) -> Result<usize>
2563 where RT: AsyncRuntime<O>,
2564 O: Default + 'static,
2565 F: Future<Output = Result<V>> + Send + 'static {
2566 if self.count >= self.capacity {
2567 return Err(Error::new(ErrorKind::Other, format!("Map task to runtime failed, capacity: {}, reason: out of capacity", self.capacity)));
2569 }
2570
2571 let index = self.count;
2572 let producor = self.producor.clone();
2573 rt.spawn_by_id(rt.alloc::<O>(), async move {
2574 let value = future.await;
2575 producor.into_send_async((index, value)).await;
2576
2577 Default::default()
2579 })?;
2580
2581 self.count += 1; Ok(index)
2583 }
2584}
2585
2586impl<V: Send + 'static> AsyncMapReduce<V> {
2590 pub async fn reduce(self, order: bool) -> Result<Vec<Result<V>>> {
2592 let mut count = self.count;
2593 let mut results = Vec::with_capacity(count);
2594 while count > 0 {
2595 match self.consumer.recv_async().await {
2596 Err(e) => {
2597 return Err(Error::new(ErrorKind::Other, format!("Reduce result failed, reason: {:?}", e)));
2599 },
2600 Ok((index, result)) => {
2601 results.push((index, result));
2603 count -= 1;
2604 },
2605 }
2606 }
2607
2608 if order {
2609 results.sort_by_key(|(key, _value)| {
2611 key.clone()
2612 });
2613 }
2614 let (_, values) = results
2615 .into_iter()
2616 .unzip::<usize, Result<V>, Vec<usize>, Vec<Result<V>>>();
2617
2618 Ok(values)
2619 }
2620}
2621
2622pub enum AsyncPipelineResult<O: 'static> {
2626 Disconnect, Filtered(O), }
2629
2630pub fn spawn_worker_thread<F0, F1>(thread_name: &str,
2636 thread_stack_size: usize,
2637 thread_handler: Arc<AtomicBool>,
2638 thread_waker: Arc<(AtomicBool, Mutex<()>, Condvar)>, sleep_timeout: u64, loop_interval: Option<u64>, loop_func: F0,
2642 get_queue_len: F1) -> Arc<AtomicBool>
2643 where F0: Fn() -> (bool, Duration) + Send + 'static,
2644 F1: Fn() -> usize + Send + 'static {
2645 let thread_status_copy = thread_handler.clone();
2646
2647 thread::Builder::new()
2648 .name(thread_name.to_string())
2649 .stack_size(thread_stack_size).spawn(move || {
2650 let mut sleep_count = 0;
2651
2652 while thread_handler.load(Ordering::Relaxed) {
2653 let (is_no_task, run_time) = loop_func();
2654
2655 if is_no_task {
2656 if sleep_count > 1 {
2658 sleep_count = 0; let (is_sleep, lock, condvar) = &*thread_waker;
2661 if get_queue_len() > 0 {
2662 continue;
2664 }
2665
2666 {
2667 let _locked = lock.lock();
2668 if !is_sleep.load(Ordering::Acquire) {
2669 is_sleep.store(true, Ordering::Release);
2671 }
2672 }
2673
2674 if get_queue_len() > 0 {
2675 is_sleep.store(false, Ordering::Release);
2677 continue;
2678 }
2679
2680 let mut locked = lock.lock();
2681 if is_sleep.load(Ordering::Acquire) {
2682 let _ = condvar.wait_for(
2683 &mut locked,
2684 Duration::from_millis(sleep_timeout),
2685 );
2686 }
2687 is_sleep.store(false, Ordering::Release);
2688
2689 continue; }
2691
2692 sleep_count += 1; if let Some(interval) = &loop_interval {
2694 if let Some(remaining_interval) = Duration::from_millis(*interval).checked_sub(run_time){
2696 thread::sleep(remaining_interval);
2698 }
2699 }
2700 } else {
2701 sleep_count = 0; if let Some(interval) = &loop_interval {
2704 if let Some(remaining_interval) = Duration::from_millis(*interval).checked_sub(run_time){
2706 thread::sleep(remaining_interval);
2708 }
2709 }
2710 }
2711 }
2712 });
2713
2714 thread_status_copy
2715}
2716
2717pub fn wakeup_worker_thread<O: Default + 'static, P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P>>(worker_waker: &Arc<(AtomicBool, Mutex<()>, Condvar)>, rt: &SingleTaskRuntime<O, P>) {
2719 if worker_waker.0.load(Ordering::Relaxed) && rt.len() > 0 {
2721 let _ = wake_thread_waker(worker_waker);
2722 }
2723}
2724
2725pub fn register_global_panic_handler<Handler>(handler: Handler)
2727 where Handler: Fn(thread::Thread, String, Option<String>, Option<(String, u32, u32)>) -> Option<i32> + Send + Sync + 'static {
2728 set_hook(Box::new(move |panic_info| {
2729 let thread_info = thread::current();
2730
2731 let payload = panic_info.payload();
2732 let payload_info = match payload.downcast_ref::<&str>() {
2733 None => {
2734 match payload.downcast_ref::<String>() {
2736 None => {
2737 "Unknow panic".to_string()
2739 },
2740 Some(info) => {
2741 info.clone()
2742 }
2743 }
2744 },
2745 Some(info) => {
2746 info.to_string()
2747 }
2748 };
2749
2750 let other_info = if let Some(arg) = panic_info.payload_as_str() {
2751 Some(arg.to_string())
2752 } else {
2753 None
2754 };
2755
2756 let location = if let Some(location) = panic_info.location() {
2757 Some((location.file().to_string(), location.line(), location.column()))
2758 } else {
2759 None
2760 };
2761
2762 if let Some(exit_code) = handler(thread_info, payload_info, other_info, location) {
2763 std::process::exit(exit_code);
2765 }
2766 }));
2767}
2768
2769pub fn replace_global_alloc_error_handler() {
2771 set_alloc_error_hook(global_alloc_error_handle);
2772}
2773
2774fn global_alloc_error_handle(layout: Layout) {
2775 let bt = Backtrace::new();
2776 eprintln!("[UTC: {}][Thread: {}]Global memory allocation of {:?} bytes failed, stacktrace: \n{:?}",
2777 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_millis(),
2778 thread::current().name().unwrap_or(""),
2779 layout.size(),
2780 bt);
2781}
2782
2783pub(crate) struct YieldNow(bool);
2785
2786impl Future for YieldNow {
2787 type Output = ();
2788
2789 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2790 if self.0 {
2791 Poll::Ready(())
2792 } else {
2793 self.0 = true;
2794 cx.waker().wake_by_ref();
2795 Poll::Pending
2796 }
2797 }
2798}