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