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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
use super::{ArcWake, AutoStopHandle};
use crate::{
error::code::*,
mutex_init,
revocable::AsyncRevocable,
sync::{Arc, ArcBorrow, LockClassKey, Mutex, UniqueArc},
unsafe_list,
workqueue::{BoxedQueue, Queue, Work, WorkAdapter},
Either, Left, Result, Right,
};
use core::{cell::UnsafeCell, future::Future, marker::PhantomPinned, pin::Pin, task::Context};
trait RevocableTask {
fn revoke(&self);
fn flush(self: Arc<Self>);
fn to_links(&self) -> &unsafe_list::Links<dyn RevocableTask>;
}
unsafe impl unsafe_list::Adapter for dyn RevocableTask {
type EntryType = dyn RevocableTask;
fn to_links(obj: &dyn RevocableTask) -> &unsafe_list::Links<dyn RevocableTask> {
obj.to_links()
}
}
struct Task<T: 'static + Send + Future> {
links: unsafe_list::Links<dyn RevocableTask>,
executor: Arc<Executor>,
work: Work,
future: AsyncRevocable<UnsafeCell<T>>,
}
unsafe impl<T: 'static + Send + Future> Sync for Task<T> {}
unsafe impl<T: 'static + Send + Future> Send for Task<T> {}
impl<T: 'static + Send + Future> Task<T> {
fn try_new(
executor: Arc<Executor>,
key: &'static LockClassKey,
future: T,
) -> Result<Arc<Self>> {
let task = UniqueArc::try_new(Self {
executor: executor.clone(),
links: unsafe_list::Links::new(),
work: unsafe { Work::new() },
future: AsyncRevocable::new(UnsafeCell::new(future)),
})?;
Work::init(&task, key);
let task = Arc::from(task);
{
let mut guard = executor.inner.lock();
if guard.stopped {
return Err(EINVAL);
}
Arc::into_raw(task.clone());
unsafe { guard.tasks.push_back(&*task) };
}
Ok(task)
}
}
unsafe impl<T: 'static + Send + Future> WorkAdapter for Task<T> {
type Target = Self;
const FIELD_OFFSET: isize = crate::offset_of!(Self, work);
fn run(task: Arc<Task<T>>) {
let waker = super::ref_waker(task.clone());
let mut ctx = Context::from_waker(&waker);
let guard = if let Some(g) = task.future.try_access() {
g
} else {
return;
};
let future = unsafe { Pin::new_unchecked(&mut *guard.get()) };
if future.poll(&mut ctx).is_ready() {
drop(guard);
task.revoke();
}
}
}
impl<T: 'static + Send + Future> super::Task for Task<T> {
fn sync_stop(self: Arc<Self>) {
self.revoke();
self.flush();
}
}
impl<T: 'static + Send + Future> RevocableTask for Task<T> {
fn revoke(&self) {
if !self.future.revoke() {
return;
}
unsafe { self.executor.inner.lock().tasks.remove(self) };
unsafe { Arc::from_raw(self) };
}
fn flush(self: Arc<Self>) {
self.work.cancel();
}
fn to_links(&self) -> &unsafe_list::Links<dyn RevocableTask> {
&self.links
}
}
impl<T: 'static + Send + Future> ArcWake for Task<T> {
fn wake(self: Arc<Self>) {
if self.future.is_revoked() {
return;
}
match &self.executor.queue {
Left(q) => &**q,
Right(q) => *q,
}
.enqueue(self.clone());
}
fn wake_by_ref(self: ArcBorrow<'_, Self>) {
Arc::from(self).wake();
}
}
struct ExecutorInner {
stopped: bool,
tasks: unsafe_list::List<dyn RevocableTask>,
}
pub struct Executor {
queue: Either<BoxedQueue, &'static Queue>,
inner: Mutex<ExecutorInner>,
_pin: PhantomPinned,
}
unsafe impl Send for Executor {}
unsafe impl Sync for Executor {}
impl Executor {
pub fn try_new(wq: &'static Queue) -> Result<AutoStopHandle<Self>> {
Self::new_internal(Right(wq))
}
pub fn try_new_owned(wq: BoxedQueue) -> Result<AutoStopHandle<Self>> {
Self::new_internal(Left(wq))
}
fn new_internal(queue: Either<BoxedQueue, &'static Queue>) -> Result<AutoStopHandle<Self>> {
let mut e = Pin::from(UniqueArc::try_new(Self {
queue,
_pin: PhantomPinned,
inner: unsafe {
Mutex::new(ExecutorInner {
stopped: false,
tasks: unsafe_list::List::new(),
})
},
})?);
let pinned = unsafe { e.as_mut().map_unchecked_mut(|e| &mut e.inner) };
mutex_init!(pinned, "Executor::inner");
Ok(AutoStopHandle::new(e.into()))
}
}
impl super::Executor for Executor {
fn spawn(
self: ArcBorrow<'_, Self>,
key: &'static LockClassKey,
future: impl Future + 'static + Send,
) -> Result<Arc<dyn super::Task>> {
let task = Task::try_new(self.into(), key, future)?;
task.clone().wake();
Ok(task)
}
fn stop(&self) {
self.inner.lock().stopped = true;
loop {
let guard = self.inner.lock();
let front = if let Some(t) = guard.tasks.front() {
t
} else {
break;
};
let tasktmp = unsafe { Arc::<dyn RevocableTask>::from_raw(front.as_ptr()) };
let task = tasktmp.clone();
Arc::into_raw(tasktmp);
drop(guard);
task.revoke();
task.flush();
}
}
}