Skip to main content

tessera_ui/
thread_utils.rs

1//! # Thread Utilities
2
3/// Thread-safety bound for abstractions that own GPU resources.
4///
5/// Native targets require `Send + Sync + 'static`; wasm requires only `'static`.
6#[cfg(not(target_family = "wasm"))]
7pub trait SendSync: Send + Sync + 'static {}
8#[cfg(not(target_family = "wasm"))]
9impl<T: Send + Sync + 'static> SendSync for T {}
10
11/// Thread-safety bound for abstractions that own GPU resources.
12///
13/// Requires only `'static` on wasm targets.
14#[cfg(target_family = "wasm")]
15pub trait SendSync: 'static {}
16#[cfg(target_family = "wasm")]
17impl<T: 'static> SendSync for T {}
18/// Sets the current thread's name for debugging and profiling on Unix and Windows.
19/// Names must follow platform-specific length limits. Other platforms do nothing.
20pub fn set_thread_name(name: &str) {
21    #[cfg(target_family = "unix")]
22    set_thread_name_unix(name);
23
24    #[cfg(target_os = "windows")]
25    set_thread_name_windows(name);
26
27    #[cfg(not(any(target_family = "unix", target_os = "windows")))]
28    {
29        let _ = name;
30    }
31}
32
33#[cfg(target_family = "unix")]
34fn set_thread_name_unix(name: &str) {
35    use std::ffi::CString;
36
37    let cname = CString::new(name).expect("thread name contains null bytes");
38
39    unsafe {
40        #[cfg(target_vendor = "apple")]
41        libc::pthread_setname_np(cname.as_ptr());
42        #[cfg(not(target_vendor = "apple"))]
43        libc::pthread_setname_np(libc::pthread_self(), cname.as_ptr());
44    }
45}
46
47#[cfg(target_os = "windows")]
48fn set_thread_name_windows(name: &str) {
49    use std::ffi::OsStr;
50    use std::os::windows::ffi::OsStrExt;
51
52    let name_wide: Vec<u16> = OsStr::new(name)
53        .encode_wide()
54        .chain(std::iter::once(0))
55        .collect();
56
57    unsafe {
58        use windows::{
59            Win32::System::Threading::{GetCurrentThread, SetThreadDescription},
60            core::PCWSTR,
61        };
62
63        let _ = SetThreadDescription(GetCurrentThread(), PCWSTR(name_wide.as_ptr()));
64    }
65}