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