toy_async_runtime/spawner.rs
1//! Spawner crate implementation
2use std::future::Future;
3use std::sync::Arc;
4
5use crate::runitime::Queue;
6use crate::task::Task;
7
8#[derive(Clone)]
9pub(crate) struct Spawner {
10 pub(crate) queue: Queue,
11}
12impl Spawner {
13 /// This is the function that gets called by the `spawn` function to
14 /// actually create a new `Task` in our queue. It takes the `Future`,
15 /// constructs a `Task` and then pushes it to the back of the queue.
16 pub fn spawn(self, future: impl Future<Output = ()> + Send + Sync + 'static) {
17 self.inner_spawn(Task::new(false, future));
18 }
19 /// This is the function that gets called by the `spawn_blocking` function to
20 /// actually create a new `Task` in our queue. It takes the `Future`,
21 /// constructs a `Task` and then pushes it to the front of the queue
22 /// where the runtime will check if it should block and then block until
23 /// this future completes.
24 pub fn spawn_blocking(self, future: impl Future<Output = ()> + Send + Sync + 'static) {
25 self.inner_spawn_blocking(Task::new(true, future));
26 }
27 /// This function just takes a `Task` and pushes it onto the queue. We use this
28 /// both for spawning new `Task`s and to push old ones that get woken up
29 /// back onto the queue.
30 pub fn inner_spawn(self, task: Arc<Task>) {
31 self.queue.lock().unwrap().push_back(task);
32 }
33 /// This function takes a `Task` and pushes it to the front of the queue
34 /// if it is meant to block. We use this both for spawning new blocking
35 /// `Task`s and to push old ones that get woken up back onto the queue.
36 pub fn inner_spawn_blocking(self, task: Arc<Task>) {
37 self.queue.lock().unwrap().push_front(task);
38 }
39}