1 // Copyright 2013-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 //! Native os-thread management
13 //! This modules contains bindings necessary for managing OS-level threads.
14 //! These functions operate outside of the rust runtime, creating threads
15 //! which are not used for scheduling in any way.
17 #![allow(non_camel_case_types)]
21 use alloc::owned::Box;
28 type StartFn = extern "C" fn(*mut libc::c_void) -> imp::rust_thread_return;
30 /// This struct represents a native thread's state. This is used to join on an
31 /// existing thread created in the join-able state.
32 pub struct Thread<T> {
33 native: imp::rust_thread,
35 packet: Box<Option<T>>,
38 static DEFAULT_STACK_SIZE: uint = 1024 * 1024;
40 // This is the starting point of rust os threads. The first thing we do
41 // is make sure that we don't trigger __morestack (also why this has a
42 // no_split_stack annotation), and then we extract the main function
45 extern fn thread_start(main: *mut libc::c_void) -> imp::rust_thread_return {
47 stack::record_stack_bounds(0, uint::MAX);
48 let f: Box<proc()> = mem::transmute(main);
50 mem::transmute(0 as imp::rust_thread_return)
54 // There are two impl blocks b/c if T were specified at the top then it's just a
55 // pain to specify a type parameter on Thread::spawn (which doesn't need the
59 /// Starts execution of a new OS thread.
61 /// This function will not wait for the thread to join, but a handle to the
62 /// thread will be returned.
64 /// Note that the handle returned is used to acquire the return value of the
65 /// procedure `main`. The `join` function will wait for the thread to finish
66 /// and return the value that `main` generated.
68 /// Also note that the `Thread` returned will *always* wait for the thread
69 /// to finish executing. This means that even if `join` is not explicitly
70 /// called, when the `Thread` falls out of scope its destructor will block
71 /// waiting for the OS thread.
72 pub fn start<T: Send>(main: proc():Send -> T) -> Thread<T> {
73 Thread::start_stack(DEFAULT_STACK_SIZE, main)
76 /// Performs the same functionality as `start`, but specifies an explicit
77 /// stack size for the new thread.
78 pub fn start_stack<T: Send>(stack: uint, main: proc():Send -> T) -> Thread<T> {
80 // We need the address of the packet to fill in to be stable so when
81 // `main` fills it in it's still valid, so allocate an extra box to do
83 let packet = box None;
84 let packet2: *mut Option<T> = unsafe {
85 *mem::transmute::<&Box<Option<T>>, *const *mut Option<T>>(&packet)
87 let main = proc() unsafe { *packet2 = Some(main()); };
88 let native = unsafe { imp::create(stack, box main) };
97 /// This will spawn a new thread, but it will not wait for the thread to
98 /// finish, nor is it possible to wait for the thread to finish.
100 /// This corresponds to creating threads in the 'detached' state on unix
101 /// systems. Note that platforms may not keep the main program alive even if
102 /// there are detached thread still running around.
103 pub fn spawn(main: proc():Send) {
104 Thread::spawn_stack(DEFAULT_STACK_SIZE, main)
107 /// Performs the same functionality as `spawn`, but explicitly specifies a
108 /// stack size for the new thread.
109 pub fn spawn_stack(stack: uint, main: proc():Send) {
111 let handle = imp::create(stack, box main);
116 /// Relinquishes the CPU slot that this OS-thread is currently using,
117 /// allowing another thread to run for awhile.
119 unsafe { imp::yield_now(); }
123 impl<T: Send> Thread<T> {
124 /// Wait for this thread to finish, returning the result of the thread's
126 pub fn join(mut self) -> T {
127 assert!(!self.joined);
128 unsafe { imp::join(self.native) };
130 assert!(self.packet.is_some());
131 self.packet.take_unwrap()
136 impl<T: Send> Drop for Thread<T> {
138 // This is required for correctness. If this is not done then the thread
139 // would fill in a return box which no longer exists.
141 unsafe { imp::join(self.native) };
148 use core::prelude::*;
150 use alloc::owned::Box;
155 use libc::types::os::arch::extra::{LPSECURITY_ATTRIBUTES, SIZE_T, BOOL,
156 LPVOID, DWORD, LPDWORD, HANDLE};
159 pub type rust_thread = HANDLE;
160 pub type rust_thread_return = DWORD;
162 pub unsafe fn create(stack: uint, p: Box<proc():Send>) -> rust_thread {
163 let arg: *mut libc::c_void = mem::transmute(p);
164 // FIXME On UNIX, we guard against stack sizes that are too small but
165 // that's because pthreads enforces that stacks are at least
166 // PTHREAD_STACK_MIN bytes big. Windows has no such lower limit, it's
167 // just that below a certain threshold you can't do anything useful.
168 // That threshold is application and architecture-specific, however.
169 // For now, the only requirement is that it's big enough to hold the
170 // red zone. Round up to the next 64 kB because that's what the NT
171 // kernel does, might as well make it explicit. With the current
172 // 20 kB red zone, that makes for a 64 kB minimum stack.
173 let stack_size = (cmp::max(stack, RED_ZONE) + 0xfffe) & (-0xfffe - 1);
174 let ret = CreateThread(ptr::mut_null(), stack_size as libc::size_t,
175 super::thread_start, arg, 0, ptr::mut_null());
177 if ret as uint == 0 {
178 // be sure to not leak the closure
179 let _p: Box<proc():Send> = mem::transmute(arg);
180 fail!("failed to spawn native thread: {}", ret);
185 pub unsafe fn join(native: rust_thread) {
186 use libc::consts::os::extra::INFINITE;
187 WaitForSingleObject(native, INFINITE);
190 pub unsafe fn detach(native: rust_thread) {
191 assert!(libc::CloseHandle(native) != 0);
194 pub unsafe fn yield_now() {
195 // This function will return 0 if there are no other threads to execute,
196 // but this also means that the yield was useless so this isn't really a
197 // case that needs to be worried about.
201 #[allow(non_snake_case_functions)]
203 fn CreateThread(lpThreadAttributes: LPSECURITY_ATTRIBUTES,
205 lpStartAddress: super::StartFn,
207 dwCreationFlags: DWORD,
208 lpThreadId: LPDWORD) -> HANDLE;
209 fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) -> DWORD;
210 fn SwitchToThread() -> BOOL;
216 use core::prelude::*;
218 use alloc::owned::Box;
222 use libc::consts::os::posix01::{PTHREAD_CREATE_JOINABLE, PTHREAD_STACK_MIN};
227 pub type rust_thread = libc::pthread_t;
228 pub type rust_thread_return = *mut u8;
230 pub unsafe fn create(stack: uint, p: Box<proc():Send>) -> rust_thread {
231 let mut native: libc::pthread_t = mem::zeroed();
232 let mut attr: libc::pthread_attr_t = mem::zeroed();
233 assert_eq!(pthread_attr_init(&mut attr), 0);
234 assert_eq!(pthread_attr_setdetachstate(&mut attr,
235 PTHREAD_CREATE_JOINABLE), 0);
237 // Reserve room for the red zone, the runtime's stack of last resort.
238 let stack_size = cmp::max(stack, RED_ZONE + min_stack_size(&attr) as uint);
239 match pthread_attr_setstacksize(&mut attr, stack_size as libc::size_t) {
243 // EINVAL means |stack_size| is either too small or not a
244 // multiple of the system page size. Because it's definitely
245 // >= PTHREAD_STACK_MIN, it must be an alignment issue.
246 // Round up to the nearest page and try again.
247 let page_size = libc::sysconf(libc::_SC_PAGESIZE) as uint;
248 let stack_size = (stack_size + page_size - 1) &
249 (-(page_size as int - 1) as uint - 1);
250 assert_eq!(pthread_attr_setstacksize(&mut attr, stack_size as libc::size_t), 0);
253 // This cannot really happen.
254 fail!("pthread_attr_setstacksize() error: {}", errno);
258 let arg: *mut libc::c_void = mem::transmute(p);
259 let ret = pthread_create(&mut native, &attr, super::thread_start, arg);
260 assert_eq!(pthread_attr_destroy(&mut attr), 0);
263 // be sure to not leak the closure
264 let _p: Box<proc():Send> = mem::transmute(arg);
265 fail!("failed to spawn native thread: {}", ret);
270 pub unsafe fn join(native: rust_thread) {
271 assert_eq!(pthread_join(native, ptr::mut_null()), 0);
274 pub unsafe fn detach(native: rust_thread) {
275 assert_eq!(pthread_detach(native), 0);
278 pub unsafe fn yield_now() { assert_eq!(sched_yield(), 0); }
279 // glibc >= 2.15 has a __pthread_get_minstack() function that returns
280 // PTHREAD_STACK_MIN plus however many bytes are needed for thread-local
281 // storage. We need that information to avoid blowing up when a small stack
282 // is created in an application with big thread-local storage requirements.
283 // See #6233 for rationale and details.
285 // Link weakly to the symbol for compatibility with older versions of glibc.
286 // Assumes that we've been dynamically linked to libpthread but that is
287 // currently always the case. Note that you need to check that the symbol
288 // is non-null before calling it!
289 #[cfg(target_os = "linux")]
290 fn min_stack_size(attr: *const libc::pthread_attr_t) -> libc::size_t {
291 type F = unsafe extern "C" fn(*const libc::pthread_attr_t) -> libc::size_t;
293 #[linkage = "extern_weak"]
294 static __pthread_get_minstack: *const ();
296 if __pthread_get_minstack.is_null() {
299 unsafe { mem::transmute::<*const (), F>(__pthread_get_minstack)(attr) }
303 // __pthread_get_minstack() is marked as weak but extern_weak linkage is
304 // not supported on OS X, hence this kludge...
305 #[cfg(not(target_os = "linux"))]
306 fn min_stack_size(_: *const libc::pthread_attr_t) -> libc::size_t {
311 fn pthread_create(native: *mut libc::pthread_t,
312 attr: *const libc::pthread_attr_t,
314 value: *mut libc::c_void) -> libc::c_int;
315 fn pthread_join(native: libc::pthread_t,
316 value: *mut *mut libc::c_void) -> libc::c_int;
317 fn pthread_attr_init(attr: *mut libc::pthread_attr_t) -> libc::c_int;
318 fn pthread_attr_destroy(attr: *mut libc::pthread_attr_t) -> libc::c_int;
319 fn pthread_attr_setstacksize(attr: *mut libc::pthread_attr_t,
320 stack_size: libc::size_t) -> libc::c_int;
321 fn pthread_attr_setdetachstate(attr: *mut libc::pthread_attr_t,
322 state: libc::c_int) -> libc::c_int;
323 fn pthread_detach(thread: libc::pthread_t) -> libc::c_int;
324 fn sched_yield() -> libc::c_int;
333 fn smoke() { Thread::start(proc (){}).join(); }
336 fn data() { assert_eq!(Thread::start(proc () { 1i }).join(), 1); }
339 fn detached() { Thread::spawn(proc () {}) }
343 assert_eq!(42i, Thread::start_stack(0, proc () 42i).join());
344 assert_eq!(42i, Thread::start_stack(1, proc () 42i).join());