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