executor.rs

 1use anyhow::{anyhow, Result};
 2use async_task::Runnable;
 3pub use async_task::Task;
 4use smol::prelude::*;
 5use smol::{channel, Executor};
 6use std::rc::Rc;
 7use std::sync::Arc;
 8use std::{marker::PhantomData, thread};
 9
10use crate::platform;
11
12pub enum Foreground {
13    Platform {
14        dispatcher: Arc<dyn platform::Dispatcher>,
15        _not_send_or_sync: PhantomData<Rc<()>>,
16    },
17    Test(smol::LocalExecutor<'static>),
18}
19
20pub struct Background {
21    executor: Arc<smol::Executor<'static>>,
22    _stop: channel::Sender<()>,
23}
24
25impl Foreground {
26    pub fn platform(dispatcher: Arc<dyn platform::Dispatcher>) -> Result<Self> {
27        if dispatcher.is_main_thread() {
28            Ok(Self::Platform {
29                dispatcher,
30                _not_send_or_sync: PhantomData,
31            })
32        } else {
33            Err(anyhow!("must be constructed on main thread"))
34        }
35    }
36
37    pub fn test() -> Self {
38        Self::Test(smol::LocalExecutor::new())
39    }
40
41    pub fn spawn<T: 'static>(&self, future: impl Future<Output = T> + 'static) -> Task<T> {
42        match self {
43            Self::Platform { dispatcher, .. } => {
44                let dispatcher = dispatcher.clone();
45                let schedule = move |runnable: Runnable| dispatcher.run_on_main_thread(runnable);
46                let (runnable, task) = async_task::spawn_local(future, schedule);
47                runnable.schedule();
48                task
49            }
50            Self::Test(executor) => executor.spawn(future),
51        }
52    }
53
54    pub async fn run<T>(&self, future: impl Future<Output = T>) -> T {
55        match self {
56            Self::Platform { .. } => panic!("you can't call run on a platform foreground executor"),
57            Self::Test(executor) => executor.run(future).await,
58        }
59    }
60}
61
62impl Background {
63    pub fn new() -> Self {
64        let executor = Arc::new(Executor::new());
65        let stop = channel::unbounded::<()>();
66
67        for i in 0..num_cpus::get() {
68            let executor = executor.clone();
69            let stop = stop.1.clone();
70            thread::Builder::new()
71                .name(format!("background-executor-{}", i))
72                .spawn(move || smol::block_on(executor.run(stop.recv())))
73                .unwrap();
74        }
75
76        Self {
77            executor,
78            _stop: stop.0,
79        }
80    }
81
82    pub fn spawn<T, F>(&self, future: F) -> Task<T>
83    where
84        T: 'static + Send,
85        F: Send + Future<Output = T> + 'static,
86    {
87        self.executor.spawn(future)
88    }
89}