]> git.lizzy.rs Git - rust.git/blob - src/librustrt/thread.rs
doc/guide-ffi: A few minor typo/language fixes
[rust.git] / src / librustrt / thread.rs
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.
4 //
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.
10
11 //! Native os-thread management
12 //!
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.
16
17 #![allow(non_camel_case_types)]
18
19 use core::prelude::*;
20
21 use alloc::owned::Box;
22 use core::mem;
23 use core::uint;
24 use libc;
25
26 use stack;
27
28 type StartFn = extern "C" fn(*mut libc::c_void) -> imp::rust_thread_return;
29
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,
34     joined: bool,
35     packet: Box<Option<T>>,
36 }
37
38 static DEFAULT_STACK_SIZE: uint = 1024 * 1024;
39
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
43 // and invoke it.
44 #[no_split_stack]
45 extern fn thread_start(main: *mut libc::c_void) -> imp::rust_thread_return {
46     unsafe {
47         stack::record_stack_bounds(0, uint::MAX);
48         let f: Box<proc()> = mem::transmute(main);
49         (*f)();
50         mem::transmute(0 as imp::rust_thread_return)
51     }
52 }
53
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
56 // type parameter).
57 impl Thread<()> {
58
59     /// Starts execution of a new OS thread.
60     ///
61     /// This function will not wait for the thread to join, but a handle to the
62     /// thread will be returned.
63     ///
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.
67     ///
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)
74     }
75
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> {
79
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
82         // so.
83         let packet = box None;
84         let packet2: *mut Option<T> = unsafe {
85             *mem::transmute::<&Box<Option<T>>, *const *mut Option<T>>(&packet)
86         };
87         let main = proc() unsafe { *packet2 = Some(main()); };
88         let native = unsafe { imp::create(stack, box main) };
89
90         Thread {
91             native: native,
92             joined: false,
93             packet: packet,
94         }
95     }
96
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.
99     ///
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)
105     }
106
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) {
110         unsafe {
111             let handle = imp::create(stack, box main);
112             imp::detach(handle);
113         }
114     }
115
116     /// Relinquishes the CPU slot that this OS-thread is currently using,
117     /// allowing another thread to run for awhile.
118     pub fn yield_now() {
119         unsafe { imp::yield_now(); }
120     }
121 }
122
123 impl<T: Send> Thread<T> {
124     /// Wait for this thread to finish, returning the result of the thread's
125     /// calculation.
126     pub fn join(mut self) -> T {
127         assert!(!self.joined);
128         unsafe { imp::join(self.native) };
129         self.joined = true;
130         assert!(self.packet.is_some());
131         self.packet.take_unwrap()
132     }
133 }
134
135 #[unsafe_destructor]
136 impl<T: Send> Drop for Thread<T> {
137     fn drop(&mut self) {
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.
140         if !self.joined {
141             unsafe { imp::join(self.native) };
142         }
143     }
144 }
145
146 #[cfg(windows)]
147 mod imp {
148     use core::prelude::*;
149
150     use alloc::owned::Box;
151     use core::cmp;
152     use core::mem;
153     use core::ptr;
154     use libc;
155     use libc::types::os::arch::extra::{LPSECURITY_ATTRIBUTES, SIZE_T, BOOL,
156                                        LPVOID, DWORD, LPDWORD, HANDLE};
157     use stack::RED_ZONE;
158
159     pub type rust_thread = HANDLE;
160     pub type rust_thread_return = DWORD;
161
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());
176
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);
181         }
182         return ret;
183     }
184
185     pub unsafe fn join(native: rust_thread) {
186         use libc::consts::os::extra::INFINITE;
187         WaitForSingleObject(native, INFINITE);
188     }
189
190     pub unsafe fn detach(native: rust_thread) {
191         assert!(libc::CloseHandle(native) != 0);
192     }
193
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.
198         SwitchToThread();
199     }
200
201     #[allow(non_snake_case_functions)]
202     extern "system" {
203         fn CreateThread(lpThreadAttributes: LPSECURITY_ATTRIBUTES,
204                         dwStackSize: SIZE_T,
205                         lpStartAddress: super::StartFn,
206                         lpParameter: LPVOID,
207                         dwCreationFlags: DWORD,
208                         lpThreadId: LPDWORD) -> HANDLE;
209         fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) -> DWORD;
210         fn SwitchToThread() -> BOOL;
211     }
212 }
213
214 #[cfg(unix)]
215 mod imp {
216     use core::prelude::*;
217
218     use alloc::owned::Box;
219     use core::cmp;
220     use core::mem;
221     use core::ptr;
222     use libc::consts::os::posix01::{PTHREAD_CREATE_JOINABLE, PTHREAD_STACK_MIN};
223     use libc;
224
225     use stack::RED_ZONE;
226
227     pub type rust_thread = libc::pthread_t;
228     pub type rust_thread_return = *mut u8;
229
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);
236
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) {
240             0 => {
241             },
242             libc::EINVAL => {
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);
251             },
252             errno => {
253                 // This cannot really happen.
254                 fail!("pthread_attr_setstacksize() error: {}", errno);
255             },
256         };
257
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);
261
262         if ret != 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);
266         }
267         native
268     }
269
270     pub unsafe fn join(native: rust_thread) {
271         assert_eq!(pthread_join(native, ptr::mut_null()), 0);
272     }
273
274     pub unsafe fn detach(native: rust_thread) {
275         assert_eq!(pthread_detach(native), 0);
276     }
277
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.
284     //
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;
292         extern {
293             #[linkage = "extern_weak"]
294             static __pthread_get_minstack: *const ();
295         }
296         if __pthread_get_minstack.is_null() {
297             PTHREAD_STACK_MIN
298         } else {
299             unsafe { mem::transmute::<*const (), F>(__pthread_get_minstack)(attr) }
300         }
301     }
302
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 {
307         PTHREAD_STACK_MIN
308     }
309
310     extern {
311         fn pthread_create(native: *mut libc::pthread_t,
312                           attr: *const libc::pthread_attr_t,
313                           f: super::StartFn,
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;
325     }
326 }
327
328 #[cfg(test)]
329 mod tests {
330     use super::Thread;
331
332     #[test]
333     fn smoke() { Thread::start(proc (){}).join(); }
334
335     #[test]
336     fn data() { assert_eq!(Thread::start(proc () { 1i }).join(), 1); }
337
338     #[test]
339     fn detached() { Thread::spawn(proc () {}) }
340
341     #[test]
342     fn small_stacks() {
343         assert_eq!(42i, Thread::start_stack(0, proc () 42i).join());
344         assert_eq!(42i, Thread::start_stack(1, proc () 42i).join());
345     }
346 }