rasi_default/
executor.rs

1//! The implementation of [`Executor`] syscall.
2//!
3//!
4
5use std::io;
6
7use futures::{executor::ThreadPool, future::BoxFuture};
8use rasi_syscall::{register_global_executor, Executor};
9
10/// The implementation of [`Executor`] syscall.
11///
12/// This type using [`ThreadPool`] as inner task executor.
13pub struct FuturesExecutor {
14    thread_pool: ThreadPool,
15}
16
17impl FuturesExecutor {
18    pub fn new(pool_size: usize) -> io::Result<Self> {
19        Ok(Self {
20            thread_pool: ThreadPool::builder().pool_size(pool_size).create()?,
21        })
22    }
23}
24
25impl Executor for FuturesExecutor {
26    fn spawn_boxed(&self, fut: BoxFuture<'static, ()>) {
27        self.thread_pool.spawn_ok(fut)
28    }
29}
30
31/// Create and register [`ThreadPool`] as the `rasi` global [`Executor`] syscall.
32/// using parameter `pool_size` to specify the [`ThreadPool`] size.
33///
34/// You may not call this function twice, otherwise will cause a panic. [`read more`](`register_global_executor`)
35pub fn register_futures_executor_with_pool_size(pool_size: usize) -> io::Result<()> {
36    register_global_executor(FuturesExecutor::new(pool_size)?);
37
38    Ok(())
39}
40
41/// Create and register [`ThreadPool`] as the `rasi` global [`Executor`] syscall,
42/// the inner using [`num_cpus::get_physical()`] to specify the pool size.
43///
44/// See [`register_futures_executor_with_pool_size`] for more informations.
45pub fn register_futures_executor() -> io::Result<()> {
46    register_futures_executor_with_pool_size(num_cpus::get_physical())
47}