/rust/registry/src/index.crates.io-1949cf8c6b5b557f/num_threads-0.1.6/src/lib.rs
Line | Count | Source |
1 | | //! Minimum supported Rust version: 1.28 |
2 | | |
3 | | use std::num::NonZeroUsize; |
4 | | |
5 | | #[cfg_attr(any(target_os = "linux", target_os = "android"), path = "linux.rs")] |
6 | | #[cfg_attr(target_os = "freebsd", path = "freebsd.rs")] |
7 | | #[cfg_attr(any(target_os = "macos", target_os = "ios"), path = "apple.rs")] |
8 | | mod imp; |
9 | | |
10 | | /// Obtain the number of threads currently part of the active process. Returns `None` if the number |
11 | | /// of threads cannot be determined. |
12 | 0 | pub fn num_threads() -> Option<NonZeroUsize> { |
13 | 0 | imp::num_threads() |
14 | 0 | } |
15 | | |
16 | | /// Determine if the current process is single-threaded. Returns `None` if the number of threads |
17 | | /// cannot be determined. |
18 | 0 | pub fn is_single_threaded() -> Option<bool> { |
19 | 0 | num_threads().map(|n| n.get() == 1) |
20 | 0 | } |
21 | | |
22 | | #[cfg(test)] |
23 | | mod test { |
24 | | use std::num::NonZeroUsize; |
25 | | |
26 | | // Run each expression in its own thread. |
27 | | macro_rules! threaded { |
28 | | ($first:expr;) => { |
29 | | $first; |
30 | | }; |
31 | | ($first:expr; $($rest:expr;)*) => { |
32 | | $first; |
33 | | ::std::thread::spawn(|| { |
34 | | threaded!($($rest;)*); |
35 | | }) |
36 | | .join() |
37 | | .unwrap(); |
38 | | }; |
39 | | } |
40 | | |
41 | | #[test] |
42 | | fn num_threads() { |
43 | | threaded! { |
44 | | assert_eq!(super::num_threads().map(NonZeroUsize::get), Some(1)); |
45 | | assert_eq!(super::num_threads().map(NonZeroUsize::get), Some(2)); |
46 | | assert_eq!(super::num_threads().map(NonZeroUsize::get), Some(3)); |
47 | | assert_eq!(super::num_threads().map(NonZeroUsize::get), Some(4)); |
48 | | assert_eq!(super::num_threads().map(NonZeroUsize::get), Some(5)); |
49 | | assert_eq!(super::num_threads().map(NonZeroUsize::get), Some(6)); |
50 | | } |
51 | | } |
52 | | |
53 | | #[test] |
54 | | fn is_single_threaded() { |
55 | | threaded! { |
56 | | assert_eq!(super::is_single_threaded(), Some(true)); |
57 | | assert_eq!(super::is_single_threaded(), Some(false)); |
58 | | assert_eq!(super::is_single_threaded(), Some(false)); |
59 | | assert_eq!(super::is_single_threaded(), Some(false)); |
60 | | assert_eq!(super::is_single_threaded(), Some(false)); |
61 | | assert_eq!(super::is_single_threaded(), Some(false)); |
62 | | } |
63 | | } |
64 | | } |