1use std::thread;
2use std::any::Any;
3use std::pin::Pin;
4use std::ptr::null_mut;
5use std::vec::IntoIter;
6use std::time::Duration;
7use std::future::Future;
8use std::marker::PhantomData;
9use std::ops::{Deref, DerefMut};
10use std::cell::{RefCell, UnsafeCell};
11use std::task::{Poll, Waker, Context};
12use std::io::{Error, Result, ErrorKind};
13use std::fmt::{Debug, Formatter, Result as FmtResult};
14use std::sync::{Arc, atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering}};
15
16use futures::{future::{FutureExt, LocalBoxFuture},
17 stream::{Stream, StreamExt, LocalBoxStream},
18 task::ArcWake};
19use parking_lot::{Mutex, Condvar};
20use crossbeam_queue::ArrayQueue;
21use crossbeam_channel::{Sender, Receiver, unbounded};
22use flume::{Sender as AsyncSender, Receiver as AsyncReceiver};
23#[cfg(not(target_arch = "wasm32"))]
24use polling::Poller;
25use num_cpus;
26
27use pi_cancel_timer::Timer;
28use slotmap::{Key, KeyData};
29use quanta::{Clock, Instant as QInstant};
30
31use crate::{lock::spin,
32 rt::{PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME, TaskId, AsyncPipelineResult,
33 TimeoutWaiter, wake_thread_waker, wake_waiting_worker,
34 serial_local_thread::{LocalTaskRunner, LocalTaskRuntime},
35 serial_single_thread::SingleTaskRuntime,
36 serial_worker_thread::{WorkerTaskRunner, WorkerRuntime}}};
37
38pub struct AsyncTask<
42 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
43 O: Default + 'static = (),
44> {
45 uid: TaskId, future: Mutex<Option<LocalBoxFuture<'static, O>>>, pool: Arc<P>, priority: usize, context: Option<UnsafeCell<Box<dyn Any>>>, }
51
52unsafe impl<
53 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
54 O: Default + 'static,
55> Send for AsyncTask<P, O> {}
56unsafe impl<
57 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
58 O: Default + 'static,
59> Sync for AsyncTask<P, O> {}
60
61impl<
62 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P>,
63 O: Default + 'static,
64> ArcWake for AsyncTask<P, O> {
65 fn wake_by_ref(arc_self: &Arc<Self>) {
66 let pool = arc_self.get_pool();
67 let _ = pool.push_keep(arc_self.clone());
68
69 if let Some(waits) = pool.get_waits() {
70 let _ = wake_waiting_worker(waits);
72 } else {
73 if let Some(thread_waker) = pool.get_thread_waker() {
75 let _ = wake_thread_waker(thread_waker);
76 }
77 }
78 }
79}
80
81impl<
82 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P>,
83 O: Default + 'static,
84> AsyncTask<P, O> {
85 pub fn new(uid: TaskId,
87 pool: Arc<P>,
88 priority: usize,
89 future: Option<LocalBoxFuture<'static, O>>) -> AsyncTask<P, O> {
90 AsyncTask {
91 uid,
92 future: Mutex::new(future),
93 pool,
94 priority,
95 context: None,
96 }
97 }
98
99 pub fn with_context<C: 'static>(uid: TaskId,
101 pool: Arc<P>,
102 priority: usize,
103 future: Option<LocalBoxFuture<'static, O>>,
104 context: C) -> AsyncTask<P, O> {
105 let any = Box::new(context);
106
107 AsyncTask {
108 uid,
109 future: Mutex::new(future),
110 pool,
111 priority,
112 context: Some(UnsafeCell::new(any)),
113 }
114 }
115
116 pub fn with_runtime_and_context<RT, C>(runtime: &RT,
118 priority: usize,
119 future: Option<LocalBoxFuture<'static, O>>,
120 context: C) -> AsyncTask<P, O>
121 where RT: AsyncRuntime<O, Pool = P>,
122 C: 'static {
123 let any = Box::new(context);
124
125 AsyncTask {
126 uid: runtime.alloc::<O>(),
127 future: Mutex::new(future),
128 pool: runtime.shared_pool(),
129 priority,
130 context: Some(UnsafeCell::new(any)),
131 }
132 }
133
134 pub fn is_enable_wakeup(&self) -> bool {
136 self.uid.exist_waker::<O>()
137 }
138
139 pub fn get_inner(&self) -> Option<LocalBoxFuture<'static, O>> {
141 self.future.lock().take()
142 }
143
144 pub fn set_inner(&self, inner: Option<LocalBoxFuture<'static, O>>) {
146 *self.future.lock() = inner;
147 }
148
149 #[inline]
151 pub fn owner(&self) -> usize {
152 unsafe {
153 *self.uid.0.get() as usize
154 }
155 }
156
157 pub fn priority(&self) -> usize {
159 self.priority
160 }
161
162 pub fn exist_context(&self) -> bool {
164 self.context.is_some()
165 }
166
167 pub fn get_context<C: 'static>(&self) -> Option<&C> {
169 if let Some(context) = &self.context {
170 let any = unsafe { &*context.get() };
172 return <dyn Any>::downcast_ref::<C>(&**any);
173 }
174
175 None
176 }
177
178 pub fn get_context_mut<C: 'static>(&self) -> Option<&mut C> {
180 if let Some(context) = &self.context {
181 let any = unsafe { &mut *context.get() };
183 return <dyn Any>::downcast_mut::<C>(&mut **any);
184 }
185
186 None
187 }
188
189 pub fn set_context<C: 'static>(&self, new: C) {
191 if let Some(context) = &self.context {
192 let _ = unsafe { &*context.get() };
194
195 let any: Box<dyn Any + 'static> = Box::new(new);
197 unsafe { *context.get() = any; }
198 }
199 }
200
201 pub fn get_pool(&self) -> &P {
203 self.pool.as_ref()
204 }
205}
206
207pub trait AsyncTaskPool<O: Default + 'static = ()>: Default + 'static {
211 type Pool: AsyncTaskPoolExt<O> + AsyncTaskPool<O>;
212
213 fn get_thread_id(&self) -> usize;
215
216 fn len(&self) -> usize;
218
219 fn push(&self, task: Arc<AsyncTask<Self::Pool, O>>) -> Result<()>;
221
222 fn push_local(&self, task: Arc<AsyncTask<Self::Pool, O>>) -> Result<()>;
224
225 fn push_priority(&self, priority: usize, task: Arc<AsyncTask<Self::Pool, O>>) -> Result<()>;
227
228 fn push_keep(&self, task: Arc<AsyncTask<Self::Pool, O>>) -> Result<()>;
230
231 fn try_pop(&self) -> Option<Arc<AsyncTask<Self::Pool, O>>>;
233
234 fn try_pop_all(&self) -> IntoIter<Arc<AsyncTask<Self::Pool, O>>>;
236
237 fn get_thread_waker(&self) -> Option<&Arc<(AtomicBool, Mutex<()>, Condvar)>> {
239 None
240 }
241}
242
243pub trait AsyncTaskPoolExt<O: Default + 'static = ()>: 'static {
247 fn set_waits(&mut self,
249 _waits: Arc<ArrayQueue<Arc<(AtomicBool, Mutex<()>, Condvar)>>>) {}
250
251 fn get_waits(&self) -> Option<&Arc<ArrayQueue<Arc<(AtomicBool, Mutex<()>, Condvar)>>>> {
253 None
255 }
256
257 fn idler_len(&self) -> usize {
259 0
261 }
262
263 fn spawn_worker(&self) -> Option<usize> {
265 None
267 }
268
269 fn worker_len(&self) -> usize {
271 #[cfg(not(target_arch = "wasm32"))]
273 return num_cpus::get();
274 #[cfg(target_arch = "wasm32")]
275 return 1;
276 }
277
278 fn buffer_len(&self) -> usize {
280 0
282 }
283
284 fn set_thread_waker(&mut self, _thread_waker: Arc<(AtomicBool, Mutex<()>, Condvar)>) {
286 }
288
289 fn clone_thread_waker(&self) -> Option<Arc<(AtomicBool, Mutex<()>, Condvar)>> {
291 None
293 }
294
295 fn close_worker(&self) {
297 }
299}
300
301pub trait AsyncRuntime<O: Default + 'static = ()>: Clone + Send + Sync + 'static {
305 type Pool: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = Self::Pool>;
306
307 fn shared_pool(&self) -> Arc<Self::Pool>;
309
310 fn get_id(&self) -> usize;
312
313 fn wait_len(&self) -> usize;
315
316 fn len(&self) -> usize;
318
319 fn alloc<R: 'static>(&self) -> TaskId;
321
322 fn spawn<F>(&self, future: F) -> Result<TaskId>
324 where F: Future<Output = O> + 'static;
325
326 fn spawn_local<F>(&self, future: F) -> Result<TaskId>
328 where F: Future<Output = O> + 'static;
329
330 fn spawn_priority<F>(&self, priority: usize, future: F) -> Result<TaskId>
332 where F: Future<Output = O> + 'static;
333
334 fn spawn_yield<F>(&self, future: F) -> Result<TaskId>
336 where F: Future<Output = O> + 'static;
337
338 fn spawn_timing<F>(&self, future: F, time: usize) -> Result<TaskId>
340 where F: Future<Output = O> + 'static;
341
342 fn spawn_by_id<F>(&self, task_id: TaskId, future: F) -> Result<()>
344 where F: Future<Output = O> + 'static;
345
346 fn spawn_local_by_id<F>(&self, task_id: TaskId, future: F) -> Result<()>
348 where F: Future<Output = O> + 'static;
349
350 fn spawn_priority_by_id<F>(&self,
352 task_id: TaskId,
353 priority: usize,
354 future: F) -> Result<()>
355 where F: Future<Output = O> + 'static;
356
357 fn spawn_yield_by_id<F>(&self, task_id: TaskId, future: F) -> Result<()>
359 where F: Future<Output = O> + 'static;
360
361 fn spawn_timing_by_id<F>(&self,
363 task_id: TaskId,
364 future: F,
365 time: usize) -> Result<()>
366 where F: Future<Output = O> + 'static;
367
368 fn pending<Output: 'static>(&self, task_id: &TaskId, waker: Waker) -> Poll<Output>;
370
371 fn wakeup<Output: 'static>(&self, task_id: &TaskId);
373
374 fn wait<V: 'static>(&self) -> AsyncWait<V>;
376
377 fn wait_any<V: 'static>(&self, capacity: usize) -> AsyncWaitAny<V>;
379
380 fn wait_any_callback<V: 'static>(&self, capacity: usize) -> AsyncWaitAnyCallback<V>;
382
383 fn map_reduce<V: 'static>(&self, capacity: usize) -> AsyncMapReduce<V>;
385
386 fn timeout(&self, timeout: usize) -> LocalBoxFuture<'static, ()>;
388
389 fn yield_now(&self) -> LocalBoxFuture<'static, ()>;
391
392 fn pipeline<S, SO, F, FO>(&self, input: S, filter: F) -> LocalBoxStream<'static, FO>
394 where S: Stream<Item = SO> + 'static,
395 SO: 'static,
396 F: FnMut(SO) -> AsyncPipelineResult<FO> + 'static,
397 FO: 'static;
398
399 fn close(&self) -> bool;
401}
402
403pub trait AsyncRuntimeExt<O: Default + 'static = ()> {
407 fn spawn_with_context<F, C>(&self,
409 task_id: TaskId,
410 future: F,
411 context: C) -> Result<()>
412 where F: Future<Output = O> + 'static,
413 C: 'static;
414
415 fn spawn_timing_with_context<F, C>(&self,
417 task_id: TaskId,
418 future: F,
419 context: C,
420 time: usize) -> Result<()>
421 where F: Future<Output = O> + 'static,
422 C: 'static;
423
424 fn block_on<F>(&self, future: F) -> Result<F::Output>
426 where F: Future + 'static,
427 <F as Future>::Output: Default + 'static;
428}
429
430pub struct AsyncRuntimeBuilder<O: Default + 'static = ()>(PhantomData<O>);
434
435impl<O: Default + 'static> AsyncRuntimeBuilder<O> {
436 pub fn default_local_thread(name: Option<&str>,
438 stack_size: Option<usize>) -> LocalTaskRuntime<O> {
439 let runner = LocalTaskRunner::new();
440
441 let thread_name = if let Some(name) = name {
442 name
443 } else {
444 "Default-Local-RT"
446 };
447 let thread_stack_size = if let Some(size) = stack_size {
448 size
449 } else {
450 2 * 1024 * 1024
452 };
453
454 runner.startup(thread_name, thread_stack_size)
455 }
456
457 pub fn default_worker_thread(worker_name: Option<&str>,
459 worker_stack_size: Option<usize>,
460 worker_sleep_timeout: Option<u64>,
461 worker_loop_interval: Option<Option<u64>>) -> WorkerRuntime<O> {
462 let runner = WorkerTaskRunner::default();
463
464 let thread_name = if let Some(name) = worker_name {
465 name
466 } else {
467 "Default-Single-Worker"
469 };
470 let thread_stack_size = if let Some(size) = worker_stack_size {
471 size
472 } else {
473 2 * 1024 * 1024
475 };
476 let sleep_timeout = if let Some(timeout) = worker_sleep_timeout {
477 timeout
478 } else {
479 1
481 };
482 let loop_interval = if let Some(interval) = worker_loop_interval {
483 interval
484 } else {
485 None
487 };
488
489 let clock = Clock::new();
491 let runner_copy = runner.clone();
492 let rt_copy = runner.get_runtime();
493 let rt = runner.startup(
494 thread_name,
495 thread_stack_size,
496 sleep_timeout,
497 loop_interval,
498 move || {
499 let now = clock.recent();
500 match runner_copy.run_once() {
501 Err(e) => {
502 panic!("Run runner failed, reason: {:?}", e);
503 },
504 Ok(len) => {
505 (len == 0,
506 clock
507 .recent()
508 .duration_since(now))
509 },
510 }
511 },
512 move || {
513 rt_copy.wait_len() + rt_copy.len()
514 },
515 );
516
517 rt
518 }
519
520 #[cfg(not(target_arch = "wasm32"))]
522 pub fn custom_local_thread(name: Option<&str>,
523 stack_size: Option<usize>,
524 poller: Option<Arc<Poller>>,
525 try_count: Option<usize>,
526 timeout: Option<Duration>,) -> LocalTaskRuntime<O> {
527 let poller = if let Some(poller) = poller {
528 poller
529 } else {
530 Arc::new(Poller::new().expect("Failed to create poller"))
531 };
532 let runner = LocalTaskRunner::with_poll(poller);
533
534 let thread_name = if let Some(name) = name {
535 name
536 } else {
537 "Custom-Local-RT"
539 };
540 let thread_stack_size = if let Some(size) = stack_size {
541 size
542 } else {
543 2 * 1024 * 1024
545 };
546 let try_count = try_count.unwrap_or(3);
547
548 runner.startup_with_poll(
549 thread_name,
550 thread_stack_size,
551 try_count,
552 timeout
553 )
554 }
555
556 pub fn custom_worker_thread<P, F0, F1>(pool: P,
558 worker_handle: Arc<AtomicBool>,
559 worker_condvar: Arc<(AtomicBool, Mutex<()>, Condvar)>,
560 thread_name: &str,
561 thread_stack_size: usize,
562 sleep_timeout: u64,
563 loop_interval: Option<u64>,
564 loop_func: F0,
565 get_queue_len: F1) -> WorkerRuntime<O, P>
566 where P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P>,
567 F0: Fn() -> (bool, Duration) + Send + 'static,
568 F1: Fn() -> usize + Send + 'static {
569 let runner = WorkerTaskRunner::new(pool,
570 worker_handle,
571 worker_condvar);
572
573 let rt_copy = runner.get_runtime();
575 let rt = runner.startup(
576 thread_name,
577 thread_stack_size,
578 sleep_timeout,
579 loop_interval,
580 loop_func,
581 move || {
582 rt_copy.wait_len() + get_queue_len()
583 },
584 );
585
586 rt
587 }
588}
589
590pub fn bind_local_thread<O: Default + 'static>(runtime: LocalAsyncRuntime<O>) {
592 match PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME.try_with(move |rt| {
593 let raw = Arc::into_raw(Arc::new(runtime)) as *mut LocalAsyncRuntime<O> as *mut ();
594 rt.store(raw, Ordering::Relaxed);
595 }) {
596 Err(e) => {
597 panic!("Bind single runtime to local thread failed, reason: {:?}", e);
598 },
599 Ok(_) => (),
600 }
601}
602
603pub fn unbind_local_thread() {
605 let _ = PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME.try_with(move |rt| {
606 rt.store(null_mut(), Ordering::Relaxed);
607 });
608}
609
610pub struct LocalAsyncRuntime<O: Default + 'static> {
614 inner: *const (), get_id_func: fn(*const ()) -> usize, spawn_func: fn(*const (), LocalBoxFuture<'static, O>) -> Result<()>, spawn_local_func: fn(*const (), LocalBoxFuture<'static, O>) -> Result<()>, spawn_timing_func: fn(*const (), LocalBoxFuture<'static, O>, usize) -> Result<()>, timeout_func: fn(*const (), usize) -> LocalBoxFuture<'static, ()>, }
621
622unsafe impl<O: Default + 'static> Send for LocalAsyncRuntime<O> {}
623unsafe impl<O: Default + 'static> Sync for LocalAsyncRuntime<O> {}
624
625impl<O: Default + 'static> LocalAsyncRuntime<O> {
626 pub fn new(inner: *const (),
628 get_id_func: fn(*const ()) -> usize,
629 spawn_func: fn(*const (), LocalBoxFuture<'static, O>) -> Result<()>,
630 spawn_timing_func: fn(*const (), LocalBoxFuture<'static, O>, usize) -> Result<()>,
631 timeout_func: fn(*const (), usize) -> LocalBoxFuture<'static, ()>) -> Self {
632 LocalAsyncRuntime {
633 inner,
634 get_id_func,
635 spawn_func,
636 spawn_local_func: spawn_func,
637 spawn_timing_func,
638 timeout_func,
639 }
640 }
641
642 #[inline]
644 pub fn get_id(&self) -> usize {
645 (self.get_id_func)(self.inner)
646 }
647
648 #[inline]
650 pub fn spawn<F>(&self, future: F) -> Result<()>
651 where F: Future<Output = O> + 'static {
652 (self.spawn_func)(self.inner, async move {
653 future.await
654 }.boxed_local())
655 }
656
657 #[inline]
659 pub fn spawn_local<F>(&self, future: F) -> Result<()>
660 where F: Future<Output = O> + 'static {
661 (self.spawn_local_func)(self.inner, async move {
662 future.await
663 }.boxed_local())
664 }
665
666 #[inline]
668 pub fn sapwn_timing_func<F>(&self, future: F, timeout: usize) -> Result<()>
669 where F: Future<Output = O> + 'static {
670 (self.spawn_timing_func)(self.inner,
671 async move {
672 future.await
673 }.boxed_local(),
674 timeout)
675 }
676
677 #[inline]
679 pub fn timeout(&self, timeout: usize) -> LocalBoxFuture<'static, ()> {
680 (self.timeout_func)(self.inner, timeout)
681 }
682}
683
684pub fn local_serial_async_runtime<O: Default + 'static>() -> Option<Arc<LocalAsyncRuntime<O>>> {
689 match PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME.try_with(move |ptr| {
690 let raw = ptr.load(Ordering::Relaxed) as *const LocalAsyncRuntime<O>;
691 unsafe {
692 if raw.is_null() {
693 None
695 } else {
696 let shared: Arc<LocalAsyncRuntime<O>> = unsafe { Arc::from_raw(raw) };
698 let result = shared.clone();
699 Arc::into_raw(shared); Some(result)
701 }
702 }
703 }) {
704 Err(_) => None, Ok(rt) => rt,
706 }
707}
708
709pub fn spawn_local<O, F>(future: F) -> Result<()>
714 where O: Default + 'static,
715 F: Future<Output = O> + 'static {
716 if let Some(rt) = local_serial_async_runtime::<O>() {
717 rt.spawn(future)
718 } else {
719 Err(Error::new(ErrorKind::Other, format!("Spawn task to local thread failed, reason: runtime not exist")))
720 }
721}
722
723pub fn local_async_runtime<O: Default + 'static>() -> Option<Arc<LocalAsyncRuntime<O>>> {
728 match PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME.try_with(move |ptr| {
729 let raw = ptr.load(Ordering::Relaxed) as *const LocalAsyncRuntime<O>;
730 unsafe {
731 if raw.is_null() {
732 None
734 } else {
735 let shared: Arc<LocalAsyncRuntime<O>> = unsafe { Arc::from_raw(raw) };
737 let result = shared.clone();
738 Arc::into_raw(shared); Some(result)
740 }
741 }
742 }) {
743 Err(_) => None, Ok(rt) => rt,
745 }
746}
747
748pub struct AsyncValue<V: 'static>(Arc<InnerAsyncValue<V>>);
752
753unsafe impl<V: 'static> Send for AsyncValue<V> {}
754unsafe impl<V: 'static> Sync for AsyncValue<V> {}
755
756impl<V: 'static> Clone for AsyncValue<V> {
757 fn clone(&self) -> Self {
758 AsyncValue(self.0.clone())
759 }
760}
761
762impl<V: Send + 'static> Debug for AsyncValue<V> {
763 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
764 write!(f,
765 "AsyncValue[status = {}]",
766 self.0.status.load(Ordering::Acquire))
767 }
768}
769
770impl<V: 'static> Future for AsyncValue<V> {
771 type Output = V;
772
773 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
774 let mut spin_len = 1;
775 while self.0.status.load(Ordering::Acquire) == 2 {
776 spin_len = spin(spin_len);
778 }
779
780 if self.0.status.load(Ordering::Acquire) == 3 {
781 if let Some(value) = unsafe { (*(&self).0.value.get()).take() } {
782 return Poll::Ready(value);
784 }
785 }
786
787 unsafe {
788 *self.0.waker.get() = Some(cx.waker().clone()); }
790
791 let mut spin_len = 1;
792 loop {
793 match self.0.status.compare_exchange(0,
794 1, Ordering::Acquire,
795 Ordering::Relaxed) {
796 Err(2) => {
797 spin_len = spin(spin_len);
799 continue;
800 },
801 Err(3) => {
802 let value = unsafe { (*(&self).0.value.get()).take().unwrap() };
804 return Poll::Ready(value);
805 },
806 Err(_) => {
807 unimplemented!();
808 },
809 Ok(_) => {
810 return Poll::Pending;
812 },
813 }
814 }
815 }
816}
817
818impl<V: 'static> AsyncValue<V> {
822 pub fn new() -> Self {
824 let inner = InnerAsyncValue {
825 value: UnsafeCell::new(None),
826 waker: UnsafeCell::new(None),
827 status: AtomicU8::new(0),
828 };
829
830 AsyncValue(Arc::new(inner))
831 }
832
833 pub fn is_complete(&self) -> bool {
835 self
836 .0
837 .status
838 .load(Ordering::Relaxed) == 3
839 }
840
841 pub fn set(self, value: V) {
843 loop {
844 match self.0.status.compare_exchange(1,
845 2,
846 Ordering::Acquire,
847 Ordering::Relaxed) {
848 Err(0) => {
849 match self.0.status.compare_exchange(0,
850 2,
851 Ordering::Acquire,
852 Ordering::Relaxed) {
853 Err(1) => {
854 continue;
856 },
857 Err(_) => {
858 return;
860 },
861 Ok(_) => {
862 unsafe { *self.0.value.get() = Some(value); }
864 self.0.status.store(3, Ordering::Release);
865 return;
866 }
867 }
868 },
869 Err(_) => {
870 return;
872 },
873 Ok(_) => {
874 break;
876 }
877 }
878 }
879
880 unsafe { *self.0.value.get() = Some(value); }
882 self.0.status.store(3, Ordering::Release);
883 let waker = unsafe { (*self.0.waker.get()).take().unwrap() };
884 waker.wake();
885 }
886}
887
888pub struct InnerAsyncValue<V: 'static> {
890 value: UnsafeCell<Option<V>>, waker: UnsafeCell<Option<Waker>>, status: AtomicU8, }
894
895pub struct AsyncVariableGuard<'a, V: 'static> {
899 value: &'a UnsafeCell<Option<V>>, waker: &'a UnsafeCell<Option<Waker>>, status: &'a AtomicU8, }
903
904unsafe impl<V: 'static> Send for AsyncVariableGuard<'_, V> {}
905
906impl<V: 'static> Drop for AsyncVariableGuard<'_, V> {
907 fn drop(&mut self) {
908 self.status.fetch_sub(2, Ordering::Relaxed);
912 }
913}
914
915impl<V: 'static> Deref for AsyncVariableGuard<'_, V> {
916 type Target = Option<V>;
917
918 fn deref(&self) -> &Self::Target {
919 unsafe {
920 &*self.value.get()
921 }
922 }
923}
924
925impl<V: 'static> DerefMut for AsyncVariableGuard<'_, V> {
926 fn deref_mut(&mut self) -> &mut Self::Target {
927 unsafe {
928 &mut *self.value.get()
929 }
930 }
931}
932
933impl<V: 'static> AsyncVariableGuard<'_, V> {
934 pub fn finish(self) {
936 if self.status.fetch_add(4, Ordering::Relaxed) == 3 {
938 if let Some(waker) = unsafe { (&mut *self.waker.get()).take() } {
939 waker.wake();
941 }
942 }
943 }
944}
945
946pub struct AsyncVariable<V: 'static>(Arc<InnerAsyncVariable<V>>);
950
951unsafe impl<V: 'static> Send for AsyncVariable<V> {}
952unsafe impl<V: 'static> Sync for AsyncVariable<V> {}
953
954impl<V: 'static> Clone for AsyncVariable<V> {
955 fn clone(&self) -> Self {
956 AsyncVariable(self.0.clone())
957 }
958}
959
960impl<V: 'static> Future for AsyncVariable<V> {
961 type Output = V;
962
963 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
964 unsafe {
965 *self.0.waker.get() = Some(cx.waker().clone()); }
967
968 let mut spin_len = 1;
969 loop {
970 match self.0.status.compare_exchange(0,
971 1,
972 Ordering::Acquire,
973 Ordering::Relaxed) {
974 Err(current) if current & 4 != 0 => {
975 unsafe {
977 let _ = (&mut *self.0.waker.get()).take(); return Poll::Ready((&mut *(&self).0.value.get()).take().unwrap());
979 }
980 },
981 Err(_) => {
982 spin_len = spin(spin_len);
984 },
985 Ok(_) => {
986 return Poll::Pending;
988 },
989 }
990 }
991 }
992}
993
994impl<V: 'static> AsyncVariable<V> {
995 pub fn new() -> Self {
997 let inner = InnerAsyncVariable {
998 value: UnsafeCell::new(None),
999 waker: UnsafeCell::new(None),
1000 status: AtomicU8::new(0),
1001 };
1002
1003 AsyncVariable(Arc::new(inner))
1004 }
1005
1006 pub fn is_complete(&self) -> bool {
1008 self
1009 .0
1010 .status
1011 .load(Ordering::Acquire) & 4 != 0
1012 }
1013
1014 pub fn lock(&self) -> Option<AsyncVariableGuard<V>> {
1016 let mut spin_len = 1;
1017 loop {
1018 match self
1019 .0
1020 .status
1021 .compare_exchange(1,
1022 3,
1023 Ordering::Acquire,
1024 Ordering::Relaxed) {
1025 Err(0) => {
1026 match self
1028 .0
1029 .status
1030 .compare_exchange(0,
1031 2,
1032 Ordering::Acquire,
1033 Ordering::Relaxed) {
1034 Err(1) => {
1035 continue;
1037 },
1038 Err(2) => {
1039 spin_len = spin(spin_len);
1041 },
1042 Err(3) => {
1043 spin_len = spin(spin_len);
1045 },
1046 Err(_) => {
1047 return None;
1049 },
1050 Ok(_) => {
1051 let guard = AsyncVariableGuard {
1053 value: &self.0.value,
1054 waker: &self.0.waker,
1055 status: &self.0.status,
1056 };
1057
1058 return Some(guard)
1059 },
1060 }
1061 },
1062 Err(2) => {
1063 spin_len = spin(spin_len);
1065 },
1066 Err(3) => {
1067 spin_len = spin(spin_len);
1069 },
1070 Err(_) => {
1071 return None;
1073 }
1074 Ok(_) => {
1075 let guard = AsyncVariableGuard {
1077 value: &self.0.value,
1078 waker: &self.0.waker,
1079 status: &self.0.status,
1080 };
1081
1082 return Some(guard)
1083 },
1084 }
1085 }
1086 }
1087}
1088
1089pub struct InnerAsyncVariable<V: 'static> {
1091 value: UnsafeCell<Option<V>>, waker: UnsafeCell<Option<Waker>>, status: AtomicU8, }
1095
1096pub struct AsyncWaitResult<V: 'static>(pub Arc<RefCell<Option<Result<V>>>>);
1100
1101unsafe impl<V: 'static> Send for AsyncWaitResult<V> {}
1102unsafe impl<V: 'static> Sync for AsyncWaitResult<V> {}
1103
1104impl<V: 'static> Clone for AsyncWaitResult<V> {
1105 fn clone(&self) -> Self {
1106 AsyncWaitResult(self.0.clone())
1107 }
1108}
1109
1110pub struct AsyncWaitResults<V: 'static>(pub Arc<RefCell<Option<Vec<Result<V>>>>>);
1114
1115unsafe impl<V: 'static> Send for AsyncWaitResults<V> {}
1116unsafe impl<V: 'static> Sync for AsyncWaitResults<V> {}
1117
1118impl<V: 'static> Clone for AsyncWaitResults<V> {
1119 fn clone(&self) -> Self {
1120 AsyncWaitResults(self.0.clone())
1121 }
1122}
1123
1124pub enum AsyncTimingTask<
1128 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1129 O: Default + 'static = (),
1130> {
1131 Pended(TaskId), WaitRun(Arc<AsyncTask<P, O>>), TimeoutWake(Arc<TimeoutWaiter>), }
1135
1136pub struct AsyncTaskTimer<
1140 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1141 O: Default + 'static = (),
1142> {
1143 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, }
1149
1150unsafe impl<
1151 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1152 O: Default + 'static,
1153> Send for AsyncTaskTimer<P, O> {}
1154unsafe impl<
1155 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1156 O: Default + 'static,
1157> Sync for AsyncTaskTimer<P, O> {}
1158
1159impl<
1160 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1161 O: Default + 'static,
1162> AsyncTaskTimer<P, O> {
1163 pub fn new() -> Self {
1165 let (producor, consumer) = unbounded();
1166 let clock = Clock::new();
1167 let now = clock.recent();
1168
1169 AsyncTaskTimer {
1170 producor,
1171 consumer,
1172 timer: Arc::new(RefCell::new(Timer::<AsyncTimingTask<P, O>, 1000, 60, 3>::default())),
1173 clock,
1174 now,
1175 }
1176 }
1177
1178 #[inline]
1180 pub fn get_producor(&self) -> &Sender<(usize, AsyncTimingTask<P, O>)> {
1181 &self.producor
1182 }
1183
1184 #[inline]
1186 pub fn len(&self) -> usize {
1187 let timer = self.timer.as_ref().borrow();
1188 timer.add_count() - timer.remove_count()
1189 }
1190
1191 pub fn set_timer(&self, task: AsyncTimingTask<P, O>, timeout: usize) -> usize {
1193 let current_time = self
1194 .clock
1195 .recent()
1196 .duration_since(self.now)
1197 .as_millis() as u64;
1198 self
1199 .timer
1200 .borrow_mut()
1201 .push_time(current_time + timeout as u64, task)
1202 .data()
1203 .as_ffi() as usize
1204 }
1205
1206 pub fn cancel_timer(&self, timer_ref: usize) -> Option<AsyncTimingTask<P, O>> {
1208 if let Some(item) =self
1209 .timer
1210 .borrow_mut()
1211 .cancel(KeyData::from_ffi(timer_ref as u64).into()) {
1212 Some(item)
1213 } else {
1214 None
1215 }
1216 }
1217
1218 pub fn consume(&self) -> usize {
1220 let mut len = 0;
1221 let timer_tasks = self.consumer.try_iter().collect::<Vec<(usize, AsyncTimingTask<P, O>)>>();
1222 for (timeout, task) in timer_tasks {
1223 self.set_timer(task, timeout);
1224 len += 1;
1225 }
1226
1227 len
1228 }
1229
1230 pub fn is_require_pop(&self) -> Option<u64> {
1232 let current_time = self
1233 .clock
1234 .recent()
1235 .duration_since(self.now)
1236 .as_millis() as u64;
1237 if self.timer.borrow_mut().is_ok(current_time) {
1238 Some(current_time)
1239 } else {
1240 None
1241 }
1242 }
1243
1244 pub fn pop(&self, current_time: u64) -> Option<(usize, AsyncTimingTask<P, O>)> {
1246 if let Some((key, item)) = self.timer.borrow_mut().pop_kv(current_time) {
1247 Some((key.data().as_ffi() as usize, item))
1248 } else {
1249 None
1250 }
1251 }
1252}
1253
1254pub struct AsyncWaitTimeout<
1258 RT: AsyncRuntime<O>,
1259 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1260 O: Default + 'static = (),
1261> {
1262 rt: RT, producor: Sender<(usize, AsyncTimingTask<P, O>)>, timeout: usize, registered: AtomicBool, waiter: Arc<TimeoutWaiter>, }
1268
1269unsafe impl<
1270 RT: AsyncRuntime<O>,
1271 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1272 O: Default + 'static,
1273> Send for AsyncWaitTimeout<RT, P, O> {}
1274unsafe impl<
1275 RT: AsyncRuntime<O>,
1276 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1277 O: Default + 'static,
1278> Sync for AsyncWaitTimeout<RT, P, O> {}
1279
1280impl<
1281 RT: AsyncRuntime<O>,
1282 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1283 O: Default + 'static,
1284> Future for AsyncWaitTimeout<RT, P, O> {
1285 type Output = ();
1286
1287 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1288 if self.waiter.is_fired() {
1289 return Poll::Ready(());
1291 }
1292
1293 self.waiter.register(cx.waker());
1294
1295 if !self.registered.swap(true, Ordering::AcqRel) {
1296 let _ = self
1298 .producor
1299 .send((self.timeout, AsyncTimingTask::TimeoutWake(self.waiter.clone())));
1300 }
1301
1302 if self.waiter.is_fired() {
1303 Poll::Ready(())
1304 } else {
1305 Poll::Pending
1306 }
1307 }
1308}
1309
1310impl<
1311 RT: AsyncRuntime<O>,
1312 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1313 O: Default + 'static,
1314> Drop for AsyncWaitTimeout<RT, P, O> {
1315 fn drop(&mut self) {
1316 self.waiter.clear_waker();
1317 }
1318}
1319
1320impl<
1321 RT: AsyncRuntime<O>,
1322 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1323 O: Default + 'static,
1324> AsyncWaitTimeout<RT, P, O> {
1325 pub fn new(rt: RT,
1327 producor: Sender<(usize, AsyncTimingTask<P, O>)>,
1328 timeout: usize) -> Self {
1329 AsyncWaitTimeout {
1330 rt,
1331 producor,
1332 timeout,
1333 registered: AtomicBool::new(false), waiter: Arc::new(TimeoutWaiter::new()),
1335 }
1336 }
1337}
1338
1339pub struct AsyncWait<V: 'static>(AsyncWaitAny<V>);
1343
1344unsafe impl<V: 'static> Send for AsyncWait<V> {}
1345unsafe impl<V: 'static> Sync for AsyncWait<V> {}
1346
1347impl<V: 'static> AsyncWait<V> {
1351 pub(crate) fn new(inner: AsyncWaitAny<V>) -> Self {
1353 AsyncWait(inner)
1354 }
1355
1356 pub fn spawn<RT, O, F>(&self,
1358 rt: RT,
1359 timeout: Option<usize>,
1360 future: F) -> Result<()>
1361 where RT: AsyncRuntime<O>,
1362 O: Default + 'static,
1363 F: Future<Output = Result<V>> + 'static {
1364 self.0.spawn(rt.clone(), future)?;
1365
1366 if let Some(timeout) = timeout {
1367 let rt_copy = rt.clone();
1369 self.0.spawn(rt, async move {
1370 rt_copy.timeout(timeout).await;
1371
1372 Err(Error::new(ErrorKind::TimedOut, format!("Time out")))
1374 })
1375 } else {
1376 Ok(())
1378 }
1379 }
1380
1381 pub fn spawn_local<O, F>(&self,
1383 timeout: Option<usize>,
1384 future: F) -> Result<()>
1385 where O: Default + 'static,
1386 F: Future<Output = Result<V>> + 'static {
1387 if let Some(rt) = local_serial_async_runtime::<O>() {
1388 self.0.spawn_local(future)?;
1390
1391 if let Some(timeout) = timeout {
1392 let rt_copy = rt.clone();
1394 self.0.spawn_local(async move {
1395 rt_copy.timeout(timeout).await;
1396
1397 Err(Error::new(ErrorKind::TimedOut, format!("Time out")))
1399 })
1400 } else {
1401 Ok(())
1403 }
1404 } else {
1405 Err(Error::new(ErrorKind::Other, format!("Spawn wait task failed, reason: local async runtime not exist")))
1407 }
1408 }
1409}
1410
1411impl<V: 'static> AsyncWait<V> {
1415 pub async fn wait_result(self) -> Result<V> {
1417 self.0.wait_result().await
1418 }
1419}
1420
1421pub struct AsyncWaitAny<V: 'static> {
1425 capacity: usize, producor: AsyncSender<Result<V>>, consumer: AsyncReceiver<Result<V>>, }
1429
1430unsafe impl<V: 'static> Send for AsyncWaitAny<V> {}
1431unsafe impl<V: 'static> Sync for AsyncWaitAny<V> {}
1432
1433impl<V: 'static> AsyncWaitAny<V> {
1437 pub(crate) fn new(capacity: usize,
1439 producor: AsyncSender<Result<V>>,
1440 consumer: AsyncReceiver<Result<V>>) -> Self {
1441 AsyncWaitAny {
1442 capacity,
1443 producor,
1444 consumer,
1445 }
1446 }
1447
1448 pub fn spawn<RT, O, F>(&self,
1450 rt: RT,
1451 future: F) -> Result<()>
1452 where RT: AsyncRuntime<O>,
1453 O: Default + 'static,
1454 F: Future<Output = Result<V>> + 'static {
1455 let producor = self.producor.clone();
1456 rt.spawn_by_id(rt.alloc::<O>(), async move {
1457 let value = future.await;
1458 producor.into_send_async(value).await;
1459
1460 Default::default()
1462 })
1463 }
1464
1465 pub fn spawn_local<F>(&self,
1467 future: F) -> Result<()>
1468 where F: Future<Output = Result<V>> + 'static {
1469 if let Some(rt) = local_serial_async_runtime() {
1470 let producor = self.producor.clone();
1472 rt.spawn(async move {
1473 let value = future.await;
1474 producor.into_send_async(value).await;
1475 })
1476 } else {
1477 Err(Error::new(ErrorKind::Other, format!("Spawn wait any task failed, reason: local async runtime not exist")))
1479 }
1480 }
1481}
1482
1483impl<V: 'static> AsyncWaitAny<V> {
1487 pub async fn wait_result(self) -> Result<V> {
1489 match self.consumer.recv_async().await {
1490 Err(e) => {
1491 Err(Error::new(ErrorKind::Other, format!("Wait any result failed, reason: {:?}", e)))
1493 },
1494 Ok(result) => {
1495 result
1497 },
1498 }
1499 }
1500}
1501
1502pub struct AsyncWaitAnyCallback<V: 'static> {
1506 capacity: usize, producor: AsyncSender<Result<V>>, consumer: AsyncReceiver<Result<V>>, }
1510
1511unsafe impl<V: 'static> Send for AsyncWaitAnyCallback<V> {}
1512unsafe impl<V: 'static> Sync for AsyncWaitAnyCallback<V> {}
1513
1514impl<V: 'static> AsyncWaitAnyCallback<V> {
1518 pub(crate) fn new(capacity: usize,
1520 producor: AsyncSender<Result<V>>,
1521 consumer: AsyncReceiver<Result<V>>) -> Self {
1522 AsyncWaitAnyCallback {
1523 capacity,
1524 producor,
1525 consumer,
1526 }
1527 }
1528
1529 pub fn spawn<RT, O, F>(&self,
1531 rt: RT,
1532 future: F) -> Result<()>
1533 where RT: AsyncRuntime<O>,
1534 O: Default + 'static,
1535 F: Future<Output = Result<V>> + 'static {
1536 let producor = self.producor.clone();
1537 rt.spawn_by_id(rt.alloc::<O>(), async move {
1538 let value = future.await;
1539 producor.into_send_async(value).await;
1540
1541 Default::default()
1543 })
1544 }
1545
1546 pub fn spawn_local<F>(&self,
1548 future: F) -> Result<()>
1549 where F: Future<Output = Result<V>> + 'static {
1550 if let Some(rt) = local_serial_async_runtime() {
1551 let producor = self.producor.clone();
1553 rt.spawn(async move {
1554 let value = future.await;
1555 producor.into_send_async(value).await;
1556 })
1557 } else {
1558 Err(Error::new(ErrorKind::Other, format!("Spawn wait any task failed by callback, reason: current async runtime not exist")))
1560 }
1561 }
1562}
1563
1564impl<V: 'static> AsyncWaitAnyCallback<V> {
1568 pub async fn wait_result(mut self,
1570 callback: impl Fn(&Result<V>) -> bool + 'static) -> Result<V> {
1571 let checker = create_checker(self.capacity, callback);
1572 loop {
1573 match self.consumer.recv_async().await {
1574 Err(e) => {
1575 return Err(Error::new(ErrorKind::Other, format!("Wait any result failed by callback, reason: {:?}", e)));
1577 },
1578 Ok(result) => {
1579 if checker(&result) {
1581 return result;
1583 }
1584 },
1585 }
1586 }
1587 }
1588}
1589
1590fn create_checker<V, F>(len: usize,
1592 callback: F) -> Arc<dyn Fn(&Result<V>) -> bool + 'static>
1593 where V: 'static,
1594 F: Fn(&Result<V>) -> bool + 'static {
1595 let mut check_counter = AtomicUsize::new(len); Arc::new(move |result| {
1597 if check_counter.fetch_sub(1, Ordering::SeqCst) == 1 {
1598 true
1600 } else {
1601 callback(result)
1603 }
1604 })
1605}
1606
1607pub struct AsyncMapReduce<V: 'static> {
1611 count: usize, capacity: usize, producor: AsyncSender<(usize, Result<V>)>, consumer: AsyncReceiver<(usize, Result<V>)>, }
1616
1617unsafe impl<V: 'static> Send for AsyncMapReduce<V> {}
1618
1619impl<V: 'static> AsyncMapReduce<V> {
1623 pub(crate) fn new(count: usize,
1625 capacity: usize,
1626 producor: AsyncSender<(usize, Result<V>)>,
1627 consumer: AsyncReceiver<(usize, Result<V>)>) -> Self {
1628 AsyncMapReduce {
1629 count,
1630 capacity,
1631 producor,
1632 consumer,
1633 }
1634 }
1635
1636 pub fn map<RT, O, F>(&mut self, rt: RT, future: F) -> Result<usize>
1638 where RT: AsyncRuntime<O>,
1639 O: Default + 'static,
1640 F: Future<Output = Result<V>> + 'static {
1641 if self.count >= self.capacity {
1642 return Err(Error::new(ErrorKind::Other, format!("Map task to runtime failed, capacity: {}, reason: out of capacity", self.capacity)));
1644 }
1645
1646 let index = self.count;
1647 let producor = self.producor.clone();
1648 rt.spawn(async move {
1649 let value = future.await;
1650 producor.into_send_async((index, value)).await;
1651
1652 Default::default()
1654 })?;
1655
1656 self.count += 1; Ok(index)
1658 }
1659}
1660
1661impl<V: 'static> AsyncMapReduce<V> {
1665 pub async fn reduce(self, order: bool) -> Result<Vec<Result<V>>> {
1667 let mut count = self.count;
1668 let mut results = Vec::with_capacity(count);
1669 while count > 0 {
1670 match self.consumer.recv_async().await {
1671 Err(e) => {
1672 return Err(Error::new(ErrorKind::Other, format!("Reduce result failed, reason: {:?}", e)));
1674 },
1675 Ok((index, result)) => {
1676 results.push((index, result));
1678 count -= 1;
1679 },
1680 }
1681 }
1682
1683 if order {
1684 results.sort_by_key(|(key, _value)| {
1686 key.clone()
1687 });
1688 }
1689 let (_, values) = results
1690 .into_iter()
1691 .unzip::<usize, Result<V>, Vec<usize>, Vec<Result<V>>>();
1692
1693 Ok(values)
1694 }
1695}
1696
1697pub fn spawn_worker_thread<F0, F1>(thread_name: &str,
1703 thread_stack_size: usize,
1704 thread_handler: Arc<AtomicBool>,
1705 thread_waker: Arc<(AtomicBool, Mutex<()>, Condvar)>, sleep_timeout: u64, loop_interval: Option<u64>, loop_func: F0,
1709 get_queue_len: F1) -> Arc<AtomicBool>
1710 where F0: Fn() -> (bool, Duration) + Send + 'static,
1711 F1: Fn() -> usize + Send + 'static {
1712 let thread_status_copy = thread_handler.clone();
1713
1714 thread::Builder::new()
1715 .name(thread_name.to_string())
1716 .stack_size(thread_stack_size)
1717 .spawn(move || {
1718 let mut sleep_count = 0;
1719
1720 while thread_handler.load(Ordering::Relaxed) {
1721 let (is_no_task, run_time) = loop_func();
1722
1723 if is_no_task {
1724 if sleep_count > 1 {
1726 sleep_count = 0; let (is_sleep, lock, condvar) = &*thread_waker;
1729 if get_queue_len() > 0 {
1730 continue;
1732 }
1733
1734 {
1735 let _locked = lock.lock();
1736 if !is_sleep.load(Ordering::Acquire) {
1737 is_sleep.store(true, Ordering::Release);
1739 }
1740 }
1741
1742 if get_queue_len() > 0 {
1743 is_sleep.store(false, Ordering::Release);
1745 continue;
1746 }
1747
1748 let mut locked = lock.lock();
1749 if is_sleep.load(Ordering::Acquire) {
1750 let _ = condvar.wait_for(
1751 &mut locked,
1752 Duration::from_millis(sleep_timeout),
1753 );
1754 }
1755 is_sleep.store(false, Ordering::Release);
1756
1757 continue; }
1759
1760 sleep_count += 1; if let Some(interval) = &loop_interval {
1762 if let Some(remaining_interval) = Duration::from_millis(*interval).checked_sub(run_time){
1764 thread::sleep(remaining_interval);
1766 }
1767 }
1768 } else {
1769 sleep_count = 0; if let Some(interval) = &loop_interval {
1772 if let Some(remaining_interval) = Duration::from_millis(*interval).checked_sub(run_time){
1774 thread::sleep(remaining_interval);
1776 }
1777 }
1778 }
1779 }
1780 });
1781
1782 thread_status_copy
1783}
1784
1785pub fn wakeup_worker_thread<O, P>(worker_waker: &Arc<(AtomicBool, Mutex<()>, Condvar)>,
1787 rt: &SingleTaskRuntime<O, P>)
1788 where O: Default + 'static,
1789 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P> {
1790 if worker_waker.0.load(Ordering::Relaxed) && rt.len() > 0 {
1792 let _ = wake_thread_waker(worker_waker);
1793 }
1794}