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