summaryrefslogtreecommitdiff
path: root/src/executor.rs
blob: 51f58fa675a9f08f35f7198c409c4debef1dcdbd (plain)
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
// luwenpeng 2022/11/01

use crate::reactor::Reactor;
use futures::future::LocalBoxFuture;
use futures::Future;
use futures::FutureExt;
use std::cell::RefCell;
use std::collections::VecDeque;
use std::marker::PhantomData;
use std::mem;
use std::pin::Pin;
use std::rc::Rc;
use std::task::Context;
use std::task::RawWaker;
use std::task::RawWakerVTable;
use std::task::Waker;

/******************************************************************************
 * thread_local 的静态变量 THREAD_LOCAL_EXECUTOR
 ******************************************************************************/

scoped_tls::scoped_thread_local!(pub(crate) static THREAD_LOCAL_EXECUTOR: Executor);

/******************************************************************************
 * Task
 ******************************************************************************/

pub struct Task {
    future: RefCell<LocalBoxFuture<'static, ()>>,
}

impl Task {
    fn enqueue(self: Rc<Self>) {
        Self::enqueue_by_ref(&self)
    }

    fn enqueue_by_ref(self: &Rc<Self>) {
        THREAD_LOCAL_EXECUTOR.with(|executor| executor.local_queue.push(self.clone()));
    }
}

/******************************************************************************
 * TaskQueue
 ******************************************************************************/

pub struct TaskQueue {
    queue: RefCell<VecDeque<Rc<Task>>>,
}

impl Default for TaskQueue {
    fn default() -> Self {
        Self::new()
    }
}

impl TaskQueue {
    pub fn new() -> Self {
        const DEFAULT_TASK_QUEUE_SIZE: usize = 4096;
        Self::new_with_capacity(DEFAULT_TASK_QUEUE_SIZE)
    }

    pub fn new_with_capacity(capacity: usize) -> Self {
        Self {
            queue: RefCell::new(VecDeque::with_capacity(capacity)),
        }
    }

    pub(crate) fn push(&self, runnable: Rc<Task>) {
        println!("[task_queue] push task");

        self.queue.borrow_mut().push_back(runnable);
    }

    pub(crate) fn pop(&self) -> Option<Rc<Task>> {
        println!("[task_queue] pop task");

        self.queue.borrow_mut().pop_front()
    }
}

/******************************************************************************
 * Executor
 ******************************************************************************/

pub struct Executor {
    local_queue: TaskQueue,                   // 任务队列
    pub(crate) reactor: Rc<RefCell<Reactor>>, // Reactor

    // Make sure the type is `!Send` and `!Sync`.
    marker: PhantomData<Rc<()>>,
}

impl Default for Executor {
    fn default() -> Self {
        Self::new()
    }
}

impl Executor {
    pub fn new() -> Self {
        Self {
            local_queue: TaskQueue::default(),
            reactor: Rc::new(RefCell::new(Reactor::default())),
            marker: PhantomData,
        }
    }

    pub fn spawn(future: impl Future<Output = ()> + 'static) {
        println!("[executor] spawn, wrap future to task, and push task to queue");

        let task = Rc::new(Task {
            future: RefCell::new(future.boxed_local()),
        });
        THREAD_LOCAL_EXECUTOR.with(|executor| executor.local_queue.push(task));
    }

    pub fn block_on<F, T, O>(&self, f: F) -> O
    where
        F: Fn() -> T,
        T: Future<Output = O> + 'static,
    {
        println!("[executor] block_on");

        let _waker = waker_fn::waker_fn(|| {});
        let ctx = &mut Context::from_waker(&_waker);

        THREAD_LOCAL_EXECUTOR.set(self, || {
            // 此处的 future 为 async fn tcp_server()
            let future = f();
            pin_utils::pin_mut!(future);

            loop {
                println!("[executor] -> loop");

                // return if the outer future is ready
                if let std::task::Poll::Ready(task) = future.as_mut().poll(ctx) {
                    println!("[executor] future poll(1), return ready");
                    break task;
                }

                println!("[executor] consume all tasks");

                // consume all tasks
                while let Some(task) = self.local_queue.pop() {
                    println!("[executor] pop task frome queue");

                    let future = task.future.borrow_mut();

                    let waker = wrap_task_to_waker(task.clone()); // 此处将 task  包装成 Waker
                    let mut context = Context::from_waker(&waker); // 此处将 Waker 包装成 Context

                    let _ = Pin::new(future).as_mut().poll(&mut context);
                    println!("[executor] future poll(2), return");

                    // 此处默认执行:[RawWaker] drop_waker()
                }

                // no task to execute now, it may ready
                if let std::task::Poll::Ready(task) = future.as_mut().poll(ctx) {
                    println!("[executor] future poll(3), return ready");
                    break task;
                }

                // block for io
                println!("[executor] reactor->wait()");
                self.reactor.borrow_mut().wait();
            }
        })
    }
}

/******************************************************************************
 * waker
 ******************************************************************************/

/*
pub struct Context<'a> {
    waker: &'a Waker,
    _marker: PhantomData<fn(&'a ()) -> &'a ()>,
}

pub struct Waker {
    waker: RawWaker,
}

pub struct RawWaker {
    data: *const (),
    vtable: &'static RawWakerVTable,
}
*/

fn wrap_task_to_waker(task: Rc<Task>) -> Waker {
    println!("[executor] ->wrap_task_to_waker(), wrap task to Waker");

    let ptr = Rc::into_raw(task) as *const ();
    let vtable = &Helper::VTABLE; // VTABLE 为 const 定义的 RawWakerVTable
    unsafe { Waker::from_raw(RawWaker::new(ptr, vtable)) }
}

/******************************************************************************
 * Helper
 ******************************************************************************/

struct Helper;

impl Helper {
    const VTABLE: RawWakerVTable = RawWakerVTable::new(
        Self::clone_waker,
        Self::wake,
        Self::wake_by_ref,
        Self::drop_waker,
    );

    // 将 task 封装成 RawWaker
    unsafe fn clone_waker(ptr: *const ()) -> RawWaker {
        println!("[RawWaker] ->clone_waker(), wrap task to RawWaker");

        increase_refcount(ptr);
        let vtable = &Self::VTABLE;
        RawWaker::new(ptr, vtable)
    }

    //  将 task 添加到任务队列中
    unsafe fn wake(ptr: *const ()) {
        println!("[RawWaker] ->wake(), add task to queue");

        let task = Rc::from_raw(ptr as *const Task);
        task.enqueue();
    }

    // 将 task 添加到任务队列中
    unsafe fn wake_by_ref(ptr: *const ()) {
        println!("[RawWaker] wake_by_ref(), add task to queue");

        let task = mem::ManuallyDrop::new(Rc::from_raw(ptr as *const Task));
        task.enqueue_by_ref();
    }

    unsafe fn drop_waker(ptr: *const ()) {
        println!("[RawWaker] ->drop_waker(), drop RawWaker");

        drop(Rc::from_raw(ptr as *const Task));
    }
}

#[allow(clippy::redundant_clone)] // The clone here isn't actually redundant.
unsafe fn increase_refcount(data: *const ()) {
    // Retain Rc, but don't touch refcount by wrapping in ManuallyDrop
    let rc = mem::ManuallyDrop::new(Rc::<Task>::from_raw(data as *const Task));
    // Now increase refcount, but don't drop new refcount either
    let _rc_clone: mem::ManuallyDrop<_> = rc.clone();
}