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
//! is_main_thread is a bare bones library to simply check if the current thread is the main
//! thread is the most platform independent way possible
//!
//! The initial code for these checks was taken from the [winit crate](https://crates.io/crates/winit)
//! collected here for the main purpose of allowing winit to be an optional dependency but
//! also have consistent behaviour should you allow another windowing library which might expect you
//! to use the main thread but either way doesn't enforce it like winit.

mod platform_impl;

use platform_impl::platform;

#[cfg(any(target_os = "macos", target_os = "ios"))]
#[macro_use]
extern crate objc;

/// The sole simple function, to check whether or not the calling thread is the main thread
///
/// If the current platform is not supported by this test the 'None' is returned,
/// else 'Some(bool)' is returned with the appropriate value
pub fn is_main_thread() -> Option<bool> {
    platform::is_main_thread()
}

/// Of note, for the sanity test to succeed you must run cargo test
/// with the additional parameter '--test-threads=1' like:
///     'cargo test -- --test-threads=1'
#[cfg(test)]
mod tests {
    use super::is_main_thread;

    #[test]
    fn sanity_test() {
        let is_main = is_main_thread();

        assert_eq!(true, is_main.is_none() || is_main.unwrap());
    }

    #[test]
    fn threaded_test() {
        let is_main = std::thread::spawn(|| is_main_thread()).join().unwrap();

        assert_eq!(false, !is_main.is_none() && is_main.unwrap());
    }
}