5 use crate::sys::handle::Handle;
6 use crate::sys::stack_overflow;
7 use crate::time::Duration;
13 pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
20 // unsafe: see thread::Builder::spawn_unchecked for safety requirements
21 pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
22 let p = Box::into_raw(box p);
24 // FIXME On UNIX, we guard against stack sizes that are too small but
25 // that's because pthreads enforces that stacks are at least
26 // PTHREAD_STACK_MIN bytes big. Windows has no such lower limit, it's
27 // just that below a certain threshold you can't do anything useful.
28 // That threshold is application and architecture-specific, however.
29 // Round up to the next 64 kB because that's what the NT kernel does,
30 // might as well make it explicit.
31 let stack_size = (stack + 0xfffe) & (!0xfffe);
32 let ret = c::CreateThread(
37 c::STACK_SIZE_PARAM_IS_A_RESERVATION,
41 return if ret as usize == 0 {
42 // The thread failed to start and as a result p was not consumed. Therefore, it is
43 // safe to reconstruct the box so that it gets deallocated.
44 drop(Box::from_raw(p));
45 Err(io::Error::last_os_error())
47 Ok(Thread { handle: Handle::new(ret) })
50 extern "system" fn thread_start(main: *mut c_void) -> c::DWORD {
52 // Next, set up our stack overflow handler which may get triggered if we run
54 let _handler = stack_overflow::Handler::new();
55 // Finally, let's run some code.
56 Box::from_raw(main as *mut Box<dyn FnOnce()>)();
62 pub fn set_name(name: &CStr) {
63 if let Ok(utf8) = name.to_str() {
64 if let Ok(utf16) = to_u16s(utf8) {
66 c::SetThreadDescription(c::GetCurrentThread(), utf16.as_ptr());
73 let rc = unsafe { c::WaitForSingleObject(self.handle.raw(), c::INFINITE) };
74 if rc == c::WAIT_FAILED {
75 panic!("failed to join on thread: {}", io::Error::last_os_error());
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.
88 pub fn sleep(dur: Duration) {
89 unsafe { c::Sleep(super::dur2timeout(dur)) }
92 pub fn handle(&self) -> &Handle {
96 pub fn into_handle(self) -> Handle {
101 #[cfg_attr(test, allow(dead_code))]
104 pub unsafe fn current() -> Option<Guard> {
107 pub unsafe fn init() -> Option<Guard> {