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