1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use alloc::boxed::FnBox;
18 use sys::handle::Handle;
19 use sys_common::thread::*;
22 pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
29 pub unsafe fn new<'a>(stack: usize, p: Box<FnBox() + 'a>)
30 -> io::Result<Thread> {
33 // FIXME On UNIX, we guard against stack sizes that are too small but
34 // that's because pthreads enforces that stacks are at least
35 // PTHREAD_STACK_MIN bytes big. Windows has no such lower limit, it's
36 // just that below a certain threshold you can't do anything useful.
37 // That threshold is application and architecture-specific, however.
38 // Round up to the next 64 kB because that's what the NT kernel does,
39 // might as well make it explicit.
40 let stack_size = (stack + 0xfffe) & (!0xfffe);
41 let ret = c::CreateThread(ptr::null_mut(), stack_size,
42 thread_start, &*p as *const _ as *mut _,
45 return if ret as usize == 0 {
46 Err(io::Error::last_os_error())
48 mem::forget(p); // ownership passed to CreateThread
49 Ok(Thread { handle: Handle::new(ret) })
52 extern "system" fn thread_start(main: *mut c_void) -> c::DWORD {
53 unsafe { start_thread(main); }
58 pub fn set_name(_name: &CStr) {
59 // Windows threads are nameless
60 // The names in MSVC debugger are obtained using a "magic" exception,
61 // which requires a use of MS C++ extensions.
62 // See https://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
66 let rc = unsafe { c::WaitForSingleObject(self.handle.raw(), c::INFINITE) };
67 if rc == c::WAIT_FAILED {
68 panic!("failed to join on thread: {}",
69 io::Error::last_os_error());
74 // This function will return 0 if there are no other threads to execute,
75 // but this also means that the yield was useless so this isn't really a
76 // case that needs to be worried about.
77 unsafe { c::SwitchToThread(); }
80 pub fn sleep(dur: Duration) {
82 c::Sleep(super::dur2timeout(dur))
86 pub fn handle(&self) -> &Handle { &self.handle }
88 pub fn into_handle(self) -> Handle { self.handle }
91 #[cfg_attr(test, allow(dead_code))]
93 pub unsafe fn current() -> Option<usize> { None }
94 pub unsafe fn init() -> Option<usize> { None }