thread_amount/
lib.rs

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