Skip to main content

quickjs_runtime/jsutils/
helper_tasks.rs

1use futures::Future;
2use hirofa_utils::task_manager::TaskManager;
3use std::sync::OnceLock;
4use tokio::runtime::Handle;
5use tokio::task::JoinError;
6
7static HELPER_TASKS: OnceLock<TaskManager> = OnceLock::new();
8
9fn get_helper_tasks() -> &'static TaskManager {
10    HELPER_TASKS.get_or_init(|| TaskManager::new(std::cmp::max(2, num_cpus::get())))
11}
12
13/// initialize the helper tasks with a specific tokio handle
14pub fn init_helper_tasks_with_handle(handle: Handle) {
15    let _ = HELPER_TASKS.set(TaskManager::from_handle(handle));
16}
17
18/// initialize the helper tasks with a specific thread count
19pub fn init_helper_tasks(thread_count: usize) {
20    let _ = HELPER_TASKS.set(TaskManager::new(thread_count));
21}
22
23/// add a task the the "helper" thread pool
24pub fn add_helper_task<T>(task: T)
25where
26    T: FnOnce() + Send + 'static,
27{
28    log::trace!("adding a helper task");
29    get_helper_tasks().add_task(task);
30}
31
32/// add an async task the the "helper" thread pool
33pub fn add_helper_task_async<R: Send + 'static, T: Future<Output = R> + Send + 'static>(
34    task: T,
35) -> impl Future<Output = Result<R, JoinError>> {
36    log::trace!("adding an async helper task");
37    get_helper_tasks().add_task_async(task)
38}