toy_async_runtime/
task.rs1use std::future::Future;
3use std::pin::Pin;
4use std::sync::atomic::Ordering;
5use std::sync::{Arc, Mutex};
6use std::task::{Context, Poll, Wake, Waker};
7
8use crate::runitime::Runtime;
9
10pub(crate) struct Task {
15 future: Mutex<Pin<Box<dyn Future<Output = ()> + Send + Sync + 'static>>>,
21 block: bool,
24}
25
26impl Wake for Task {
27 fn wake(self: Arc<Self>) {
28 if self.is_blocking() {
29 Runtime::spawner().inner_spawn_blocking(self);
30 } else {
31 Runtime::spawner().inner_spawn(self);
32 }
33 }
34}
35
36impl Drop for Task {
37 fn drop(&mut self) {
38 Runtime::get().size.fetch_sub(1, Ordering::Relaxed);
39 }
40}
41
42impl Task {
43 pub(crate) fn new(
44 block: bool,
45 future: impl Future<Output = ()> + Send + Sync + 'static,
46 ) -> Arc<Self> {
47 Runtime::get().size.fetch_add(1, Ordering::Relaxed);
48 Arc::new(Task {
49 future: Mutex::new(Box::pin(future)),
50 block,
51 })
52 }
53
54 pub fn poll(self: &Arc<Self>) -> Poll<()> {
56 let waker = self.waker();
57 let mut ctx = Context::from_waker(&waker);
58 self.future.lock().unwrap().as_mut().poll(&mut ctx)
59 }
60
61 pub fn waker(self: &Arc<Self>) -> Waker {
63 self.clone().into()
64 }
65
66 pub fn is_blocking(&self) -> bool {
68 self.block
69 }
70}