]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/windows/thread.rs
Rollup merge of #106779 - RReverser:patch-2, r=Mark-Simulacrum
[rust.git] / library / std / src / sys / windows / thread.rs
1 use crate::ffi::CStr;
2 use crate::io;
3 use crate::num::NonZeroUsize;
4 use crate::os::windows::io::AsRawHandle;
5 use crate::ptr;
6 use crate::sys::c;
7 use crate::sys::handle::Handle;
8 use crate::sys::stack_overflow;
9 use crate::sys_common::FromInner;
10 use crate::time::Duration;
11
12 use libc::c_void;
13
14 use super::to_u16s;
15
16 pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
17
18 pub struct Thread {
19     handle: Handle,
20 }
21
22 impl Thread {
23     // unsafe: see thread::Builder::spawn_unchecked for safety requirements
24     pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
25         let p = Box::into_raw(Box::new(p));
26
27         // FIXME On UNIX, we guard against stack sizes that are too small but
28         // that's because pthreads enforces that stacks are at least
29         // PTHREAD_STACK_MIN bytes big. Windows has no such lower limit, it's
30         // just that below a certain threshold you can't do anything useful.
31         // That threshold is application and architecture-specific, however.
32         let ret = c::CreateThread(
33             ptr::null_mut(),
34             stack,
35             thread_start,
36             p as *mut _,
37             c::STACK_SIZE_PARAM_IS_A_RESERVATION,
38             ptr::null_mut(),
39         );
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 p was not consumed. Therefore, it is
45             // safe to reconstruct the box so that it gets deallocated.
46             drop(Box::from_raw(p));
47             Err(io::Error::last_os_error())
48         };
49
50         extern "system" fn thread_start(main: *mut c_void) -> c::DWORD {
51             unsafe {
52                 // Next, set up our stack overflow handler which may get triggered if we run
53                 // out of stack.
54                 let _handler = stack_overflow::Handler::new();
55                 // Finally, let's run some code.
56                 Box::from_raw(main as *mut Box<dyn FnOnce()>)();
57             }
58             0
59         }
60     }
61
62     pub fn set_name(name: &CStr) {
63         if let Ok(utf8) = name.to_str() {
64             if let Ok(utf16) = to_u16s(utf8) {
65                 unsafe {
66                     c::SetThreadDescription(c::GetCurrentThread(), utf16.as_ptr());
67                 };
68             };
69         };
70     }
71
72     pub fn join(self) {
73         let rc = unsafe { c::WaitForSingleObject(self.handle.as_raw_handle(), c::INFINITE) };
74         if rc == c::WAIT_FAILED {
75             panic!("failed to join on thread: {}", io::Error::last_os_error());
76         }
77     }
78
79     pub fn yield_now() {
80         // This function will return 0 if there are no other threads to execute,
81         // but this also means that the yield was useless so this isn't really a
82         // case that needs to be worried about.
83         unsafe {
84             c::SwitchToThread();
85         }
86     }
87
88     pub fn sleep(dur: Duration) {
89         unsafe { c::Sleep(super::dur2timeout(dur)) }
90     }
91
92     pub fn handle(&self) -> &Handle {
93         &self.handle
94     }
95
96     pub fn into_handle(self) -> Handle {
97         self.handle
98     }
99 }
100
101 pub fn available_parallelism() -> io::Result<NonZeroUsize> {
102     let res = unsafe {
103         let mut sysinfo: c::SYSTEM_INFO = crate::mem::zeroed();
104         c::GetSystemInfo(&mut sysinfo);
105         sysinfo.dwNumberOfProcessors as usize
106     };
107     match res {
108         0 => Err(io::const_io_error!(
109             io::ErrorKind::NotFound,
110             "The number of hardware threads is not known for the target platform",
111         )),
112         cpus => Ok(unsafe { NonZeroUsize::new_unchecked(cpus) }),
113     }
114 }
115
116 #[cfg_attr(test, allow(dead_code))]
117 pub mod guard {
118     pub type Guard = !;
119     pub unsafe fn current() -> Option<Guard> {
120         None
121     }
122     pub unsafe fn init() -> Option<Guard> {
123         None
124     }
125 }