thread_count/
lib.rs

1#![warn(clippy::pedantic)]
2use std::num::NonZeroUsize;
3
4#[cfg_attr(any(target_os = "macos", target_os = "ios"), path = "osx.rs")]
5#[cfg_attr(target_os = "linux", path = "linux.rs")]
6#[cfg_attr(target_family = "windows", path = "windows.rs")]
7mod implementation;
8
9/// Gets the amount of threads for the current process.
10/// Returns `None` if there are no threads.
11#[must_use]
12pub fn thread_amount() -> Option<NonZeroUsize> {
13    implementation::thread_amount()
14}
15
16/// Check if the current process is single-threaded.
17#[must_use]
18pub fn is_single_threaded() -> bool {
19    match thread_amount() {
20        Some(amount) => amount.get() == 1,
21        None => false,
22    }
23}
24
25#[cfg(test)]
26mod tests {
27    use std::num::NonZeroUsize;
28
29    #[test]
30    fn thread_amount() {
31        for i in 0..5 {
32            std::thread::spawn(move || {
33                assert_eq!(super::thread_amount().map(NonZeroUsize::get), Some(i));
34            });
35        }
36    }
37
38    #[test]
39    fn is_single_threaded() {
40        for i in 0..5 {
41            std::thread::spawn(move || {
42                if i == 0 {
43                    assert!(super::is_single_threaded());
44                } else {
45                    assert!(!super::is_single_threaded());
46                }
47            });
48        }
49    }
50}