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/// Initialize the global runtime and its Melinoe partition bridge.
9///
10/// Call this during application startup before code invokes
11/// `melinoe::sync::partition_*` directly. The operation is idempotent and
12/// refreshes the process-global bridge if a test or integration cleared it.
13pub fn initialize() {
14    moirai_executor::initialize();
15}
16
17/// Get or initialize the global Moirai runtime.
18///
19/// This provides a convenient way to access a shared runtime instance
20/// without having to pass it around explicitly.
21///
22/// # Panics
23///
24/// Panics if the global runtime fails to initialize, which should not happen
25/// under normal circumstances unless there are severe system resource constraints.
26pub fn global() -> &'static Moirai {
27    // Wrap the SAME shared executor that `moirai-parallel` schedules data-parallel
28    // work on, so async tasks (spawn_async/block_on) and parallel work run on one
29    // unified hybrid scheduler — a parallel worker can drive async work in-process.
30    GLOBAL_RUNTIME.get_or_init(|| Moirai {
31        executor: moirai_executor::shared(),
32    })
33}
34
35/// Spawn an async task on the global runtime.
36pub fn spawn_async<F>(future: F) -> TaskHandle<F::Output>
37where
38    F: Future + Send + 'static,
39    F::Output: Send + 'static,
40{
41    global().spawn_async(future)
42}
43
44/// Spawn a parallel task on the global runtime.
45pub fn spawn_fn<F, R>(func: F) -> TaskHandle<R>
46where
47    F: FnOnce() -> R + Send + 'static,
48    R: Send + 'static,
49{
50    global().spawn_fn(func)
51}
52
53/// Block on a future using the global runtime.
54pub fn block_on<F>(future: F) -> F::Output
55where
56    F: Future,
57{
58    global().block_on(future)
59}