is_main_thread/lib.rs
1//! is_main_thread is a bare bones library to simply check if the current thread is the main
2//! thread is the most platform independent way possible
3//!
4//! The initial code for these checks was taken from the [winit crate](https://crates.io/crates/winit)
5//! collected here for the main purpose of allowing winit to be an optional dependency but
6//! also have consistent behaviour should you allow another windowing library which might expect you
7//! to use the main thread but either way doesn't enforce it like winit.
8
9mod platform_impl;
10
11use platform_impl::platform;
12
13#[cfg(any(target_os = "macos", target_os = "ios"))]
14#[macro_use]
15extern crate objc;
16
17/// The sole simple function, to check whether or not the calling thread is the main thread
18///
19/// If the current platform is not supported by this test the 'None' is returned,
20/// else 'Some(bool)' is returned with the appropriate value
21pub fn is_main_thread() -> Option<bool> {
22 platform::is_main_thread()
23}
24
25/// Of note, for the sanity test to succeed you must run cargo test
26/// with the additional parameter '--test-threads=1' like:
27/// 'cargo test -- --test-threads=1'
28#[cfg(test)]
29mod tests {
30 use super::is_main_thread;
31
32 #[test]
33 fn sanity_test() {
34 let is_main = is_main_thread();
35
36 assert_eq!(true, is_main.is_none() || is_main.unwrap());
37 }
38
39 #[test]
40 fn threaded_test() {
41 let is_main = std::thread::spawn(|| is_main_thread()).join().unwrap();
42
43 assert_eq!(false, !is_main.is_none() && is_main.unwrap());
44 }
45}