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.
16 use libc::types::os::arch::extra::{LPSECURITY_ATTRIBUTES, SIZE_T, BOOL,
17 LPVOID, DWORD, LPDWORD, HANDLE};
19 use sys_common::stack::RED_ZONE;
20 use sys_common::thread::*;
22 pub type rust_thread = HANDLE;
23 pub type rust_thread_return = DWORD;
25 pub type StartFn = extern "system" fn(*mut libc::c_void) -> rust_thread_return;
28 pub extern "system" fn thread_start(main: *mut libc::c_void) -> rust_thread_return {
29 return start_thread(main);
33 pub unsafe fn main() -> uint {
37 pub unsafe fn current() -> uint {
41 pub unsafe fn init() {
45 pub unsafe fn create(stack: uint, p: Thunk) -> rust_thread {
46 let arg: *mut libc::c_void = mem::transmute(box p);
47 // FIXME On UNIX, we guard against stack sizes that are too small but
48 // that's because pthreads enforces that stacks are at least
49 // PTHREAD_STACK_MIN bytes big. Windows has no such lower limit, it's
50 // just that below a certain threshold you can't do anything useful.
51 // That threshold is application and architecture-specific, however.
52 // For now, the only requirement is that it's big enough to hold the
53 // red zone. Round up to the next 64 kB because that's what the NT
54 // kernel does, might as well make it explicit. With the current
55 // 20 kB red zone, that makes for a 64 kB minimum stack.
56 let stack_size = (cmp::max(stack, RED_ZONE) + 0xfffe) & (-0xfffe - 1);
57 let ret = CreateThread(ptr::null_mut(), stack_size as libc::size_t,
58 thread_start, arg, 0, ptr::null_mut());
61 // be sure to not leak the closure
62 let _p: Box<Thunk> = mem::transmute(arg);
63 panic!("failed to spawn native thread: {}", ret);
68 pub unsafe fn join(native: rust_thread) {
69 use libc::consts::os::extra::INFINITE;
70 WaitForSingleObject(native, INFINITE);
73 pub unsafe fn detach(native: rust_thread) {
74 assert!(libc::CloseHandle(native) != 0);
77 pub unsafe fn yield_now() {
78 // This function will return 0 if there are no other threads to execute,
79 // but this also means that the yield was useless so this isn't really a
80 // case that needs to be worried about.
84 #[allow(non_snake_case)]
86 fn CreateThread(lpThreadAttributes: LPSECURITY_ATTRIBUTES,
88 lpStartAddress: StartFn,
90 dwCreationFlags: DWORD,
91 lpThreadId: LPDWORD) -> HANDLE;
92 fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) -> DWORD;
93 fn SwitchToThread() -> BOOL;