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