1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#![no_std]
extern crate alloc;
use {
alloc::{boxed::Box, sync::Arc},
core::{
future::Future,
pin::Pin,
task::{Context, Poll},
},
spin::Mutex,
woke::{waker_ref, Woke},
};
use smallvec::*;
#[macro_use]
extern crate lazy_static;
pub struct Executor {
tasks: SmallVec<[Arc<Task>;1024]>,
}
struct Task {
pub future: Mutex<Option<Pin<Box<dyn Future<Output = ()> + Send + 'static>>>>,
}
impl Woke for Task {
fn wake_by_ref(_: &Arc<Self>) {
Executor::run()
}
}
impl Executor {
pub fn spawn(future: impl Future<Output = ()> + 'static + Send) {
let task = Arc::new(Task {
future: Mutex::new(Some(Box::pin(future))),
});
let mut e = get_executor().lock();
let mut v = SmallVec::new();
v.push(task);
e.tasks = v;
core::mem::drop(e);
Executor::run();
}
fn run() {
let mut e = get_executor().lock();
let count = e.tasks.len();
for _ in 0..count {
let task = e.tasks.remove(0);
let mut is_pending = false;
{
let mut future_slot = task.future.lock();
if let Some(mut future) = future_slot.take() {
let waker = waker_ref(&task);
let context = &mut Context::from_waker(&*waker);
if let Poll::Pending = future.as_mut().poll(context) {
*future_slot = Some(future);
is_pending = true;
}
}
}
if is_pending {
e.tasks.push(task);
}
}
}
}
lazy_static! {
static ref INSTANCE: Mutex<Executor> = {
Mutex::new(Executor {
tasks: SmallVec::new(),
})
};
}
fn get_executor() -> &'static Mutex<Executor> {
&INSTANCE
}