1 use std::sync::atomic::{AtomicBool, Ordering};
2 
3 /// Init the global executor, spawning as many threads as specified or
4 /// the value specified by the specified environment variable.
5 ///
6 /// # Examples
7 ///
8 /// ```
9 /// async_global_executor::init_with_config(
10 ///     async_global_executor::GlobalExecutorConfig::default()
11 ///         .with_env_var("NUMBER_OF_THREADS")
12 ///         .with_min_threads(4)
13 ///         .with_max_threads(6)
14 ///         .with_thread_name_fn(Box::new(|| "worker".to_string()))
15 /// );
16 /// ```
init_with_config(config: crate::config::GlobalExecutorConfig)17 pub fn init_with_config(config: crate::config::GlobalExecutorConfig) {
18     let _ = crate::config::GLOBAL_EXECUTOR_CONFIG.set(config.seal());
19     init();
20 }
21 
22 /// Init the global executor, spawning as many threads as the number or cpus or
23 /// the value specified by the `ASYNC_GLOBAL_EXECUTOR_THREADS` environment variable
24 /// if specified.
25 ///
26 /// # Examples
27 ///
28 /// ```
29 /// async_global_executor::init();
30 /// ```
init()31 pub fn init() {
32     static INIT_DONE: AtomicBool = AtomicBool::new(false);
33     if !INIT_DONE.swap(true, Ordering::SeqCst) {
34         let config =
35             crate::config::GLOBAL_EXECUTOR_CONFIG.get_or_init(crate::config::Config::default);
36         crate::reactor::block_on(async {
37             crate::threading::spawn_more_threads(config.min_threads)
38                 .await
39                 .expect("cannot spawn executor threads");
40         });
41     }
42 }
43