nuclei/runtime.rs
1//! nuclei's own runtime: thread-per-core shards that run tasks, a blocking
2//! pool, and the functions that place work on them.
3//!
4//! A [`Runtime`] runs one shard per worker thread. A shard owns its run
5//! queue, its timers and its poller, and a task stays on the shard it was
6//! placed on: [`spawn`] keeps it near the spawning thread's other tasks
7//! within a margin of load (see [`Builder::local_spawn_margin`]),
8//! [`spawn_local`] keeps it on the calling thread. [`block_on`] runs a
9//! future on the calling thread and nests: called from a task, it keeps the
10//! shard running its other tasks until the future completes.
11//!
12//! [`RuntimeHandle::spawn_on_worker`], [`RuntimeHandle::on_each_worker`] and
13//! [`task::Builder::worker`](crate::task::Builder::worker) place a task on a
14//! worker the caller names, where it stays; [`shard_local!`](crate::shard_local)
15//! keeps a [`ShardLocal`](crate::runtime::ShardLocal) value per worker, which moves with the worker's
16//! shard when a handoff gives the shard to another thread.
17//!
18//! The free functions use the runtime the calling thread is inside, or the
19//! process default runtime, which starts on first use with no configuration
20//! (one worker per core). [`Builder`] sets everything else, and
21//! [`Runtime::stats`] reads one runtime's counters.
22//!
23//! ```
24//! use nuclei::runtime::{Runtime, spawn};
25//!
26//! let runtime = Runtime::builder().worker_threads(2).build().unwrap();
27//! let sum = runtime.block_on(async {
28//! let tasks: Vec<_> = (0..4u64).map(|n| spawn(async move { n * n })).collect();
29//! let mut sum = 0;
30//! for task in tasks {
31//! sum += task.await;
32//! }
33//! sum
34//! });
35//! assert_eq!(sum, 14);
36//! ```
37
38pub use crate::rt::runtime::{
39 Builder, EnterGuard, RngSeed, Runtime, RuntimeHandle, RuntimeId, TaskMeta, TryCurrentError,
40 UnhandledPanic, block_on, spawn, spawn_blocking, spawn_local, worker_index,
41};
42pub use crate::rt::task::{FallibleTask, Task};
43pub use crate::shard_local::{ShardAccessError, ShardLocal};