Skip to main content

moirai/
global.rs

1use crate::Moirai;
2use moirai_core::task::TaskHandle;
3use std::future::Future;
4
5/// Global runtime instance for convenience.
6static GLOBAL_RUNTIME: std::sync::OnceLock<Moirai> = std::sync::OnceLock::new();
7
8/// Get or initialize the global Moirai runtime.
9///
10/// This provides a convenient way to access a shared runtime instance
11/// without having to pass it around explicitly.
12///
13/// # Panics
14///
15/// Panics if the global runtime fails to initialize, which should not happen
16/// under normal circumstances unless there are severe system resource constraints.
17pub fn global() -> &'static Moirai {
18    // Wrap the SAME shared executor that `moirai-parallel` schedules data-parallel
19    // work on, so async tasks (spawn_async/block_on) and parallel work run on one
20    // unified hybrid scheduler — a parallel worker can drive async work in-process.
21    GLOBAL_RUNTIME.get_or_init(|| Moirai {
22        executor: moirai_executor::shared(),
23    })
24}
25
26/// Spawn an async task on the global runtime.
27pub fn spawn_async<F>(future: F) -> TaskHandle<F::Output>
28where
29    F: Future + Send + 'static,
30    F::Output: Send + 'static,
31{
32    global().spawn_async(future)
33}
34
35/// Spawn a parallel task on the global runtime.
36pub fn spawn_fn<F, R>(func: F) -> TaskHandle<R>
37where
38    F: FnOnce() -> R + Send + 'static,
39    R: Send + 'static,
40{
41    global().spawn_fn(func)
42}
43
44/// Block on a future using the global runtime.
45pub fn block_on<F>(future: F) -> F::Output
46where
47    F: Future,
48{
49    global().block_on(future)
50}