1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use std::num::NonZeroUsize;
#[cfg_attr(any(target_os = "linux", target_os = "android"), path = "linux.rs")]
#[cfg_attr(target_os = "freebsd", path = "freebsd.rs")]
#[cfg_attr(any(target_os = "macos", target_os = "ios"), path = "apple.rs")]
mod imp;
pub fn num_threads() -> Option<NonZeroUsize> {
imp::num_threads()
}
pub fn is_single_threaded() -> Option<bool> {
num_threads().map(|n| n.get() == 1)
}
#[cfg(test)]
mod test {
use std::num::NonZeroUsize;
macro_rules! threaded {
($first:expr;) => {
$first;
};
($first:expr; $($rest:expr;)*) => {
$first;
::std::thread::spawn(|| {
threaded!($($rest;)*);
})
.join()
.unwrap();
};
}
#[test]
fn num_threads() {
threaded! {
assert_eq!(super::num_threads().map(NonZeroUsize::get), Some(1));
assert_eq!(super::num_threads().map(NonZeroUsize::get), Some(2));
assert_eq!(super::num_threads().map(NonZeroUsize::get), Some(3));
assert_eq!(super::num_threads().map(NonZeroUsize::get), Some(4));
assert_eq!(super::num_threads().map(NonZeroUsize::get), Some(5));
assert_eq!(super::num_threads().map(NonZeroUsize::get), Some(6));
}
}
#[test]
fn is_single_threaded() {
threaded! {
assert_eq!(super::is_single_threaded(), Some(true));
assert_eq!(super::is_single_threaded(), Some(false));
assert_eq!(super::is_single_threaded(), Some(false));
assert_eq!(super::is_single_threaded(), Some(false));
assert_eq!(super::is_single_threaded(), Some(false));
assert_eq!(super::is_single_threaded(), Some(false));
}
}
}