]> git.lizzy.rs Git - rust.git/blob - src/libstd/thread/mod.rs
Stabilize basic timeout functionality
[rust.git] / src / libstd / thread / mod.rs
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.
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 threads
12 //!
13 //! ## The threading model
14 //!
15 //! An executing Rust program consists of a collection of native OS threads,
16 //! each with their own stack and local state.
17 //!
18 //! Communication between threads can be done through
19 //! [channels](../../std/sync/mpsc/index.html), Rust's message-passing
20 //! types, along with [other forms of thread
21 //! synchronization](../../std/sync/index.html) and shared-memory data
22 //! structures. In particular, types that are guaranteed to be
23 //! threadsafe are easily shared between threads using the
24 //! atomically-reference-counted container,
25 //! [`Arc`](../../std/sync/struct.Arc.html).
26 //!
27 //! Fatal logic errors in Rust cause *thread panic*, during which
28 //! a thread will unwind the stack, running destructors and freeing
29 //! owned resources. Thread panic is unrecoverable from within
30 //! the panicking thread (i.e. there is no 'try/catch' in Rust), but
31 //! the panic may optionally be detected from a different thread. If
32 //! the main thread panics, the application will exit with a non-zero
33 //! exit code.
34 //!
35 //! When the main thread of a Rust program terminates, the entire program shuts
36 //! down, even if other threads are still running. However, this module provides
37 //! convenient facilities for automatically waiting for the termination of a
38 //! child thread (i.e., join).
39 //!
40 //! ## The `Thread` type
41 //!
42 //! Threads are represented via the `Thread` type, which you can
43 //! get in one of two ways:
44 //!
45 //! * By spawning a new thread, e.g. using the `thread::spawn` function.
46 //! * By requesting the current thread, using the `thread::current` function.
47 //!
48 //! Threads can be named, and provide some built-in support for low-level
49 //! synchronization (described below).
50 //!
51 //! The `thread::current()` function is available even for threads not spawned
52 //! by the APIs of this module.
53 //!
54 //! ## Spawning a thread
55 //!
56 //! A new thread can be spawned using the `thread::spawn` function:
57 //!
58 //! ```rust
59 //! use std::thread;
60 //!
61 //! thread::spawn(move || {
62 //!     // some work here
63 //! });
64 //! ```
65 //!
66 //! In this example, the spawned thread is "detached" from the current
67 //! thread. This means that it can outlive its parent (the thread that spawned
68 //! it), unless this parent is the main thread.
69 //!
70 //! ## Scoped threads
71 //!
72 //! Often a parent thread uses a child thread to perform some particular task,
73 //! and at some point must wait for the child to complete before continuing.
74 //! For this scenario, use the `thread::scoped` function:
75 //!
76 //! ```rust
77 //! use std::thread;
78 //!
79 //! let guard = thread::scoped(move || {
80 //!     // some work here
81 //! });
82 //!
83 //! // do some other work in the meantime
84 //! let output = guard.join();
85 //! ```
86 //!
87 //! The `scoped` function doesn't return a `Thread` directly; instead,
88 //! it returns a *join guard*. The join guard is an RAII-style guard
89 //! that will automatically join the child thread (block until it
90 //! terminates) when it is dropped. You can join the child thread in
91 //! advance by calling the `join` method on the guard, which will also
92 //! return the result produced by the thread.  A handle to the thread
93 //! itself is available via the `thread` method of the join guard.
94 //!
95 //! ## Configuring threads
96 //!
97 //! A new thread can be configured before it is spawned via the `Builder` type,
98 //! which currently allows you to set the name, stack size, and writers for
99 //! `println!` and `panic!` for the child thread:
100 //!
101 //! ```rust
102 //! use std::thread;
103 //!
104 //! thread::Builder::new().name("child1".to_string()).spawn(move || {
105 //!     println!("Hello, world!");
106 //! });
107 //! ```
108 //!
109 //! ## Blocking support: park and unpark
110 //!
111 //! Every thread is equipped with some basic low-level blocking support, via the
112 //! `park` and `unpark` functions.
113 //!
114 //! Conceptually, each `Thread` handle has an associated token, which is
115 //! initially not present:
116 //!
117 //! * The `thread::park()` function blocks the current thread unless or until
118 //!   the token is available for its thread handle, at which point it atomically
119 //!   consumes the token. It may also return *spuriously*, without consuming the
120 //!   token. `thread::park_timeout()` does the same, but allows specifying a
121 //!   maximum time to block the thread for.
122 //!
123 //! * The `unpark()` method on a `Thread` atomically makes the token available
124 //!   if it wasn't already.
125 //!
126 //! In other words, each `Thread` acts a bit like a semaphore with initial count
127 //! 0, except that the semaphore is *saturating* (the count cannot go above 1),
128 //! and can return spuriously.
129 //!
130 //! The API is typically used by acquiring a handle to the current thread,
131 //! placing that handle in a shared data structure so that other threads can
132 //! find it, and then `park`ing. When some desired condition is met, another
133 //! thread calls `unpark` on the handle.
134 //!
135 //! The motivation for this design is twofold:
136 //!
137 //! * It avoids the need to allocate mutexes and condvars when building new
138 //!   synchronization primitives; the threads already provide basic blocking/signaling.
139 //!
140 //! * It can be implemented very efficiently on many platforms.
141 //!
142 //! ## Thread-local storage
143 //!
144 //! This module also provides an implementation of thread local storage for Rust
145 //! programs. Thread local storage is a method of storing data into a global
146 //! variable which each thread in the program will have its own copy of.
147 //! Threads do not share this data, so accesses do not need to be synchronized.
148 //!
149 //! At a high level, this module provides two variants of storage:
150 //!
151 //! * Owned thread-local storage. This is a type of thread local key which
152 //!   owns the value that it contains, and will destroy the value when the
153 //!   thread exits. This variant is created with the `thread_local!` macro and
154 //!   can contain any value which is `'static` (no borrowed pointers).
155 //!
156 //! * Scoped thread-local storage. This type of key is used to store a reference
157 //!   to a value into local storage temporarily for the scope of a function
158 //!   call. There are no restrictions on what types of values can be placed
159 //!   into this key.
160 //!
161 //! Both forms of thread local storage provide an accessor function, `with`,
162 //! which will yield a shared reference to the value to the specified
163 //! closure. Thread-local keys only allow shared access to values as there is no
164 //! way to guarantee uniqueness if a mutable borrow was allowed. Most values
165 //! will want to make use of some form of **interior mutability** through the
166 //! `Cell` or `RefCell` types.
167
168 #![stable(feature = "rust1", since = "1.0.0")]
169
170 #[stable(feature = "rust1", since = "1.0.0")]
171 pub use self::__local::{LocalKey, LocalKeyState};
172
173 #[unstable(feature = "scoped_tls",
174             reason = "scoped TLS has yet to have wide enough use to fully consider \
175                       stabilizing its interface")]
176 pub use self::__scoped::ScopedKey;
177
178 use prelude::v1::*;
179
180 use any::Any;
181 use cell::UnsafeCell;
182 use fmt;
183 use io;
184 use marker::PhantomData;
185 use rt::{self, unwind};
186 use sync::{Mutex, Condvar, Arc};
187 use sys::thread as imp;
188 use sys_common::{stack, thread_info};
189 use thunk::Thunk;
190 use time::Duration;
191
192 ////////////////////////////////////////////////////////////////////////////////
193 // Thread-local storage
194 ////////////////////////////////////////////////////////////////////////////////
195
196 #[macro_use]
197 #[doc(hidden)]
198 #[path = "local.rs"] pub mod __local;
199
200 #[macro_use]
201 #[doc(hidden)]
202 #[path = "scoped.rs"] pub mod __scoped;
203
204 ////////////////////////////////////////////////////////////////////////////////
205 // Builder
206 ////////////////////////////////////////////////////////////////////////////////
207
208 /// Thread configuration. Provides detailed control over the properties
209 /// and behavior of new threads.
210 #[stable(feature = "rust1", since = "1.0.0")]
211 pub struct Builder {
212     // A name for the thread-to-be, for identification in panic messages
213     name: Option<String>,
214     // The size of the stack for the spawned thread
215     stack_size: Option<usize>,
216 }
217
218 impl Builder {
219     /// Generate the base configuration for spawning a thread, from which
220     /// configuration methods can be chained.
221     #[stable(feature = "rust1", since = "1.0.0")]
222     pub fn new() -> Builder {
223         Builder {
224             name: None,
225             stack_size: None,
226         }
227     }
228
229     /// Name the thread-to-be. Currently the name is used for identification
230     /// only in panic messages.
231     #[stable(feature = "rust1", since = "1.0.0")]
232     pub fn name(mut self, name: String) -> Builder {
233         self.name = Some(name);
234         self
235     }
236
237     /// Set the size of the stack for the new thread.
238     #[stable(feature = "rust1", since = "1.0.0")]
239     pub fn stack_size(mut self, size: usize) -> Builder {
240         self.stack_size = Some(size);
241         self
242     }
243
244     /// Spawn a new thread, and return a join handle for it.
245     ///
246     /// The child thread may outlive the parent (unless the parent thread
247     /// is the main thread; the whole process is terminated when the main
248     /// thread finishes.) The join handle can be used to block on
249     /// termination of the child thread, including recovering its panics.
250     ///
251     /// # Errors
252     ///
253     /// Unlike the `spawn` free function, this method yields an
254     /// `io::Result` to capture any failure to create the thread at
255     /// the OS level.
256     #[stable(feature = "rust1", since = "1.0.0")]
257     pub fn spawn<F>(self, f: F) -> io::Result<JoinHandle> where
258         F: FnOnce(), F: Send + 'static
259     {
260         self.spawn_inner(Thunk::new(f)).map(|i| JoinHandle(i))
261     }
262
263     /// Spawn a new child thread that must be joined within a given
264     /// scope, and return a `JoinGuard`.
265     ///
266     /// The join guard can be used to explicitly join the child thread (via
267     /// `join`), returning `Result<T>`, or it will implicitly join the child
268     /// upon being dropped. Because the child thread may refer to data on the
269     /// current thread's stack (hence the "scoped" name), it cannot be detached;
270     /// it *must* be joined before the relevant stack frame is popped. See the
271     /// module documentation for additional details.
272     ///
273     /// # Errors
274     ///
275     /// Unlike the `scoped` free function, this method yields an
276     /// `io::Result` to capture any failure to create the thread at
277     /// the OS level.
278     #[stable(feature = "rust1", since = "1.0.0")]
279     pub fn scoped<'a, T, F>(self, f: F) -> io::Result<JoinGuard<'a, T>> where
280         T: Send + 'a, F: FnOnce() -> T, F: Send + 'a
281     {
282         self.spawn_inner(Thunk::new(f)).map(|inner| {
283             JoinGuard { inner: inner, _marker: PhantomData }
284         })
285     }
286
287     fn spawn_inner<T: Send>(self, f: Thunk<(), T>) -> io::Result<JoinInner<T>> {
288         let Builder { name, stack_size } = self;
289
290         let stack_size = stack_size.unwrap_or(rt::min_stack());
291
292         let my_thread = Thread::new(name);
293         let their_thread = my_thread.clone();
294
295         let my_packet = Packet(Arc::new(UnsafeCell::new(None)));
296         let their_packet = Packet(my_packet.0.clone());
297
298         // Spawning a new OS thread guarantees that __morestack will never get
299         // triggered, but we must manually set up the actual stack bounds once
300         // this function starts executing. This raises the lower limit by a bit
301         // because by the time that this function is executing we've already
302         // consumed at least a little bit of stack (we don't know the exact byte
303         // address at which our stack started).
304         let main = move || {
305             let something_around_the_top_of_the_stack = 1;
306             let addr = &something_around_the_top_of_the_stack as *const i32;
307             let my_stack_top = addr as usize;
308             let my_stack_bottom = my_stack_top - stack_size + 1024;
309             unsafe {
310                 if let Some(name) = their_thread.name() {
311                     imp::set_name(name);
312                 }
313                 stack::record_os_managed_stack_bounds(my_stack_bottom,
314                                                       my_stack_top);
315                 thread_info::set(imp::guard::current(), their_thread);
316             }
317
318             let mut output = None;
319             let try_result = {
320                 let ptr = &mut output;
321
322                 // There are two primary reasons that general try/catch is
323                 // unsafe. The first is that we do not support nested
324                 // try/catch. The fact that this is happening in a newly-spawned
325                 // thread suffices. The second is that unwinding while unwinding
326                 // is not defined.  We take care of that by having an
327                 // 'unwinding' flag in the thread itself. For these reasons,
328                 // this unsafety should be ok.
329                 unsafe {
330                     unwind::try(move || *ptr = Some(f.invoke(())))
331                 }
332             };
333             unsafe {
334                 *their_packet.0.get() = Some(match (output, try_result) {
335                     (Some(data), Ok(_)) => Ok(data),
336                     (None, Err(cause)) => Err(cause),
337                     _ => unreachable!()
338                 });
339             }
340         };
341
342         Ok(JoinInner {
343             native: try!(unsafe { imp::create(stack_size, Thunk::new(main)) }),
344             thread: my_thread,
345             packet: my_packet,
346             joined: false,
347         })
348     }
349 }
350
351 ////////////////////////////////////////////////////////////////////////////////
352 // Free functions
353 ////////////////////////////////////////////////////////////////////////////////
354
355 /// Spawn a new thread, returning a `JoinHandle` for it.
356 ///
357 /// The join handle will implicitly *detach* the child thread upon being
358 /// dropped. In this case, the child thread may outlive the parent (unless
359 /// the parent thread is the main thread; the whole process is terminated when
360 /// the main thread finishes.) Additionally, the join handle provides a `join`
361 /// method that can be used to join the child thread. If the child thread
362 /// panics, `join` will return an `Err` containing the argument given to
363 /// `panic`.
364 ///
365 /// # Panics
366 ///
367 /// Panicks if the OS fails to create a thread; use `Builder::spawn`
368 /// to recover from such errors.
369 #[stable(feature = "rust1", since = "1.0.0")]
370 pub fn spawn<F>(f: F) -> JoinHandle where F: FnOnce(), F: Send + 'static {
371     Builder::new().spawn(f).unwrap()
372 }
373
374 /// Spawn a new *scoped* thread, returning a `JoinGuard` for it.
375 ///
376 /// The join guard can be used to explicitly join the child thread (via
377 /// `join`), returning `Result<T>`, or it will implicitly join the child
378 /// upon being dropped. Because the child thread may refer to data on the
379 /// current thread's stack (hence the "scoped" name), it cannot be detached;
380 /// it *must* be joined before the relevant stack frame is popped. See the
381 /// module documentation for additional details.
382 ///
383 /// # Panics
384 ///
385 /// Panicks if the OS fails to create a thread; use `Builder::scoped`
386 /// to recover from such errors.
387 #[stable(feature = "rust1", since = "1.0.0")]
388 pub fn scoped<'a, T, F>(f: F) -> JoinGuard<'a, T> where
389     T: Send + 'a, F: FnOnce() -> T, F: Send + 'a
390 {
391     Builder::new().scoped(f).unwrap()
392 }
393
394 /// Gets a handle to the thread that invokes it.
395 #[stable(feature = "rust1", since = "1.0.0")]
396 pub fn current() -> Thread {
397     thread_info::current_thread()
398 }
399
400 /// Cooperatively give up a timeslice to the OS scheduler.
401 #[stable(feature = "rust1", since = "1.0.0")]
402 pub fn yield_now() {
403     unsafe { imp::yield_now() }
404 }
405
406 /// Determines whether the current thread is unwinding because of panic.
407 #[inline]
408 #[stable(feature = "rust1", since = "1.0.0")]
409 pub fn panicking() -> bool {
410     unwind::panicking()
411 }
412
413 /// Invoke a closure, capturing the cause of panic if one occurs.
414 ///
415 /// This function will return `Ok(())` if the closure does not panic, and will
416 /// return `Err(cause)` if the closure panics. The `cause` returned is the
417 /// object with which panic was originally invoked.
418 ///
419 /// It is currently undefined behavior to unwind from Rust code into foreign
420 /// code, so this function is particularly useful when Rust is called from
421 /// another language (normally C). This can run arbitrary Rust code, capturing a
422 /// panic and allowing a graceful handling of the error.
423 ///
424 /// It is **not** recommended to use this function for a general try/catch
425 /// mechanism. The `Result` type is more appropriate to use for functions that
426 /// can fail on a regular basis.
427 ///
428 /// The closure provided is required to adhere to the `'static` bound to ensure
429 /// that it cannot reference data in the parent stack frame, mitigating problems
430 /// with exception safety. Furthermore, a `Send` bound is also required,
431 /// providing the same safety guarantees as `thread::spawn` (ensuring the
432 /// closure is properly isolated from the parent).
433 ///
434 /// # Examples
435 ///
436 /// ```
437 /// # #![feature(catch_panic)]
438 /// use std::thread;
439 ///
440 /// let result = thread::catch_panic(|| {
441 ///     println!("hello!");
442 /// });
443 /// assert!(result.is_ok());
444 ///
445 /// let result = thread::catch_panic(|| {
446 ///     panic!("oh no!");
447 /// });
448 /// assert!(result.is_err());
449 /// ```
450 #[unstable(feature = "catch_panic", reason = "recent API addition")]
451 pub fn catch_panic<F, R>(f: F) -> Result<R>
452     where F: FnOnce() -> R + Send + 'static
453 {
454     let mut result = None;
455     unsafe {
456         let result = &mut result;
457         try!(::rt::unwind::try(move || *result = Some(f())))
458     }
459     Ok(result.unwrap())
460 }
461
462 /// Put the current thread to sleep for the specified amount of time.
463 ///
464 /// The thread may sleep longer than the duration specified due to scheduling
465 /// specifics or platform-dependent functionality. Note that on unix platforms
466 /// this function will not return early due to a signal being received or a
467 /// spurious wakeup.
468 #[stable(feature = "rust1", since = "1.0.0")]
469 pub fn sleep_ms(ms: u32) {
470     imp::sleep(Duration::milliseconds(ms as i64))
471 }
472
473 /// Deprecated: use `sleep_ms` instead.
474 #[unstable(feature = "thread_sleep",
475            reason = "recently added, needs an RFC, and `Duration` itself is \
476                      unstable")]
477 #[deprecated(since = "1.0.0", reason = "use sleep_ms instead")]
478 pub fn sleep(dur: Duration) {
479     imp::sleep(dur)
480 }
481
482 /// Block unless or until the current thread's token is made available (may wake spuriously).
483 ///
484 /// See the module doc for more detail.
485 //
486 // The implementation currently uses the trivial strategy of a Mutex+Condvar
487 // with wakeup flag, which does not actually allow spurious wakeups. In the
488 // future, this will be implemented in a more efficient way, perhaps along the lines of
489 //   http://cr.openjdk.java.net/~stefank/6989984.1/raw_files/new/src/os/linux/vm/os_linux.cpp
490 // or futuxes, and in either case may allow spurious wakeups.
491 #[stable(feature = "rust1", since = "1.0.0")]
492 pub fn park() {
493     let thread = current();
494     let mut guard = thread.inner.lock.lock().unwrap();
495     while !*guard {
496         guard = thread.inner.cvar.wait(guard).unwrap();
497     }
498     *guard = false;
499 }
500
501 /// Block unless or until the current thread's token is made available or
502 /// the specified duration has been reached (may wake spuriously).
503 ///
504 /// The semantics of this function are equivalent to `park()` except that the
505 /// thread will be blocked for roughly no longer than *duration*. This method
506 /// should not be used for precise timing due to anomalies such as
507 /// preemption or platform differences that may not cause the maximum
508 /// amount of time waited to be precisely *duration* long.
509 ///
510 /// See the module doc for more detail.
511 #[stable(feature = "rust1", since = "1.0.0")]
512 pub fn park_timeout_ms(ms: u32) {
513     let thread = current();
514     let mut guard = thread.inner.lock.lock().unwrap();
515     if !*guard {
516         let (g, _) = thread.inner.cvar.wait_timeout_ms(guard, ms).unwrap();
517         guard = g;
518     }
519     *guard = false;
520 }
521
522 /// Deprecated: use `park_timeout_ms`
523 #[unstable(feature = "std_misc", reason = "recently introduced, depends on Duration")]
524 #[deprecated(since = "1.0.0", reason = "use park_timeout_ms instead")]
525 pub fn park_timeout(duration: Duration) {
526     park_timeout_ms(duration.num_milliseconds() as u32)
527 }
528
529 ////////////////////////////////////////////////////////////////////////////////
530 // Thread
531 ////////////////////////////////////////////////////////////////////////////////
532
533 /// The internal representation of a `Thread` handle
534 struct Inner {
535     name: Option<String>,
536     lock: Mutex<bool>,          // true when there is a buffered unpark
537     cvar: Condvar,
538 }
539
540 unsafe impl Sync for Inner {}
541
542 #[derive(Clone)]
543 #[stable(feature = "rust1", since = "1.0.0")]
544 /// A handle to a thread.
545 pub struct Thread {
546     inner: Arc<Inner>,
547 }
548
549 impl Thread {
550     // Used only internally to construct a thread object without spawning
551     fn new(name: Option<String>) -> Thread {
552         Thread {
553             inner: Arc::new(Inner {
554                 name: name,
555                 lock: Mutex::new(false),
556                 cvar: Condvar::new(),
557             })
558         }
559     }
560
561     /// Atomically makes the handle's token available if it is not already.
562     ///
563     /// See the module doc for more detail.
564     #[stable(feature = "rust1", since = "1.0.0")]
565     pub fn unpark(&self) {
566         let mut guard = self.inner.lock.lock().unwrap();
567         if !*guard {
568             *guard = true;
569             self.inner.cvar.notify_one();
570         }
571     }
572
573     /// Get the thread's name.
574     #[stable(feature = "rust1", since = "1.0.0")]
575     pub fn name(&self) -> Option<&str> {
576         self.inner.name.as_ref().map(|s| &**s)
577     }
578 }
579
580 #[stable(feature = "rust1", since = "1.0.0")]
581 impl fmt::Debug for Thread {
582     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
583         fmt::Debug::fmt(&self.name(), f)
584     }
585 }
586
587 // a hack to get around privacy restrictions
588 impl thread_info::NewThread for Thread {
589     fn new(name: Option<String>) -> Thread { Thread::new(name) }
590 }
591
592 ////////////////////////////////////////////////////////////////////////////////
593 // JoinHandle and JoinGuard
594 ////////////////////////////////////////////////////////////////////////////////
595
596 /// Indicates the manner in which a thread exited.
597 ///
598 /// A thread that completes without panicking is considered to exit successfully.
599 #[stable(feature = "rust1", since = "1.0.0")]
600 pub type Result<T> = ::result::Result<T, Box<Any + Send + 'static>>;
601
602 struct Packet<T>(Arc<UnsafeCell<Option<Result<T>>>>);
603
604 unsafe impl<T:Send> Send for Packet<T> {}
605 unsafe impl<T> Sync for Packet<T> {}
606
607 /// Inner representation for JoinHandle and JoinGuard
608 struct JoinInner<T> {
609     native: imp::rust_thread,
610     thread: Thread,
611     packet: Packet<T>,
612     joined: bool,
613 }
614
615 impl<T> JoinInner<T> {
616     fn join(&mut self) -> Result<T> {
617         assert!(!self.joined);
618         unsafe { imp::join(self.native) };
619         self.joined = true;
620         unsafe {
621             (*self.packet.0.get()).take().unwrap()
622         }
623     }
624 }
625
626 /// An owned permission to join on a thread (block on its termination).
627 ///
628 /// Unlike a `JoinGuard`, a `JoinHandle` *detaches* the child thread
629 /// when it is dropped, rather than automatically joining on drop.
630 ///
631 /// Due to platform restrictions, it is not possible to `Clone` this
632 /// handle: the ability to join a child thread is a uniquely-owned
633 /// permission.
634 #[stable(feature = "rust1", since = "1.0.0")]
635 pub struct JoinHandle(JoinInner<()>);
636
637 impl JoinHandle {
638     /// Extract a handle to the underlying thread
639     #[stable(feature = "rust1", since = "1.0.0")]
640     pub fn thread(&self) -> &Thread {
641         &self.0.thread
642     }
643
644     /// Wait for the associated thread to finish.
645     ///
646     /// If the child thread panics, `Err` is returned with the parameter given
647     /// to `panic`.
648     #[stable(feature = "rust1", since = "1.0.0")]
649     pub fn join(mut self) -> Result<()> {
650         self.0.join()
651     }
652 }
653
654 #[stable(feature = "rust1", since = "1.0.0")]
655 impl Drop for JoinHandle {
656     fn drop(&mut self) {
657         if !self.0.joined {
658             unsafe { imp::detach(self.0.native) }
659         }
660     }
661 }
662
663 /// An RAII-style guard that will block until thread termination when dropped.
664 ///
665 /// The type `T` is the return type for the thread's main function.
666 ///
667 /// Joining on drop is necessary to ensure memory safety when stack
668 /// data is shared between a parent and child thread.
669 ///
670 /// Due to platform restrictions, it is not possible to `Clone` this
671 /// handle: the ability to join a child thread is a uniquely-owned
672 /// permission.
673 #[must_use = "thread will be immediately joined if `JoinGuard` is not used"]
674 #[stable(feature = "rust1", since = "1.0.0")]
675 pub struct JoinGuard<'a, T: Send + 'a> {
676     inner: JoinInner<T>,
677     _marker: PhantomData<&'a T>,
678 }
679
680 #[stable(feature = "rust1", since = "1.0.0")]
681 unsafe impl<'a, T: Send + 'a> Sync for JoinGuard<'a, T> {}
682
683 impl<'a, T: Send + 'a> JoinGuard<'a, T> {
684     /// Extract a handle to the thread this guard will join on.
685     #[stable(feature = "rust1", since = "1.0.0")]
686     pub fn thread(&self) -> &Thread {
687         &self.inner.thread
688     }
689
690     /// Wait for the associated thread to finish, returning the result of the
691     /// thread's calculation.
692     ///
693     /// # Panics
694     ///
695     /// Panics on the child thread are propagated by panicking the parent.
696     #[stable(feature = "rust1", since = "1.0.0")]
697     pub fn join(mut self) -> T {
698         match self.inner.join() {
699             Ok(res) => res,
700             Err(_) => panic!("child thread {:?} panicked", self.thread()),
701         }
702     }
703 }
704
705 #[unsafe_destructor]
706 #[stable(feature = "rust1", since = "1.0.0")]
707 impl<'a, T: Send + 'a> Drop for JoinGuard<'a, T> {
708     fn drop(&mut self) {
709         if !self.inner.joined {
710             if self.inner.join().is_err() {
711                 panic!("child thread {:?} panicked", self.thread());
712             }
713         }
714     }
715 }
716
717 ////////////////////////////////////////////////////////////////////////////////
718 // Tests
719 ////////////////////////////////////////////////////////////////////////////////
720
721 #[cfg(test)]
722 mod test {
723     use prelude::v1::*;
724
725     use any::Any;
726     use sync::mpsc::{channel, Sender};
727     use result;
728     use std::old_io::{ChanReader, ChanWriter};
729     use super::{Builder};
730     use thread;
731     use thunk::Thunk;
732     use time::Duration;
733     use u32;
734
735     // !!! These tests are dangerous. If something is buggy, they will hang, !!!
736     // !!! instead of exiting cleanly. This might wedge the buildbots.       !!!
737
738     #[test]
739     fn test_unnamed_thread() {
740         thread::spawn(move|| {
741             assert!(thread::current().name().is_none());
742         }).join().ok().unwrap();
743     }
744
745     #[test]
746     fn test_named_thread() {
747         Builder::new().name("ada lovelace".to_string()).scoped(move|| {
748             assert!(thread::current().name().unwrap() == "ada lovelace".to_string());
749         }).unwrap().join();
750     }
751
752     #[test]
753     fn test_run_basic() {
754         let (tx, rx) = channel();
755         thread::spawn(move|| {
756             tx.send(()).unwrap();
757         });
758         rx.recv().unwrap();
759     }
760
761     #[test]
762     fn test_join_success() {
763         assert!(thread::scoped(move|| -> String {
764             "Success!".to_string()
765         }).join() == "Success!");
766     }
767
768     #[test]
769     fn test_join_panic() {
770         match thread::spawn(move|| {
771             panic!()
772         }).join() {
773             result::Result::Err(_) => (),
774             result::Result::Ok(()) => panic!()
775         }
776     }
777
778     #[test]
779     fn test_scoped_success() {
780         let res = thread::scoped(move|| -> String {
781             "Success!".to_string()
782         }).join();
783         assert!(res == "Success!");
784     }
785
786     #[test]
787     #[should_panic]
788     fn test_scoped_panic() {
789         thread::scoped(|| panic!()).join();
790     }
791
792     #[test]
793     #[should_panic]
794     fn test_scoped_implicit_panic() {
795         let _ = thread::scoped(|| panic!());
796     }
797
798     #[test]
799     fn test_spawn_sched() {
800         use clone::Clone;
801
802         let (tx, rx) = channel();
803
804         fn f(i: i32, tx: Sender<()>) {
805             let tx = tx.clone();
806             thread::spawn(move|| {
807                 if i == 0 {
808                     tx.send(()).unwrap();
809                 } else {
810                     f(i - 1, tx);
811                 }
812             });
813
814         }
815         f(10, tx);
816         rx.recv().unwrap();
817     }
818
819     #[test]
820     fn test_spawn_sched_childs_on_default_sched() {
821         let (tx, rx) = channel();
822
823         thread::spawn(move|| {
824             thread::spawn(move|| {
825                 tx.send(()).unwrap();
826             });
827         });
828
829         rx.recv().unwrap();
830     }
831
832     fn avoid_copying_the_body<F>(spawnfn: F) where F: FnOnce(Thunk<'static>) {
833         let (tx, rx) = channel();
834
835         let x: Box<_> = box 1;
836         let x_in_parent = (&*x) as *const i32 as usize;
837
838         spawnfn(Thunk::new(move|| {
839             let x_in_child = (&*x) as *const i32 as usize;
840             tx.send(x_in_child).unwrap();
841         }));
842
843         let x_in_child = rx.recv().unwrap();
844         assert_eq!(x_in_parent, x_in_child);
845     }
846
847     #[test]
848     fn test_avoid_copying_the_body_spawn() {
849         avoid_copying_the_body(|v| {
850             thread::spawn(move || v.invoke(()));
851         });
852     }
853
854     #[test]
855     fn test_avoid_copying_the_body_thread_spawn() {
856         avoid_copying_the_body(|f| {
857             thread::spawn(move|| {
858                 f.invoke(());
859             });
860         })
861     }
862
863     #[test]
864     fn test_avoid_copying_the_body_join() {
865         avoid_copying_the_body(|f| {
866             let _ = thread::spawn(move|| {
867                 f.invoke(())
868             }).join();
869         })
870     }
871
872     #[test]
873     fn test_child_doesnt_ref_parent() {
874         // If the child refcounts the parent task, this will stack overflow when
875         // climbing the task tree to dereference each ancestor. (See #1789)
876         // (well, it would if the constant were 8000+ - I lowered it to be more
877         // valgrind-friendly. try this at home, instead..!)
878         const GENERATIONS: u32 = 16;
879         fn child_no(x: u32) -> Thunk<'static> {
880             return Thunk::new(move|| {
881                 if x < GENERATIONS {
882                     thread::spawn(move|| child_no(x+1).invoke(()));
883                 }
884             });
885         }
886         thread::spawn(|| child_no(0).invoke(()));
887     }
888
889     #[test]
890     fn test_simple_newsched_spawn() {
891         thread::spawn(move || {});
892     }
893
894     #[test]
895     fn test_try_panic_message_static_str() {
896         match thread::spawn(move|| {
897             panic!("static string");
898         }).join() {
899             Err(e) => {
900                 type T = &'static str;
901                 assert!(e.is::<T>());
902                 assert_eq!(*e.downcast::<T>().unwrap(), "static string");
903             }
904             Ok(()) => panic!()
905         }
906     }
907
908     #[test]
909     fn test_try_panic_message_owned_str() {
910         match thread::spawn(move|| {
911             panic!("owned string".to_string());
912         }).join() {
913             Err(e) => {
914                 type T = String;
915                 assert!(e.is::<T>());
916                 assert_eq!(*e.downcast::<T>().unwrap(), "owned string".to_string());
917             }
918             Ok(()) => panic!()
919         }
920     }
921
922     #[test]
923     fn test_try_panic_message_any() {
924         match thread::spawn(move|| {
925             panic!(box 413u16 as Box<Any + Send>);
926         }).join() {
927             Err(e) => {
928                 type T = Box<Any + Send>;
929                 assert!(e.is::<T>());
930                 let any = e.downcast::<T>().unwrap();
931                 assert!(any.is::<u16>());
932                 assert_eq!(*any.downcast::<u16>().unwrap(), 413);
933             }
934             Ok(()) => panic!()
935         }
936     }
937
938     #[test]
939     fn test_try_panic_message_unit_struct() {
940         struct Juju;
941
942         match thread::spawn(move|| {
943             panic!(Juju)
944         }).join() {
945             Err(ref e) if e.is::<Juju>() => {}
946             Err(_) | Ok(()) => panic!()
947         }
948     }
949
950     #[test]
951     fn test_park_timeout_unpark_before() {
952         for _ in 0..10 {
953             thread::current().unpark();
954             thread::park_timeout_ms(u32::MAX);
955         }
956     }
957
958     #[test]
959     fn test_park_timeout_unpark_not_called() {
960         for _ in 0..10 {
961             thread::park_timeout_ms(10);
962         }
963     }
964
965     #[test]
966     fn test_park_timeout_unpark_called_other_thread() {
967         use std::old_io;
968
969         for _ in 0..10 {
970             let th = thread::current();
971
972             let _guard = thread::spawn(move || {
973                 old_io::timer::sleep(Duration::milliseconds(50));
974                 th.unpark();
975             });
976
977             thread::park_timeout_ms(u32::MAX);
978         }
979     }
980
981     #[test]
982     fn sleep_ms_smoke() {
983         thread::sleep_ms(2);
984     }
985
986     // NOTE: the corresponding test for stderr is in run-pass/task-stderr, due
987     // to the test harness apparently interfering with stderr configuration.
988 }