-
-
Save RandyMcMillan/883fce29682f4132c496c57fbb5aa869 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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