threadfin/
common.rs

1use crate::{Builder, CommonAlreadyInitializedError, ThreadPool};
2use once_cell::sync::OnceCell;
3
4static COMMON: OnceCell<ThreadPool> = OnceCell::new();
5
6/// Get a shared reference to a common thread pool for the entire process.
7///
8/// # Examples
9///
10/// ```
11/// let result = threadfin::common().execute(|| 2 + 2).join();
12///
13/// assert_eq!(result, 4);
14/// ```
15pub fn common() -> &'static ThreadPool {
16    COMMON.get_or_init(|| common_builder().build())
17}
18
19/// Configure the common thread pool.
20///
21/// This should be done near the start of your program before any other code
22/// uses the common pool, as this function will return an error if the common
23/// pool has already been initialized.
24///
25/// Only programs should use this function! Libraries should not use this
26/// function and instead allow the running program to configure the common pool.
27/// If you need a customized pool in a library then you should use a separate
28/// pool instance.
29///
30/// # Examples
31///
32/// ```
33/// threadfin::configure_common(|builder| builder
34///     .size(3)
35///     .queue_limit(1024))
36///     .unwrap();
37///
38/// assert_eq!(threadfin::common().threads(), 3);
39/// ```
40pub fn configure_common<F>(f: F) -> Result<(), CommonAlreadyInitializedError>
41where
42    F: FnOnce(Builder) -> Builder,
43{
44    let mut was_initialized = true;
45
46    COMMON.get_or_init(|| {
47        was_initialized = false;
48        f(common_builder()).build()
49    });
50
51    if was_initialized {
52        Err(CommonAlreadyInitializedError::new())
53    } else {
54        Ok(())
55    }
56}
57
58fn common_builder() -> Builder {
59    Builder::default().name("common-pool")
60}