Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created March 26, 2025 04:04
Show Gist options
  • Save rust-play/b47549fcd2ab31ba3d2f24e0317c9645 to your computer and use it in GitHub Desktop.
Save rust-play/b47549fcd2ab31ba3d2f24e0317c9645 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use once_cell::sync::OnceCell;
// global_rt
pub fn global_rt() -> &'static tokio::runtime::Runtime {
static RT: OnceCell<tokio::runtime::Runtime> = OnceCell::new();
RT.get_or_init(|| tokio::runtime::Runtime::new().unwrap())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_global_rt() {
let rt1 = global_rt();
let rt2 = global_rt();
// Ensure that the same runtime is returned each time.
assert!(std::ptr::eq(rt1, rt2));
// Ensure the runtime is functional by spawning a simple task.
rt1.block_on(async {
let result = tokio::spawn(async {
1 + 1
}).await.unwrap();
assert_eq!(result, 2);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment