Skip to main content

std\sys\thread/
windows.rs

1use core::ffi::c_void;
2
3use crate::ffi::CStr;
4use crate::num::NonZero;
5use crate::os::windows::io::{AsRawHandle, HandleOrNull};
6use crate::sys::handle::Handle;
7use crate::sys::pal::time::WaitableTimer;
8use crate::sys::pal::{dur2timeout, to_u16s};
9use crate::sys::{FromInner, c, stack_overflow};
10use crate::thread::ThreadInit;
11use crate::time::{Duration, Instant};
12use crate::{io, ptr};
13
14pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
15
16pub struct Thread {
17    handle: Handle,
18}
19
20impl Thread {
21    // unsafe: see thread::Builder::spawn_unchecked for safety requirements
22    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
23    pub unsafe fn new(stack: usize, init: Box<ThreadInit>) -> io::Result<Thread> {
24        let data = Box::into_raw(init);
25
26        // CreateThread rounds up values for the stack size to the nearest page size (at least 4kb).
27        // If a value of zero is given then the default stack size is used instead.
28        // SAFETY: `thread_start` has the right ABI for a thread's entry point.
29        // `data` is simply passed through to the new thread without being touched.
30        let ret = unsafe {
31            let ret = c::CreateThread(
32                ptr::null_mut(),
33                stack,
34                Some(thread_start),
35                data as *mut _,
36                c::STACK_SIZE_PARAM_IS_A_RESERVATION,
37                ptr::null_mut(),
38            );
39            HandleOrNull::from_raw_handle(ret)
40        };
41        return if let Ok(handle) = ret.try_into() {
42            Ok(Thread { handle: Handle::from_inner(handle) })
43        } else {
44            // The thread failed to start and as a result data was not consumed. Therefore, it is
45            // safe to reconstruct the box so that it gets deallocated.
46            unsafe { drop(Box::from_raw(data)) };
47            Err(io::Error::last_os_error())
48        };
49
50        unsafe extern "system" fn thread_start(data: *mut c_void) -> u32 {
51            // SAFETY: we are simply recreating the box that was leaked earlier.
52            let init = unsafe { Box::from_raw(data as *mut ThreadInit) };
53            let rust_start = init.init();
54
55            // Reserve some stack space for if we otherwise run out of stack.
56            stack_overflow::reserve_stack();
57
58            rust_start();
59            0
60        }
61    }
62
63    pub fn join(self) {
64        let rc = unsafe { c::WaitForSingleObject(self.handle.as_raw_handle(), c::INFINITE) };
65        if rc == c::WAIT_FAILED {
66            panic!("failed to join on thread: {}", io::Error::last_os_error());
67        }
68    }
69
70    pub fn handle(&self) -> &Handle {
71        &self.handle
72    }
73
74    pub fn into_handle(self) -> Handle {
75        self.handle
76    }
77}
78
79pub fn available_parallelism() -> io::Result<NonZero<usize>> {
80    let res = unsafe {
81        let mut sysinfo: c::SYSTEM_INFO = crate::mem::zeroed();
82        c::GetSystemInfo(&mut sysinfo);
83        sysinfo.dwNumberOfProcessors as usize
84    };
85    match res {
86        0 => Err(io::Error::UNKNOWN_THREAD_COUNT),
87        cpus => Ok(unsafe { NonZero::new_unchecked(cpus) }),
88    }
89}
90
91pub fn current_os_id() -> Option<u64> {
92    // SAFETY: FFI call with no preconditions.
93    let id: u32 = unsafe { c::GetCurrentThreadId() };
94
95    // A return value of 0 indicates failed lookup.
96    if id == 0 { None } else { Some(id.into()) }
97}
98
99pub fn set_name(name: &CStr) {
100    if let Ok(utf8) = name.to_str() {
101        if let Ok(utf16) = to_u16s(utf8) {
102            unsafe {
103                // SAFETY: the vec returned by `to_u16s` ends with a zero value
104                set_name_wide(&utf16)
105            }
106        };
107    };
108}
109
110/// # Safety
111///
112/// `name` must end with a zero value
113pub unsafe fn set_name_wide(name: &[u16]) {
114    unsafe { c::SetThreadDescription(c::GetCurrentThread(), name.as_ptr()) };
115}
116
117pub fn sleep(dur: Duration) {
118    fn high_precision_sleep(dur: Duration) -> Result<(), ()> {
119        let timer = WaitableTimer::high_resolution()?;
120        timer.set(dur)?;
121        timer.wait()
122    }
123    // Directly forward to `Sleep` for its zero duration behavior when indeed
124    // zero in order to skip the `Instant::now` calls, useless in this case.
125    if dur.is_zero() {
126        unsafe { c::Sleep(0) };
127    // Attempt to use high-precision sleep (Windows 10, version 1803+).
128    // On error, fallback to the standard `Sleep` function.
129    } else if high_precision_sleep(dur).is_err() {
130        let start = Instant::now();
131        unsafe { c::Sleep(dur2timeout(dur)) };
132
133        // See #149935: `Sleep` under Windows 7 and probably 8 as well seems a
134        // bit buggy for us as it can last less than the requested time while
135        // our API is meant to guarantee that. This is fixed by measuring the
136        // effective time difference and if needed, sleeping a bit more in
137        // order to ensure the duration is always exceeded. A fixed single
138        // millisecond works because `Sleep` operates based on a system-wide
139        // (until Windows 10 2004 that makes it process-local) interrupt timer
140        // that counts in "tick" units of ~15ms by default: a 1ms timeout
141        // therefore passes the next tick boundary.
142        if start.elapsed() < dur {
143            unsafe { c::Sleep(1) };
144        }
145    }
146}
147
148pub fn yield_now() {
149    // This function will return 0 if there are no other threads to execute,
150    // but this also means that the yield was useless so this isn't really a
151    // case that needs to be worried about.
152    unsafe {
153        c::SwitchToThread();
154    }
155}