Skip to main content

lelet/executor/
mod.rs

1// extra doc:
2// Inspired by golang runtime, see https://golang.org/s/go11sched
3// understanding some terminology like machine and processor will help you
4// understand this code.
5//
6// Noticable difference with golang scheduler
7// 1. new machine steal the processor from old one when it run the processor instead of
8//    acquire/release from global list
9// 2. machine don't live without a processor (when stolen by others),
10//    it must exit as soon as possible
11// 3. each processor have dedicated global queue
12
13mod machine;
14mod processor;
15mod system;
16mod task;
17
18pub use system::get_num_cpus;
19pub use system::set_num_cpus;
20
21pub use system::detach_current_thread;
22
23use std::future::Future;
24use std::pin::Pin;
25use std::task::{Context, Poll};
26
27use self::task::TaskTag;
28
29type Task = async_task::Task<TaskTag>;
30
31/// Run the task in the background.
32///
33/// Just like goroutine in golang, there is no way to cancel a task,
34/// but unlike goroutine you can `await` the task
35///
36/// # Panic
37///
38/// When a task panic, it will abort the entire program
39#[inline(always)]
40pub fn spawn<T, R>(task: T) -> JoinHandle<R>
41where
42    T: Future<Output = R> + Send + 'static,
43    R: Send + 'static,
44{
45    let system = system::get();
46    let (task, handle) = async_task::spawn(task, move |task| system.push(task), TaskTag::new());
47    task.schedule();
48    JoinHandle(handle)
49}
50
51/// Handle that you can `await` for
52///
53/// this struct returned by [`spawn`]
54///
55/// [`spawn`]: fn.spawn.html
56pub struct JoinHandle<R>(async_task::JoinHandle<R, TaskTag>);
57
58impl<R> Future for JoinHandle<R> {
59    type Output = R;
60
61    #[inline(always)]
62    fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
63        match Pin::new(&mut self.0).poll(cx) {
64            Poll::Pending => Poll::Pending,
65            Poll::Ready(Some(val)) => Poll::Ready(val),
66            Poll::Ready(None) => unreachable!(), // we don't provide api to cancel the task
67        }
68    }
69}