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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#![no_std]
extern crate alloc;
use lazy_static::*;
use {
alloc::{boxed::Box, sync::Arc, collections::vec_deque::VecDeque},
core::{
future::Future,
pin::Pin,
task::{Context, Poll},
},
spin::Mutex,
woke::{waker_ref, Woke},
};
pub struct Executor {
tasks: VecDeque<Arc<Task>>,
}
impl Default for Executor {
fn default() -> Self {
Executor {
tasks: VecDeque::new(),
}
}
}
struct Task {
pub future: Mutex<Pin<Box<dyn Future<Output = ()> + Send + 'static>>>,
}
impl Woke for Task {
fn wake_by_ref(_: &Arc<Self>) {
DEFAULT_EXECUTOR.lock().poll_tasks()
}
}
impl GlobalExecutor for Executor {
fn spawn(&mut self, future: Box<dyn Future<Output = ()> + 'static + Send + Unpin>) {
self.add_task(future);
self.poll_tasks();
}
}
impl Executor {
fn add_task(&mut self, future: Box<dyn Future<Output = ()> + 'static + Send + Unpin>) {
let task = Arc::new(Task {
future: Mutex::new(Box::pin(future)),
});
self.tasks.push_back(task);
}
fn poll_tasks(&mut self) {
let count = self.tasks.len();
for _ in 0..count {
let task = self.tasks.remove(0).unwrap();
let mut is_pending = false;
{
let mut future = task.future.lock();
let waker = waker_ref(&task);
let context = &mut Context::from_waker(&*waker);
if let Poll::Pending = future.as_mut().poll(context) {
is_pending = true;
}
}
if is_pending {
self.tasks.push_back(task);
}
}
}
}
struct DefaultExecutor;
impl GlobalExecutor for DefaultExecutor {
fn spawn(&mut self, future: Box<dyn Future<Output = ()> + 'static + Send + Unpin>) {
DEFAULT_EXECUTOR.lock().spawn(future)
}
}
lazy_static! {
static ref DEFAULT_EXECUTOR: Mutex<Box<Executor>> = {
let m = Executor::default();
Mutex::new(Box::new(m))
};
static ref GLOBAL_EXECUTOR: Mutex<Box<dyn GlobalExecutor+Send+Sync>> = {
let m = DefaultExecutor;
Mutex::new(Box::new(m))
};
}
pub fn spawn(future: impl Future<Output = ()> + 'static + Send) {
GLOBAL_EXECUTOR.lock().spawn(Box::new(Box::pin(future)));
}
pub fn set_global_executor(executor:impl GlobalExecutor+Send+Sync+'static) {
let mut global_executor = GLOBAL_EXECUTOR.lock();
*global_executor = Box::new(executor);
}
pub trait GlobalExecutor {
fn spawn(&mut self, future: Box<dyn Future<Output = ()> + 'static + Send + Unpin>);
}