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
25#[must_use]
26pub type BackgroundTask<T> = smol::Task<T>;
27
28impl Foreground {
29    pub fn platform(dispatcher: Arc<dyn platform::Dispatcher>) -> Result<Self> {
30        if dispatcher.is_main_thread() {
31            Ok(Self::Platform {
32                dispatcher,
33                _not_send_or_sync: PhantomData,
34            })
35        } else {
36            Err(anyhow!("must be constructed on main thread"))
37        }
38    }
39
40    pub fn test() -> Self {
41        Self::Test(smol::LocalExecutor::new())
42    }
43
44    pub fn spawn<T: 'static>(&self, future: impl Future<Output = T> + 'static) -> Task<T> {
45        match self {
46            Self::Platform { dispatcher, .. } => {
47                let dispatcher = dispatcher.clone();
48                let schedule = move |runnable: Runnable| dispatcher.run_on_main_thread(runnable);
49                let (runnable, task) = async_task::spawn_local(future, schedule);
50                runnable.schedule();
51                task
52            }
53            Self::Test(executor) => executor.spawn(future),
54        }
55    }
56
57    pub async fn run<T>(&self, future: impl Future<Output = T>) -> T {
58        match self {
59            Self::Platform { .. } => panic!("you can't call run on a platform foreground executor"),
60            Self::Test(executor) => executor.run(future).await,
61        }
62    }
63}
64
65impl Background {
66    pub fn new() -> Self {
67        let executor = Arc::new(Executor::new());
68        let stop = channel::unbounded::<()>();
69
70        for i in 0..num_cpus::get() {
71            let executor = executor.clone();
72            let stop = stop.1.clone();
73            thread::Builder::new()
74                .name(format!("background-executor-{}", i))
75                .spawn(move || smol::block_on(executor.run(stop.recv())))
76                .unwrap();
77        }
78
79        Self {
80            executor,
81            _stop: stop.0,
82        }
83    }
84
85    pub fn spawn<T>(&self, future: impl Send + Future<Output = T> + 'static) -> BackgroundTask<T>
86    where
87        T: 'static + Send,
88    {
89        self.executor.spawn(future)
90    }
91}