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