1use std::thread;
2use std::any::Any;
3use std::pin::Pin;
4use std::ptr::null_mut;
5use std::vec::IntoIter;
6use std::time::Duration;
7use std::future::Future;
8use std::marker::PhantomData;
9use std::ops::{Deref, DerefMut};
10use std::cell::{RefCell, UnsafeCell};
11use std::task::{Poll, Waker, Context};
12use std::io::{Error, Result, ErrorKind};
13use std::fmt::{Debug, Formatter, Result as FmtResult};
14use std::sync::{Arc, atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering}};
15
16use futures::{future::{FutureExt, LocalBoxFuture},
17 stream::{Stream, StreamExt, LocalBoxStream},
18 task::{ArcWake, AtomicWaker}};
19use parking_lot::{Mutex, Condvar};
20use crossbeam_queue::ArrayQueue;
21use crossbeam_channel::{Sender, Receiver, unbounded};
22use flume::{Sender as AsyncSender, Receiver as AsyncReceiver};
23#[cfg(not(target_arch = "wasm32"))]
24use polling::Poller;
25use num_cpus;
26
27use pi_cancel_timer::Timer;
28use slotmap::{Key, KeyData};
29use quanta::{Clock, Instant as QInstant};
30
31use crate::{lock::spin,
32 rt::{PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME, TaskId, AsyncPipelineResult,
33 TimeoutWaiter, wake_thread_waker, wake_waiting_worker,
34 ASYNC_VALUE_EMPTY, ASYNC_VALUE_WAITING, ASYNC_VALUE_SETTING,
35 ASYNC_VALUE_READY, ASYNC_VALUE_TAKING, ASYNC_VALUE_CONSUMED,
36 serial_local_thread::{LocalTaskRunner, LocalTaskRuntime},
37 serial_single_thread::SingleTaskRuntime,
38 serial_worker_thread::{WorkerTaskRunner, WorkerRuntime}}};
39
40pub struct AsyncTask<
44 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
45 O: Default + 'static = (),
46> {
47 uid: TaskId, future: Mutex<Option<LocalBoxFuture<'static, O>>>, pool: Arc<P>, priority: usize, context: Option<UnsafeCell<Box<dyn Any>>>, }
53
54unsafe impl<
55 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
56 O: Default + 'static,
57> Send for AsyncTask<P, O> {}
58unsafe impl<
59 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
60 O: Default + 'static,
61> Sync for AsyncTask<P, O> {}
62
63impl<
64 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P>,
65 O: Default + 'static,
66> ArcWake for AsyncTask<P, O> {
67 fn wake_by_ref(arc_self: &Arc<Self>) {
68 let pool = arc_self.get_pool();
69 let _ = pool.push_keep(arc_self.clone());
70
71 if let Some(waits) = pool.get_waits() {
72 let _ = wake_waiting_worker(waits);
74 } else {
75 if let Some(thread_waker) = pool.get_thread_waker() {
77 let _ = wake_thread_waker(thread_waker);
78 }
79 }
80 }
81}
82
83impl<
84 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P>,
85 O: Default + 'static,
86> AsyncTask<P, O> {
87 pub fn new(uid: TaskId,
89 pool: Arc<P>,
90 priority: usize,
91 future: Option<LocalBoxFuture<'static, O>>) -> AsyncTask<P, O> {
92 AsyncTask {
93 uid,
94 future: Mutex::new(future),
95 pool,
96 priority,
97 context: None,
98 }
99 }
100
101 pub fn with_context<C: 'static>(uid: TaskId,
103 pool: Arc<P>,
104 priority: usize,
105 future: Option<LocalBoxFuture<'static, O>>,
106 context: C) -> AsyncTask<P, O> {
107 let any = Box::new(context);
108
109 AsyncTask {
110 uid,
111 future: Mutex::new(future),
112 pool,
113 priority,
114 context: Some(UnsafeCell::new(any)),
115 }
116 }
117
118 pub fn with_runtime_and_context<RT, C>(runtime: &RT,
120 priority: usize,
121 future: Option<LocalBoxFuture<'static, O>>,
122 context: C) -> AsyncTask<P, O>
123 where RT: AsyncRuntime<O, Pool = P>,
124 C: 'static {
125 let any = Box::new(context);
126
127 AsyncTask {
128 uid: runtime.alloc::<O>(),
129 future: Mutex::new(future),
130 pool: runtime.shared_pool(),
131 priority,
132 context: Some(UnsafeCell::new(any)),
133 }
134 }
135
136 pub fn is_enable_wakeup(&self) -> bool {
138 self.uid.exist_waker::<O>()
139 }
140
141 pub fn get_inner(&self) -> Option<LocalBoxFuture<'static, O>> {
143 self.future.lock().take()
144 }
145
146 pub fn set_inner(&self, inner: Option<LocalBoxFuture<'static, O>>) {
148 *self.future.lock() = inner;
149 }
150
151 #[inline]
153 pub fn owner(&self) -> usize {
154 unsafe {
155 *self.uid.0.get() as usize
156 }
157 }
158
159 pub fn priority(&self) -> usize {
161 self.priority
162 }
163
164 pub fn exist_context(&self) -> bool {
166 self.context.is_some()
167 }
168
169 pub fn get_context<C: 'static>(&self) -> Option<&C> {
171 if let Some(context) = &self.context {
172 let any = unsafe { &*context.get() };
174 return <dyn Any>::downcast_ref::<C>(&**any);
175 }
176
177 None
178 }
179
180 pub fn get_context_mut<C: 'static>(&self) -> Option<&mut C> {
182 if let Some(context) = &self.context {
183 let any = unsafe { &mut *context.get() };
185 return <dyn Any>::downcast_mut::<C>(&mut **any);
186 }
187
188 None
189 }
190
191 pub fn set_context<C: 'static>(&self, new: C) {
193 if let Some(context) = &self.context {
194 let _ = unsafe { &*context.get() };
196
197 let any: Box<dyn Any + 'static> = Box::new(new);
199 unsafe { *context.get() = any; }
200 }
201 }
202
203 pub fn get_pool(&self) -> &P {
205 self.pool.as_ref()
206 }
207}
208
209pub trait AsyncTaskPool<O: Default + 'static = ()>: Default + 'static {
213 type Pool: AsyncTaskPoolExt<O> + AsyncTaskPool<O>;
214
215 fn get_thread_id(&self) -> usize;
217
218 fn len(&self) -> usize;
220
221 fn push(&self, task: Arc<AsyncTask<Self::Pool, O>>) -> Result<()>;
223
224 fn push_local(&self, task: Arc<AsyncTask<Self::Pool, O>>) -> Result<()>;
226
227 fn push_priority(&self, priority: usize, task: Arc<AsyncTask<Self::Pool, O>>) -> Result<()>;
229
230 fn push_keep(&self, task: Arc<AsyncTask<Self::Pool, O>>) -> Result<()>;
232
233 fn try_pop(&self) -> Option<Arc<AsyncTask<Self::Pool, O>>>;
235
236 fn try_pop_all(&self) -> IntoIter<Arc<AsyncTask<Self::Pool, O>>>;
238
239 fn get_thread_waker(&self) -> Option<&Arc<(AtomicBool, Mutex<()>, Condvar)>> {
241 None
242 }
243}
244
245pub trait AsyncTaskPoolExt<O: Default + 'static = ()>: 'static {
249 fn set_waits(&mut self,
251 _waits: Arc<ArrayQueue<Arc<(AtomicBool, Mutex<()>, Condvar)>>>) {}
252
253 fn get_waits(&self) -> Option<&Arc<ArrayQueue<Arc<(AtomicBool, Mutex<()>, Condvar)>>>> {
255 None
257 }
258
259 fn idler_len(&self) -> usize {
261 0
263 }
264
265 fn spawn_worker(&self) -> Option<usize> {
267 None
269 }
270
271 fn worker_len(&self) -> usize {
273 #[cfg(not(target_arch = "wasm32"))]
275 return num_cpus::get();
276 #[cfg(target_arch = "wasm32")]
277 return 1;
278 }
279
280 fn buffer_len(&self) -> usize {
282 0
284 }
285
286 fn set_thread_waker(&mut self, _thread_waker: Arc<(AtomicBool, Mutex<()>, Condvar)>) {
288 }
290
291 fn clone_thread_waker(&self) -> Option<Arc<(AtomicBool, Mutex<()>, Condvar)>> {
293 None
295 }
296
297 fn close_worker(&self) {
299 }
301}
302
303pub trait AsyncRuntime<O: Default + 'static = ()>: Clone + Send + Sync + 'static {
307 type Pool: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = Self::Pool>;
308
309 fn shared_pool(&self) -> Arc<Self::Pool>;
311
312 fn get_id(&self) -> usize;
314
315 fn wait_len(&self) -> usize;
317
318 fn len(&self) -> usize;
320
321 fn alloc<R: 'static>(&self) -> TaskId;
323
324 fn spawn<F>(&self, future: F) -> Result<TaskId>
326 where F: Future<Output = O> + 'static;
327
328 fn spawn_local<F>(&self, future: F) -> Result<TaskId>
330 where F: Future<Output = O> + 'static;
331
332 fn spawn_priority<F>(&self, priority: usize, future: F) -> Result<TaskId>
334 where F: Future<Output = O> + 'static;
335
336 fn spawn_yield<F>(&self, future: F) -> Result<TaskId>
338 where F: Future<Output = O> + 'static;
339
340 fn spawn_timing<F>(&self, future: F, time: usize) -> Result<TaskId>
342 where F: Future<Output = O> + 'static;
343
344 fn spawn_by_id<F>(&self, task_id: TaskId, future: F) -> Result<()>
346 where F: Future<Output = O> + 'static;
347
348 fn spawn_local_by_id<F>(&self, task_id: TaskId, future: F) -> Result<()>
350 where F: Future<Output = O> + 'static;
351
352 fn spawn_priority_by_id<F>(&self,
354 task_id: TaskId,
355 priority: usize,
356 future: F) -> Result<()>
357 where F: Future<Output = O> + 'static;
358
359 fn spawn_yield_by_id<F>(&self, task_id: TaskId, future: F) -> Result<()>
361 where F: Future<Output = O> + 'static;
362
363 fn spawn_timing_by_id<F>(&self,
365 task_id: TaskId,
366 future: F,
367 time: usize) -> Result<()>
368 where F: Future<Output = O> + 'static;
369
370 fn pending<Output: 'static>(&self, task_id: &TaskId, waker: Waker) -> Poll<Output>;
372
373 fn wakeup<Output: 'static>(&self, task_id: &TaskId);
375
376 fn wait<V: 'static>(&self) -> AsyncWait<V>;
378
379 fn wait_any<V: 'static>(&self, capacity: usize) -> AsyncWaitAny<V>;
381
382 fn wait_any_callback<V: 'static>(&self, capacity: usize) -> AsyncWaitAnyCallback<V>;
384
385 fn map_reduce<V: 'static>(&self, capacity: usize) -> AsyncMapReduce<V>;
387
388 fn timeout(&self, timeout: usize) -> LocalBoxFuture<'static, ()>;
390
391 fn yield_now(&self) -> LocalBoxFuture<'static, ()>;
393
394 fn pipeline<S, SO, F, FO>(&self, input: S, filter: F) -> LocalBoxStream<'static, FO>
396 where S: Stream<Item = SO> + 'static,
397 SO: 'static,
398 F: FnMut(SO) -> AsyncPipelineResult<FO> + 'static,
399 FO: 'static;
400
401 fn close(&self) -> bool;
403}
404
405pub trait AsyncRuntimeExt<O: Default + 'static = ()> {
409 fn spawn_with_context<F, C>(&self,
411 task_id: TaskId,
412 future: F,
413 context: C) -> Result<()>
414 where F: Future<Output = O> + 'static,
415 C: 'static;
416
417 fn spawn_timing_with_context<F, C>(&self,
419 task_id: TaskId,
420 future: F,
421 context: C,
422 time: usize) -> Result<()>
423 where F: Future<Output = O> + 'static,
424 C: 'static;
425
426 fn block_on<F>(&self, future: F) -> Result<F::Output>
428 where F: Future + 'static,
429 <F as Future>::Output: Default + 'static;
430}
431
432pub struct AsyncRuntimeBuilder<O: Default + 'static = ()>(PhantomData<O>);
436
437impl<O: Default + 'static> AsyncRuntimeBuilder<O> {
438 pub fn default_local_thread(name: Option<&str>,
440 stack_size: Option<usize>) -> LocalTaskRuntime<O> {
441 let runner = LocalTaskRunner::new();
442
443 let thread_name = if let Some(name) = name {
444 name
445 } else {
446 "Default-Local-RT"
448 };
449 let thread_stack_size = if let Some(size) = stack_size {
450 size
451 } else {
452 2 * 1024 * 1024
454 };
455
456 runner.startup(thread_name, thread_stack_size)
457 }
458
459 pub fn default_worker_thread(worker_name: Option<&str>,
461 worker_stack_size: Option<usize>,
462 worker_sleep_timeout: Option<u64>,
463 worker_loop_interval: Option<Option<u64>>) -> WorkerRuntime<O> {
464 let runner = WorkerTaskRunner::default();
465
466 let thread_name = if let Some(name) = worker_name {
467 name
468 } else {
469 "Default-Single-Worker"
471 };
472 let thread_stack_size = if let Some(size) = worker_stack_size {
473 size
474 } else {
475 2 * 1024 * 1024
477 };
478 let sleep_timeout = if let Some(timeout) = worker_sleep_timeout {
479 timeout
480 } else {
481 1
483 };
484 let loop_interval = if let Some(interval) = worker_loop_interval {
485 interval
486 } else {
487 None
489 };
490
491 let clock = Clock::new();
493 let runner_copy = runner.clone();
494 let rt_copy = runner.get_runtime();
495 let rt = runner.startup(
496 thread_name,
497 thread_stack_size,
498 sleep_timeout,
499 loop_interval,
500 move || {
501 let now = clock.recent();
502 match runner_copy.run_once() {
503 Err(e) => {
504 panic!("Run runner failed, reason: {:?}", e);
505 },
506 Ok(len) => {
507 (len == 0,
508 clock
509 .recent()
510 .duration_since(now))
511 },
512 }
513 },
514 move || {
515 rt_copy.wait_len() + rt_copy.len()
516 },
517 );
518
519 rt
520 }
521
522 #[cfg(not(target_arch = "wasm32"))]
524 pub fn custom_local_thread(name: Option<&str>,
525 stack_size: Option<usize>,
526 poller: Option<Arc<Poller>>,
527 try_count: Option<usize>,
528 timeout: Option<Duration>,) -> LocalTaskRuntime<O> {
529 let poller = if let Some(poller) = poller {
530 poller
531 } else {
532 Arc::new(Poller::new().expect("Failed to create poller"))
533 };
534 let runner = LocalTaskRunner::with_poll(poller);
535
536 let thread_name = if let Some(name) = name {
537 name
538 } else {
539 "Custom-Local-RT"
541 };
542 let thread_stack_size = if let Some(size) = stack_size {
543 size
544 } else {
545 2 * 1024 * 1024
547 };
548 let try_count = try_count.unwrap_or(3);
549
550 runner.startup_with_poll(
551 thread_name,
552 thread_stack_size,
553 try_count,
554 timeout
555 )
556 }
557
558 pub fn custom_worker_thread<P, F0, F1>(pool: P,
560 worker_handle: Arc<AtomicBool>,
561 worker_condvar: Arc<(AtomicBool, Mutex<()>, Condvar)>,
562 thread_name: &str,
563 thread_stack_size: usize,
564 sleep_timeout: u64,
565 loop_interval: Option<u64>,
566 loop_func: F0,
567 get_queue_len: F1) -> WorkerRuntime<O, P>
568 where P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P>,
569 F0: Fn() -> (bool, Duration) + Send + 'static,
570 F1: Fn() -> usize + Send + 'static {
571 let runner = WorkerTaskRunner::new(pool,
572 worker_handle,
573 worker_condvar);
574
575 let rt_copy = runner.get_runtime();
577 let rt = runner.startup(
578 thread_name,
579 thread_stack_size,
580 sleep_timeout,
581 loop_interval,
582 loop_func,
583 move || {
584 rt_copy.wait_len() + get_queue_len()
585 },
586 );
587
588 rt
589 }
590}
591
592pub fn bind_local_thread<O: Default + 'static>(runtime: LocalAsyncRuntime<O>) {
594 match PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME.try_with(move |rt| {
595 let raw = Arc::into_raw(Arc::new(runtime)) as *mut LocalAsyncRuntime<O> as *mut ();
596 rt.store(raw, Ordering::Relaxed);
597 }) {
598 Err(e) => {
599 panic!("Bind single runtime to local thread failed, reason: {:?}", e);
600 },
601 Ok(_) => (),
602 }
603}
604
605pub fn unbind_local_thread() {
607 let _ = PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME.try_with(move |rt| {
608 rt.store(null_mut(), Ordering::Relaxed);
609 });
610}
611
612pub struct LocalAsyncRuntime<O: Default + 'static> {
616 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, ()>, }
623
624unsafe impl<O: Default + 'static> Send for LocalAsyncRuntime<O> {}
625unsafe impl<O: Default + 'static> Sync for LocalAsyncRuntime<O> {}
626
627impl<O: Default + 'static> LocalAsyncRuntime<O> {
628 pub fn new(inner: *const (),
630 get_id_func: fn(*const ()) -> usize,
631 spawn_func: fn(*const (), LocalBoxFuture<'static, O>) -> Result<()>,
632 spawn_timing_func: fn(*const (), LocalBoxFuture<'static, O>, usize) -> Result<()>,
633 timeout_func: fn(*const (), usize) -> LocalBoxFuture<'static, ()>) -> Self {
634 LocalAsyncRuntime {
635 inner,
636 get_id_func,
637 spawn_func,
638 spawn_local_func: spawn_func,
639 spawn_timing_func,
640 timeout_func,
641 }
642 }
643
644 #[inline]
646 pub fn get_id(&self) -> usize {
647 (self.get_id_func)(self.inner)
648 }
649
650 #[inline]
652 pub fn spawn<F>(&self, future: F) -> Result<()>
653 where F: Future<Output = O> + 'static {
654 (self.spawn_func)(self.inner, async move {
655 future.await
656 }.boxed_local())
657 }
658
659 #[inline]
661 pub fn spawn_local<F>(&self, future: F) -> Result<()>
662 where F: Future<Output = O> + 'static {
663 (self.spawn_local_func)(self.inner, async move {
664 future.await
665 }.boxed_local())
666 }
667
668 #[inline]
670 pub fn sapwn_timing_func<F>(&self, future: F, timeout: usize) -> Result<()>
671 where F: Future<Output = O> + 'static {
672 (self.spawn_timing_func)(self.inner,
673 async move {
674 future.await
675 }.boxed_local(),
676 timeout)
677 }
678
679 #[inline]
681 pub fn timeout(&self, timeout: usize) -> LocalBoxFuture<'static, ()> {
682 (self.timeout_func)(self.inner, timeout)
683 }
684}
685
686pub fn local_serial_async_runtime<O: Default + 'static>() -> Option<Arc<LocalAsyncRuntime<O>>> {
691 match PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME.try_with(move |ptr| {
692 let raw = ptr.load(Ordering::Relaxed) as *const LocalAsyncRuntime<O>;
693 unsafe {
694 if raw.is_null() {
695 None
697 } else {
698 let shared: Arc<LocalAsyncRuntime<O>> = unsafe { Arc::from_raw(raw) };
700 let result = shared.clone();
701 Arc::into_raw(shared); Some(result)
703 }
704 }
705 }) {
706 Err(_) => None, Ok(rt) => rt,
708 }
709}
710
711pub fn spawn_local<O, F>(future: F) -> Result<()>
716 where O: Default + 'static,
717 F: Future<Output = O> + 'static {
718 if let Some(rt) = local_serial_async_runtime::<O>() {
719 rt.spawn(future)
720 } else {
721 Err(Error::new(ErrorKind::Other, format!("Spawn task to local thread failed, reason: runtime not exist")))
722 }
723}
724
725pub fn local_async_runtime<O: Default + 'static>() -> Option<Arc<LocalAsyncRuntime<O>>> {
730 match PI_ASYNC_LOCAL_THREAD_ASYNC_RUNTIME.try_with(move |ptr| {
731 let raw = ptr.load(Ordering::Relaxed) as *const LocalAsyncRuntime<O>;
732 unsafe {
733 if raw.is_null() {
734 None
736 } else {
737 let shared: Arc<LocalAsyncRuntime<O>> = unsafe { Arc::from_raw(raw) };
739 let result = shared.clone();
740 Arc::into_raw(shared); Some(result)
742 }
743 }
744 }) {
745 Err(_) => None, Ok(rt) => rt,
747 }
748}
749
750pub struct AsyncValue<V: 'static>(Arc<InnerAsyncValue<V>>);
771
772unsafe impl<V: 'static> Send for AsyncValue<V> {}
773unsafe impl<V: 'static> Sync for AsyncValue<V> {}
774
775impl<V: 'static> Clone for AsyncValue<V> {
776 fn clone(&self) -> Self {
777 AsyncValue(self.0.clone())
778 }
779}
780
781impl<V: Send + 'static> Debug for AsyncValue<V> {
782 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
783 write!(f,
784 "AsyncValue[status = {}]",
785 self.0.status.load(Ordering::Acquire))
786 }
787}
788
789impl<V: 'static> Future for AsyncValue<V> {
790 type Output = V;
791
792 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
793 let mut spin_len = 1;
794 loop {
795 match self.0.status.load(Ordering::Acquire) {
796 ASYNC_VALUE_EMPTY => {
797 self.0.waker.register(cx.waker());
798 match self.0.status.compare_exchange(ASYNC_VALUE_EMPTY,
799 ASYNC_VALUE_WAITING,
800 Ordering::AcqRel,
801 Ordering::Acquire) {
802 Ok(_) => {
803 return Poll::Pending;
804 },
805 Err(ASYNC_VALUE_EMPTY) => {
806 continue;
807 },
808 Err(ASYNC_VALUE_WAITING) | Err(ASYNC_VALUE_SETTING) => {
809 return Poll::Pending;
810 },
811 Err(ASYNC_VALUE_READY) => {
812 continue;
813 },
814 Err(ASYNC_VALUE_TAKING) => {
815 spin_len = spin(spin_len);
816 continue;
817 },
818 Err(ASYNC_VALUE_CONSUMED) => {
819 panic!("AsyncValue polled after completion");
820 },
821 Err(_) => {
822 panic!("AsyncValue entered invalid state");
823 },
824 }
825 },
826 ASYNC_VALUE_WAITING | ASYNC_VALUE_SETTING => {
827 self.0.waker.register(cx.waker());
828 match self.0.status.load(Ordering::Acquire) {
829 ASYNC_VALUE_READY => {
830 continue;
831 },
832 ASYNC_VALUE_TAKING => {
833 spin_len = spin(spin_len);
834 continue;
835 },
836 ASYNC_VALUE_CONSUMED => {
837 panic!("AsyncValue polled after completion");
838 },
839 _ => {
840 return Poll::Pending;
841 },
842 }
843 },
844 ASYNC_VALUE_READY => {
845 match self.0.status.compare_exchange(ASYNC_VALUE_READY,
846 ASYNC_VALUE_TAKING,
847 Ordering::AcqRel,
848 Ordering::Acquire) {
849 Ok(_) => {
850 let value = unsafe { (*self.0.value.get()).take().unwrap() };
851 self.0.status.store(ASYNC_VALUE_CONSUMED, Ordering::Release);
852 return Poll::Ready(value);
853 },
854 Err(ASYNC_VALUE_TAKING) => {
855 spin_len = spin(spin_len);
856 continue;
857 },
858 Err(ASYNC_VALUE_CONSUMED) => {
859 panic!("AsyncValue polled after completion");
860 },
861 Err(_) => {
862 continue;
863 },
864 }
865 },
866 ASYNC_VALUE_TAKING => {
867 spin_len = spin(spin_len);
869 continue;
870 },
871 ASYNC_VALUE_CONSUMED => {
872 panic!("AsyncValue polled after completion");
873 },
874 _ => {
875 panic!("AsyncValue entered invalid state");
876 },
877 }
878 }
879 }
880}
881
882impl<V: 'static> AsyncValue<V> {
886 pub fn new() -> Self {
888 let inner = InnerAsyncValue {
889 value: UnsafeCell::new(None),
890 waker: AtomicWaker::new(),
891 status: AtomicU8::new(ASYNC_VALUE_EMPTY),
892 };
893
894 AsyncValue(Arc::new(inner))
895 }
896
897 pub fn is_complete(&self) -> bool {
899 match self.0.status.load(Ordering::Acquire) {
900 ASYNC_VALUE_READY | ASYNC_VALUE_TAKING | ASYNC_VALUE_CONSUMED => true,
901 _ => false,
902 }
903 }
904
905 pub fn set(self, value: V) {
907 let mut value = Some(value);
908 loop {
909 match self.0.status.load(Ordering::Acquire) {
910 ASYNC_VALUE_EMPTY => {
911 match self.0.status.compare_exchange(ASYNC_VALUE_EMPTY,
912 ASYNC_VALUE_SETTING,
913 Ordering::AcqRel,
914 Ordering::Acquire) {
915 Ok(_) => {
916 unsafe { *self.0.value.get() = value.take(); }
917 self.0.status.store(ASYNC_VALUE_READY, Ordering::Release);
918 self.0.waker.wake();
919 return;
920 },
921 Err(_) => {
922 continue;
923 },
924 }
925 },
926 ASYNC_VALUE_WAITING => {
927 match self.0.status.compare_exchange(ASYNC_VALUE_WAITING,
928 ASYNC_VALUE_SETTING,
929 Ordering::AcqRel,
930 Ordering::Acquire) {
931 Ok(_) => {
932 unsafe { *self.0.value.get() = value.take(); }
933 self.0.status.store(ASYNC_VALUE_READY, Ordering::Release);
934 self.0.waker.wake();
935 return;
936 },
937 Err(_) => {
938 continue;
939 },
940 }
941 },
942 _ => {
943 return;
945 },
946 }
947 }
948 }
949}
950
951pub struct InnerAsyncValue<V: 'static> {
953 value: UnsafeCell<Option<V>>, waker: AtomicWaker, status: AtomicU8, }
957
958pub struct AsyncVariableGuard<'a, V: 'static> {
962 value: &'a UnsafeCell<Option<V>>, waker: &'a UnsafeCell<Option<Waker>>, status: &'a AtomicU8, }
966
967unsafe impl<V: 'static> Send for AsyncVariableGuard<'_, V> {}
968
969impl<V: 'static> Drop for AsyncVariableGuard<'_, V> {
970 fn drop(&mut self) {
971 self.status.fetch_sub(2, Ordering::Relaxed);
975 }
976}
977
978impl<V: 'static> Deref for AsyncVariableGuard<'_, V> {
979 type Target = Option<V>;
980
981 fn deref(&self) -> &Self::Target {
982 unsafe {
983 &*self.value.get()
984 }
985 }
986}
987
988impl<V: 'static> DerefMut for AsyncVariableGuard<'_, V> {
989 fn deref_mut(&mut self) -> &mut Self::Target {
990 unsafe {
991 &mut *self.value.get()
992 }
993 }
994}
995
996impl<V: 'static> AsyncVariableGuard<'_, V> {
997 pub fn finish(self) {
999 if self.status.fetch_add(4, Ordering::Relaxed) == 3 {
1001 if let Some(waker) = unsafe { (&mut *self.waker.get()).take() } {
1002 waker.wake();
1004 }
1005 }
1006 }
1007}
1008
1009pub struct AsyncVariable<V: 'static>(Arc<InnerAsyncVariable<V>>);
1013
1014unsafe impl<V: 'static> Send for AsyncVariable<V> {}
1015unsafe impl<V: 'static> Sync for AsyncVariable<V> {}
1016
1017impl<V: 'static> Clone for AsyncVariable<V> {
1018 fn clone(&self) -> Self {
1019 AsyncVariable(self.0.clone())
1020 }
1021}
1022
1023impl<V: 'static> Future for AsyncVariable<V> {
1024 type Output = V;
1025
1026 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1027 unsafe {
1028 *self.0.waker.get() = Some(cx.waker().clone()); }
1030
1031 let mut spin_len = 1;
1032 loop {
1033 match self.0.status.compare_exchange(0,
1034 1,
1035 Ordering::Acquire,
1036 Ordering::Relaxed) {
1037 Err(current) if current & 4 != 0 => {
1038 unsafe {
1040 let _ = (&mut *self.0.waker.get()).take(); return Poll::Ready((&mut *(&self).0.value.get()).take().unwrap());
1042 }
1043 },
1044 Err(_) => {
1045 spin_len = spin(spin_len);
1047 },
1048 Ok(_) => {
1049 return Poll::Pending;
1051 },
1052 }
1053 }
1054 }
1055}
1056
1057impl<V: 'static> AsyncVariable<V> {
1058 pub fn new() -> Self {
1060 let inner = InnerAsyncVariable {
1061 value: UnsafeCell::new(None),
1062 waker: UnsafeCell::new(None),
1063 status: AtomicU8::new(0),
1064 };
1065
1066 AsyncVariable(Arc::new(inner))
1067 }
1068
1069 pub fn is_complete(&self) -> bool {
1071 self
1072 .0
1073 .status
1074 .load(Ordering::Acquire) & 4 != 0
1075 }
1076
1077 pub fn lock(&self) -> Option<AsyncVariableGuard<V>> {
1079 let mut spin_len = 1;
1080 loop {
1081 match self
1082 .0
1083 .status
1084 .compare_exchange(1,
1085 3,
1086 Ordering::Acquire,
1087 Ordering::Relaxed) {
1088 Err(0) => {
1089 match self
1091 .0
1092 .status
1093 .compare_exchange(0,
1094 2,
1095 Ordering::Acquire,
1096 Ordering::Relaxed) {
1097 Err(1) => {
1098 continue;
1100 },
1101 Err(2) => {
1102 spin_len = spin(spin_len);
1104 },
1105 Err(3) => {
1106 spin_len = spin(spin_len);
1108 },
1109 Err(_) => {
1110 return None;
1112 },
1113 Ok(_) => {
1114 let guard = AsyncVariableGuard {
1116 value: &self.0.value,
1117 waker: &self.0.waker,
1118 status: &self.0.status,
1119 };
1120
1121 return Some(guard)
1122 },
1123 }
1124 },
1125 Err(2) => {
1126 spin_len = spin(spin_len);
1128 },
1129 Err(3) => {
1130 spin_len = spin(spin_len);
1132 },
1133 Err(_) => {
1134 return None;
1136 }
1137 Ok(_) => {
1138 let guard = AsyncVariableGuard {
1140 value: &self.0.value,
1141 waker: &self.0.waker,
1142 status: &self.0.status,
1143 };
1144
1145 return Some(guard)
1146 },
1147 }
1148 }
1149 }
1150}
1151
1152pub struct InnerAsyncVariable<V: 'static> {
1154 value: UnsafeCell<Option<V>>, waker: UnsafeCell<Option<Waker>>, status: AtomicU8, }
1158
1159pub struct AsyncWaitResult<V: 'static>(pub Arc<RefCell<Option<Result<V>>>>);
1163
1164unsafe impl<V: 'static> Send for AsyncWaitResult<V> {}
1165unsafe impl<V: 'static> Sync for AsyncWaitResult<V> {}
1166
1167impl<V: 'static> Clone for AsyncWaitResult<V> {
1168 fn clone(&self) -> Self {
1169 AsyncWaitResult(self.0.clone())
1170 }
1171}
1172
1173pub struct AsyncWaitResults<V: 'static>(pub Arc<RefCell<Option<Vec<Result<V>>>>>);
1177
1178unsafe impl<V: 'static> Send for AsyncWaitResults<V> {}
1179unsafe impl<V: 'static> Sync for AsyncWaitResults<V> {}
1180
1181impl<V: 'static> Clone for AsyncWaitResults<V> {
1182 fn clone(&self) -> Self {
1183 AsyncWaitResults(self.0.clone())
1184 }
1185}
1186
1187pub enum AsyncTimingTask<
1191 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1192 O: Default + 'static = (),
1193> {
1194 Pended(TaskId), WaitRun(Arc<AsyncTask<P, O>>), TimeoutWake(Arc<TimeoutWaiter>), }
1198
1199pub struct AsyncTaskTimer<
1203 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1204 O: Default + 'static = (),
1205> {
1206 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, }
1212
1213unsafe impl<
1214 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1215 O: Default + 'static,
1216> Send for AsyncTaskTimer<P, O> {}
1217unsafe impl<
1218 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1219 O: Default + 'static,
1220> Sync for AsyncTaskTimer<P, O> {}
1221
1222impl<
1223 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1224 O: Default + 'static,
1225> AsyncTaskTimer<P, O> {
1226 pub fn new() -> Self {
1228 let (producor, consumer) = unbounded();
1229 let clock = Clock::new();
1230 let now = clock.recent();
1231
1232 AsyncTaskTimer {
1233 producor,
1234 consumer,
1235 timer: Arc::new(RefCell::new(Timer::<AsyncTimingTask<P, O>, 1000, 60, 3>::default())),
1236 clock,
1237 now,
1238 }
1239 }
1240
1241 #[inline]
1243 pub fn get_producor(&self) -> &Sender<(usize, AsyncTimingTask<P, O>)> {
1244 &self.producor
1245 }
1246
1247 #[inline]
1249 pub fn len(&self) -> usize {
1250 let timer = self.timer.as_ref().borrow();
1251 timer.add_count() - timer.remove_count()
1252 }
1253
1254 pub fn set_timer(&self, task: AsyncTimingTask<P, O>, timeout: usize) -> usize {
1256 let current_time = self
1257 .clock
1258 .recent()
1259 .duration_since(self.now)
1260 .as_millis() as u64;
1261 self
1262 .timer
1263 .borrow_mut()
1264 .push_time(current_time + timeout as u64, task)
1265 .data()
1266 .as_ffi() as usize
1267 }
1268
1269 pub fn cancel_timer(&self, timer_ref: usize) -> Option<AsyncTimingTask<P, O>> {
1271 if let Some(item) =self
1272 .timer
1273 .borrow_mut()
1274 .cancel(KeyData::from_ffi(timer_ref as u64).into()) {
1275 Some(item)
1276 } else {
1277 None
1278 }
1279 }
1280
1281 pub fn consume(&self) -> usize {
1283 let mut len = 0;
1284 let timer_tasks = self.consumer.try_iter().collect::<Vec<(usize, AsyncTimingTask<P, O>)>>();
1285 for (timeout, task) in timer_tasks {
1286 self.set_timer(task, timeout);
1287 len += 1;
1288 }
1289
1290 len
1291 }
1292
1293 pub fn is_require_pop(&self) -> Option<u64> {
1295 let current_time = self
1296 .clock
1297 .recent()
1298 .duration_since(self.now)
1299 .as_millis() as u64;
1300 if self.timer.borrow_mut().is_ok(current_time) {
1301 Some(current_time)
1302 } else {
1303 None
1304 }
1305 }
1306
1307 pub fn pop(&self, current_time: u64) -> Option<(usize, AsyncTimingTask<P, O>)> {
1309 if let Some((key, item)) = self.timer.borrow_mut().pop_kv(current_time) {
1310 Some((key.data().as_ffi() as usize, item))
1311 } else {
1312 None
1313 }
1314 }
1315}
1316
1317pub struct AsyncWaitTimeout<
1321 RT: AsyncRuntime<O>,
1322 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1323 O: Default + 'static = (),
1324> {
1325 rt: RT, producor: Sender<(usize, AsyncTimingTask<P, O>)>, timeout: usize, registered: AtomicBool, waiter: Arc<TimeoutWaiter>, }
1331
1332unsafe impl<
1333 RT: AsyncRuntime<O>,
1334 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1335 O: Default + 'static,
1336> Send for AsyncWaitTimeout<RT, P, O> {}
1337unsafe impl<
1338 RT: AsyncRuntime<O>,
1339 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1340 O: Default + 'static,
1341> Sync for AsyncWaitTimeout<RT, P, O> {}
1342
1343impl<
1344 RT: AsyncRuntime<O>,
1345 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1346 O: Default + 'static,
1347> Future for AsyncWaitTimeout<RT, P, O> {
1348 type Output = ();
1349
1350 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1351 if self.waiter.is_fired() {
1352 return Poll::Ready(());
1354 }
1355
1356 self.waiter.register(cx.waker());
1357
1358 if !self.registered.swap(true, Ordering::AcqRel) {
1359 let _ = self
1361 .producor
1362 .send((self.timeout, AsyncTimingTask::TimeoutWake(self.waiter.clone())));
1363 }
1364
1365 if self.waiter.is_fired() {
1366 Poll::Ready(())
1367 } else {
1368 Poll::Pending
1369 }
1370 }
1371}
1372
1373impl<
1374 RT: AsyncRuntime<O>,
1375 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1376 O: Default + 'static,
1377> Drop for AsyncWaitTimeout<RT, P, O> {
1378 fn drop(&mut self) {
1379 self.waiter.clear_waker();
1380 }
1381}
1382
1383impl<
1384 RT: AsyncRuntime<O>,
1385 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O>,
1386 O: Default + 'static,
1387> AsyncWaitTimeout<RT, P, O> {
1388 pub fn new(rt: RT,
1390 producor: Sender<(usize, AsyncTimingTask<P, O>)>,
1391 timeout: usize) -> Self {
1392 AsyncWaitTimeout {
1393 rt,
1394 producor,
1395 timeout,
1396 registered: AtomicBool::new(false), waiter: Arc::new(TimeoutWaiter::new()),
1398 }
1399 }
1400}
1401
1402pub struct AsyncWait<V: 'static>(AsyncWaitAny<V>);
1406
1407unsafe impl<V: 'static> Send for AsyncWait<V> {}
1408unsafe impl<V: 'static> Sync for AsyncWait<V> {}
1409
1410impl<V: 'static> AsyncWait<V> {
1414 pub(crate) fn new(inner: AsyncWaitAny<V>) -> Self {
1416 AsyncWait(inner)
1417 }
1418
1419 pub fn spawn<RT, O, F>(&self,
1421 rt: RT,
1422 timeout: Option<usize>,
1423 future: F) -> Result<()>
1424 where RT: AsyncRuntime<O>,
1425 O: Default + 'static,
1426 F: Future<Output = Result<V>> + 'static {
1427 self.0.spawn(rt.clone(), future)?;
1428
1429 if let Some(timeout) = timeout {
1430 let rt_copy = rt.clone();
1432 self.0.spawn(rt, async move {
1433 rt_copy.timeout(timeout).await;
1434
1435 Err(Error::new(ErrorKind::TimedOut, format!("Time out")))
1437 })
1438 } else {
1439 Ok(())
1441 }
1442 }
1443
1444 pub fn spawn_local<O, F>(&self,
1446 timeout: Option<usize>,
1447 future: F) -> Result<()>
1448 where O: Default + 'static,
1449 F: Future<Output = Result<V>> + 'static {
1450 if let Some(rt) = local_serial_async_runtime::<O>() {
1451 self.0.spawn_local(future)?;
1453
1454 if let Some(timeout) = timeout {
1455 let rt_copy = rt.clone();
1457 self.0.spawn_local(async move {
1458 rt_copy.timeout(timeout).await;
1459
1460 Err(Error::new(ErrorKind::TimedOut, format!("Time out")))
1462 })
1463 } else {
1464 Ok(())
1466 }
1467 } else {
1468 Err(Error::new(ErrorKind::Other, format!("Spawn wait task failed, reason: local async runtime not exist")))
1470 }
1471 }
1472}
1473
1474impl<V: 'static> AsyncWait<V> {
1478 pub async fn wait_result(self) -> Result<V> {
1480 self.0.wait_result().await
1481 }
1482}
1483
1484pub struct AsyncWaitAny<V: 'static> {
1488 capacity: usize, producor: AsyncSender<Result<V>>, consumer: AsyncReceiver<Result<V>>, }
1492
1493unsafe impl<V: 'static> Send for AsyncWaitAny<V> {}
1494unsafe impl<V: 'static> Sync for AsyncWaitAny<V> {}
1495
1496impl<V: 'static> AsyncWaitAny<V> {
1500 pub(crate) fn new(capacity: usize,
1502 producor: AsyncSender<Result<V>>,
1503 consumer: AsyncReceiver<Result<V>>) -> Self {
1504 AsyncWaitAny {
1505 capacity,
1506 producor,
1507 consumer,
1508 }
1509 }
1510
1511 pub fn spawn<RT, O, F>(&self,
1513 rt: RT,
1514 future: F) -> Result<()>
1515 where RT: AsyncRuntime<O>,
1516 O: Default + 'static,
1517 F: Future<Output = Result<V>> + 'static {
1518 let producor = self.producor.clone();
1519 rt.spawn_by_id(rt.alloc::<O>(), async move {
1520 let value = future.await;
1521 producor.into_send_async(value).await;
1522
1523 Default::default()
1525 })
1526 }
1527
1528 pub fn spawn_local<F>(&self,
1530 future: F) -> Result<()>
1531 where F: Future<Output = Result<V>> + 'static {
1532 if let Some(rt) = local_serial_async_runtime() {
1533 let producor = self.producor.clone();
1535 rt.spawn(async move {
1536 let value = future.await;
1537 producor.into_send_async(value).await;
1538 })
1539 } else {
1540 Err(Error::new(ErrorKind::Other, format!("Spawn wait any task failed, reason: local async runtime not exist")))
1542 }
1543 }
1544}
1545
1546impl<V: 'static> AsyncWaitAny<V> {
1550 pub async fn wait_result(self) -> Result<V> {
1552 match self.consumer.recv_async().await {
1553 Err(e) => {
1554 Err(Error::new(ErrorKind::Other, format!("Wait any result failed, reason: {:?}", e)))
1556 },
1557 Ok(result) => {
1558 result
1560 },
1561 }
1562 }
1563}
1564
1565pub struct AsyncWaitAnyCallback<V: 'static> {
1569 capacity: usize, producor: AsyncSender<Result<V>>, consumer: AsyncReceiver<Result<V>>, }
1573
1574unsafe impl<V: 'static> Send for AsyncWaitAnyCallback<V> {}
1575unsafe impl<V: 'static> Sync for AsyncWaitAnyCallback<V> {}
1576
1577impl<V: 'static> AsyncWaitAnyCallback<V> {
1581 pub(crate) fn new(capacity: usize,
1583 producor: AsyncSender<Result<V>>,
1584 consumer: AsyncReceiver<Result<V>>) -> Self {
1585 AsyncWaitAnyCallback {
1586 capacity,
1587 producor,
1588 consumer,
1589 }
1590 }
1591
1592 pub fn spawn<RT, O, F>(&self,
1594 rt: RT,
1595 future: F) -> Result<()>
1596 where RT: AsyncRuntime<O>,
1597 O: Default + 'static,
1598 F: Future<Output = Result<V>> + 'static {
1599 let producor = self.producor.clone();
1600 rt.spawn_by_id(rt.alloc::<O>(), async move {
1601 let value = future.await;
1602 producor.into_send_async(value).await;
1603
1604 Default::default()
1606 })
1607 }
1608
1609 pub fn spawn_local<F>(&self,
1611 future: F) -> Result<()>
1612 where F: Future<Output = Result<V>> + 'static {
1613 if let Some(rt) = local_serial_async_runtime() {
1614 let producor = self.producor.clone();
1616 rt.spawn(async move {
1617 let value = future.await;
1618 producor.into_send_async(value).await;
1619 })
1620 } else {
1621 Err(Error::new(ErrorKind::Other, format!("Spawn wait any task failed by callback, reason: current async runtime not exist")))
1623 }
1624 }
1625}
1626
1627impl<V: 'static> AsyncWaitAnyCallback<V> {
1631 pub async fn wait_result(mut self,
1633 callback: impl Fn(&Result<V>) -> bool + 'static) -> Result<V> {
1634 let checker = create_checker(self.capacity, callback);
1635 loop {
1636 match self.consumer.recv_async().await {
1637 Err(e) => {
1638 return Err(Error::new(ErrorKind::Other, format!("Wait any result failed by callback, reason: {:?}", e)));
1640 },
1641 Ok(result) => {
1642 if checker(&result) {
1644 return result;
1646 }
1647 },
1648 }
1649 }
1650 }
1651}
1652
1653fn create_checker<V, F>(len: usize,
1655 callback: F) -> Arc<dyn Fn(&Result<V>) -> bool + 'static>
1656 where V: 'static,
1657 F: Fn(&Result<V>) -> bool + 'static {
1658 let mut check_counter = AtomicUsize::new(len); Arc::new(move |result| {
1660 if check_counter.fetch_sub(1, Ordering::SeqCst) == 1 {
1661 true
1663 } else {
1664 callback(result)
1666 }
1667 })
1668}
1669
1670pub struct AsyncMapReduce<V: 'static> {
1674 count: usize, capacity: usize, producor: AsyncSender<(usize, Result<V>)>, consumer: AsyncReceiver<(usize, Result<V>)>, }
1679
1680unsafe impl<V: 'static> Send for AsyncMapReduce<V> {}
1681
1682impl<V: 'static> AsyncMapReduce<V> {
1686 pub(crate) fn new(count: usize,
1688 capacity: usize,
1689 producor: AsyncSender<(usize, Result<V>)>,
1690 consumer: AsyncReceiver<(usize, Result<V>)>) -> Self {
1691 AsyncMapReduce {
1692 count,
1693 capacity,
1694 producor,
1695 consumer,
1696 }
1697 }
1698
1699 pub fn map<RT, O, F>(&mut self, rt: RT, future: F) -> Result<usize>
1701 where RT: AsyncRuntime<O>,
1702 O: Default + 'static,
1703 F: Future<Output = Result<V>> + 'static {
1704 if self.count >= self.capacity {
1705 return Err(Error::new(ErrorKind::Other, format!("Map task to runtime failed, capacity: {}, reason: out of capacity", self.capacity)));
1707 }
1708
1709 let index = self.count;
1710 let producor = self.producor.clone();
1711 rt.spawn(async move {
1712 let value = future.await;
1713 producor.into_send_async((index, value)).await;
1714
1715 Default::default()
1717 })?;
1718
1719 self.count += 1; Ok(index)
1721 }
1722}
1723
1724impl<V: 'static> AsyncMapReduce<V> {
1728 pub async fn reduce(self, order: bool) -> Result<Vec<Result<V>>> {
1730 let mut count = self.count;
1731 let mut results = Vec::with_capacity(count);
1732 while count > 0 {
1733 match self.consumer.recv_async().await {
1734 Err(e) => {
1735 return Err(Error::new(ErrorKind::Other, format!("Reduce result failed, reason: {:?}", e)));
1737 },
1738 Ok((index, result)) => {
1739 results.push((index, result));
1741 count -= 1;
1742 },
1743 }
1744 }
1745
1746 if order {
1747 results.sort_by_key(|(key, _value)| {
1749 key.clone()
1750 });
1751 }
1752 let (_, values) = results
1753 .into_iter()
1754 .unzip::<usize, Result<V>, Vec<usize>, Vec<Result<V>>>();
1755
1756 Ok(values)
1757 }
1758}
1759
1760pub fn spawn_worker_thread<F0, F1>(thread_name: &str,
1766 thread_stack_size: usize,
1767 thread_handler: Arc<AtomicBool>,
1768 thread_waker: Arc<(AtomicBool, Mutex<()>, Condvar)>, sleep_timeout: u64, loop_interval: Option<u64>, loop_func: F0,
1772 get_queue_len: F1) -> Arc<AtomicBool>
1773 where F0: Fn() -> (bool, Duration) + Send + 'static,
1774 F1: Fn() -> usize + Send + 'static {
1775 let thread_status_copy = thread_handler.clone();
1776
1777 thread::Builder::new()
1778 .name(thread_name.to_string())
1779 .stack_size(thread_stack_size)
1780 .spawn(move || {
1781 let mut sleep_count = 0;
1782
1783 while thread_handler.load(Ordering::Relaxed) {
1784 let (is_no_task, run_time) = loop_func();
1785
1786 if is_no_task {
1787 if sleep_count > 1 {
1789 sleep_count = 0; let (is_sleep, lock, condvar) = &*thread_waker;
1792 if get_queue_len() > 0 {
1793 continue;
1795 }
1796
1797 {
1798 let _locked = lock.lock();
1799 if !is_sleep.load(Ordering::Acquire) {
1800 is_sleep.store(true, Ordering::Release);
1802 }
1803 }
1804
1805 if get_queue_len() > 0 {
1806 is_sleep.store(false, Ordering::Release);
1808 continue;
1809 }
1810
1811 let mut locked = lock.lock();
1812 if is_sleep.load(Ordering::Acquire) {
1813 let _ = condvar.wait_for(
1814 &mut locked,
1815 Duration::from_millis(sleep_timeout),
1816 );
1817 }
1818 is_sleep.store(false, Ordering::Release);
1819
1820 continue; }
1822
1823 sleep_count += 1; if let Some(interval) = &loop_interval {
1825 if let Some(remaining_interval) = Duration::from_millis(*interval).checked_sub(run_time){
1827 thread::sleep(remaining_interval);
1829 }
1830 }
1831 } else {
1832 sleep_count = 0; if let Some(interval) = &loop_interval {
1835 if let Some(remaining_interval) = Duration::from_millis(*interval).checked_sub(run_time){
1837 thread::sleep(remaining_interval);
1839 }
1840 }
1841 }
1842 }
1843 });
1844
1845 thread_status_copy
1846}
1847
1848pub fn wakeup_worker_thread<O, P>(worker_waker: &Arc<(AtomicBool, Mutex<()>, Condvar)>,
1850 rt: &SingleTaskRuntime<O, P>)
1851 where O: Default + 'static,
1852 P: AsyncTaskPoolExt<O> + AsyncTaskPool<O, Pool = P> {
1853 if worker_waker.0.load(Ordering::Relaxed) && rt.len() > 0 {
1855 let _ = wake_thread_waker(worker_waker);
1856 }
1857}