]> git.lizzy.rs Git - rust.git/blob - src/libstd/thread/mod.rs
Fix warnings when compiling stdlib with --test
[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 sys_common::{AsInner, IntoInner};
175 use time::Duration;
176
177 ////////////////////////////////////////////////////////////////////////////////
178 // Thread-local storage
179 ////////////////////////////////////////////////////////////////////////////////
180
181 #[macro_use] mod local;
182 #[macro_use] mod scoped_tls;
183
184 #[stable(feature = "rust1", since = "1.0.0")]
185 pub use self::local::{LocalKey, LocalKeyState};
186
187 #[unstable(feature = "scoped_tls",
188            reason = "scoped TLS has yet to have wide enough use to fully \
189                      consider stabilizing its interface",
190            issue = "27715")]
191 pub use self::scoped_tls::ScopedKey;
192
193 #[unstable(feature = "libstd_thread_internals", issue = "0")]
194 #[cfg(target_thread_local)]
195 #[doc(hidden)] pub use self::local::elf::Key as __ElfLocalKeyInner;
196 #[unstable(feature = "libstd_thread_internals", issue = "0")]
197 #[doc(hidden)] pub use self::local::os::Key as __OsLocalKeyInner;
198 #[unstable(feature = "libstd_thread_internals", issue = "0")]
199 #[doc(hidden)] pub use self::scoped_tls::__KeyInner as __ScopedKeyInner;
200
201 ////////////////////////////////////////////////////////////////////////////////
202 // Builder
203 ////////////////////////////////////////////////////////////////////////////////
204
205 /// Thread configuration. Provides detailed control over the properties
206 /// and behavior of new threads.
207 #[stable(feature = "rust1", since = "1.0.0")]
208 pub struct Builder {
209     // A name for the thread-to-be, for identification in panic messages
210     name: Option<String>,
211     // The size of the stack for the spawned thread
212     stack_size: Option<usize>,
213 }
214
215 impl Builder {
216     /// Generates the base configuration for spawning a thread, from which
217     /// configuration methods can be chained.
218     #[stable(feature = "rust1", since = "1.0.0")]
219     pub fn new() -> Builder {
220         Builder {
221             name: None,
222             stack_size: None,
223         }
224     }
225
226     /// Names the thread-to-be. Currently the name is used for identification
227     /// only in panic messages.
228     #[stable(feature = "rust1", since = "1.0.0")]
229     pub fn name(mut self, name: String) -> Builder {
230         self.name = Some(name);
231         self
232     }
233
234     /// Sets the size of the stack for the new thread.
235     #[stable(feature = "rust1", since = "1.0.0")]
236     pub fn stack_size(mut self, size: usize) -> Builder {
237         self.stack_size = Some(size);
238         self
239     }
240
241     /// Spawns a new thread, and returns a join handle for it.
242     ///
243     /// The child thread may outlive the parent (unless the parent thread
244     /// is the main thread; the whole process is terminated when the main
245     /// thread finishes). The join handle can be used to block on
246     /// termination of the child thread, including recovering its panics.
247     ///
248     /// # Errors
249     ///
250     /// Unlike the `spawn` free function, this method yields an
251     /// `io::Result` to capture any failure to create the thread at
252     /// the OS level.
253     #[stable(feature = "rust1", since = "1.0.0")]
254     pub fn spawn<F, T>(self, f: F) -> io::Result<JoinHandle<T>> where
255         F: FnOnce() -> T, F: Send + 'static, T: Send + 'static
256     {
257         let Builder { name, stack_size } = self;
258
259         let stack_size = stack_size.unwrap_or(util::min_stack());
260
261         let my_thread = Thread::new(name);
262         let their_thread = my_thread.clone();
263
264         let my_packet : Arc<UnsafeCell<Option<Result<T>>>>
265             = Arc::new(UnsafeCell::new(None));
266         let their_packet = my_packet.clone();
267
268         let main = move || {
269             if let Some(name) = their_thread.name() {
270                 imp::Thread::set_name(name);
271             }
272             unsafe {
273                 thread_info::set(imp::guard::current(), their_thread);
274                 let mut output = None;
275                 let try_result = {
276                     let ptr = &mut output;
277                     unwind::try(move || *ptr = Some(f()))
278                 };
279                 *their_packet.get() = Some(try_result.map(|()| {
280                     output.unwrap()
281                 }));
282             }
283         };
284
285         Ok(JoinHandle(JoinInner {
286             native: unsafe {
287                 Some(try!(imp::Thread::new(stack_size, Box::new(main))))
288             },
289             thread: my_thread,
290             packet: Packet(my_packet),
291         }))
292     }
293 }
294
295 ////////////////////////////////////////////////////////////////////////////////
296 // Free functions
297 ////////////////////////////////////////////////////////////////////////////////
298
299 /// Spawns a new thread, returning a `JoinHandle` for it.
300 ///
301 /// The join handle will implicitly *detach* the child thread upon being
302 /// dropped. In this case, the child thread may outlive the parent (unless
303 /// the parent thread is the main thread; the whole process is terminated when
304 /// the main thread finishes.) Additionally, the join handle provides a `join`
305 /// method that can be used to join the child thread. If the child thread
306 /// panics, `join` will return an `Err` containing the argument given to
307 /// `panic`.
308 ///
309 /// # Panics
310 ///
311 /// Panics if the OS fails to create a thread; use `Builder::spawn`
312 /// to recover from such errors.
313 #[stable(feature = "rust1", since = "1.0.0")]
314 pub fn spawn<F, T>(f: F) -> JoinHandle<T> where
315     F: FnOnce() -> T, F: Send + 'static, T: Send + 'static
316 {
317     Builder::new().spawn(f).unwrap()
318 }
319
320 /// Gets a handle to the thread that invokes it.
321 #[stable(feature = "rust1", since = "1.0.0")]
322 pub fn current() -> Thread {
323     thread_info::current_thread().expect("use of std::thread::current() is not \
324                                           possible after the thread's local \
325                                           data has been destroyed")
326 }
327
328 /// Cooperatively gives up a timeslice to the OS scheduler.
329 #[stable(feature = "rust1", since = "1.0.0")]
330 pub fn yield_now() {
331     imp::Thread::yield_now()
332 }
333
334 /// Determines whether the current thread is unwinding because of panic.
335 #[inline]
336 #[stable(feature = "rust1", since = "1.0.0")]
337 pub fn panicking() -> bool {
338     unwind::panicking()
339 }
340
341 /// Invokes a closure, capturing the cause of panic if one occurs.
342 ///
343 /// This function will return `Ok` with the closure's result if the closure
344 /// does not panic, and will return `Err(cause)` if the closure panics. The
345 /// `cause` returned is the object with which panic was originally invoked.
346 ///
347 /// It is currently undefined behavior to unwind from Rust code into foreign
348 /// code, so this function is particularly useful when Rust is called from
349 /// another language (normally C). This can run arbitrary Rust code, capturing a
350 /// panic and allowing a graceful handling of the error.
351 ///
352 /// It is **not** recommended to use this function for a general try/catch
353 /// mechanism. The `Result` type is more appropriate to use for functions that
354 /// can fail on a regular basis.
355 ///
356 /// The closure provided is required to adhere to the `'static` bound to ensure
357 /// that it cannot reference data in the parent stack frame, mitigating problems
358 /// with exception safety. Furthermore, a `Send` bound is also required,
359 /// providing the same safety guarantees as `thread::spawn` (ensuring the
360 /// closure is properly isolated from the parent).
361 #[unstable(feature = "catch_panic", reason = "recent API addition",
362            issue = "27719")]
363 #[rustc_deprecated(since = "1.6.0", reason = "renamed to std::panic::recover")]
364 pub fn catch_panic<F, R>(f: F) -> Result<R>
365     where F: FnOnce() -> R + Send + 'static
366 {
367     let mut result = None;
368     unsafe {
369         let result = &mut result;
370         try!(unwind::try(move || *result = Some(f())))
371     }
372     Ok(result.unwrap())
373 }
374
375 /// Puts the current thread to sleep for the specified amount of time.
376 ///
377 /// The thread may sleep longer than the duration specified due to scheduling
378 /// specifics or platform-dependent functionality. Note that on unix platforms
379 /// this function will not return early due to a signal being received or a
380 /// spurious wakeup.
381 #[stable(feature = "rust1", since = "1.0.0")]
382 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::sleep`")]
383 pub fn sleep_ms(ms: u32) {
384     sleep(Duration::from_millis(ms as u64))
385 }
386
387 /// Puts the current thread to sleep for the specified amount of time.
388 ///
389 /// The thread may sleep longer than the duration specified due to scheduling
390 /// specifics or platform-dependent functionality.
391 ///
392 /// # Platform behavior
393 ///
394 /// On Unix platforms this function will not return early due to a
395 /// signal being received or a spurious wakeup. Platforms which do not support
396 /// nanosecond precision for sleeping will have `dur` rounded up to the nearest
397 /// granularity of time they can sleep for.
398 #[stable(feature = "thread_sleep", since = "1.4.0")]
399 pub fn sleep(dur: Duration) {
400     imp::Thread::sleep(dur)
401 }
402
403 /// Blocks unless or until the current thread's token is made available.
404 ///
405 /// Every thread is equipped with some basic low-level blocking support, via
406 /// the `park()` function and the [`unpark()`][unpark] method. These can be
407 /// used as a more CPU-efficient implementation of a spinlock.
408 ///
409 /// [unpark]: struct.Thread.html#method.unpark
410 ///
411 /// The API is typically used by acquiring a handle to the current thread,
412 /// placing that handle in a shared data structure so that other threads can
413 /// find it, and then parking (in a loop with a check for the token actually
414 /// being acquired).
415 ///
416 /// A call to `park` does not guarantee that the thread will remain parked
417 /// forever, and callers should be prepared for this possibility.
418 ///
419 /// See the [module documentation][thread] for more detail.
420 ///
421 /// [thread]: index.html
422 //
423 // The implementation currently uses the trivial strategy of a Mutex+Condvar
424 // with wakeup flag, which does not actually allow spurious wakeups. In the
425 // future, this will be implemented in a more efficient way, perhaps along the lines of
426 //   http://cr.openjdk.java.net/~stefank/6989984.1/raw_files/new/src/os/linux/vm/os_linux.cpp
427 // or futuxes, and in either case may allow spurious wakeups.
428 #[stable(feature = "rust1", since = "1.0.0")]
429 pub fn park() {
430     let thread = current();
431     let mut guard = thread.inner.lock.lock().unwrap();
432     while !*guard {
433         guard = thread.inner.cvar.wait(guard).unwrap();
434     }
435     *guard = false;
436 }
437
438 /// Blocks unless or until the current thread's token is made available or
439 /// the specified duration has been reached (may wake spuriously).
440 ///
441 /// The semantics of this function are equivalent to `park()` except that the
442 /// thread will be blocked for roughly no longer than *ms*. This method
443 /// should not be used for precise timing due to anomalies such as
444 /// preemption or platform differences that may not cause the maximum
445 /// amount of time waited to be precisely *ms* long.
446 ///
447 /// See the module doc for more detail.
448 #[stable(feature = "rust1", since = "1.0.0")]
449 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::park_timeout`")]
450 pub fn park_timeout_ms(ms: u32) {
451     park_timeout(Duration::from_millis(ms as u64))
452 }
453
454 /// Blocks unless or until the current thread's token is made available or
455 /// the specified duration has been reached (may wake spuriously).
456 ///
457 /// The semantics of this function are equivalent to `park()` except that the
458 /// thread will be blocked for roughly no longer than *dur*. This method
459 /// should not be used for precise timing due to anomalies such as
460 /// preemption or platform differences that may not cause the maximum
461 /// amount of time waited to be precisely *dur* long.
462 ///
463 /// See the module doc for more detail.
464 ///
465 /// # Platform behavior
466 ///
467 /// Platforms which do not support nanosecond precision for sleeping will have
468 /// `dur` rounded up to the nearest granularity of time they can sleep for.
469 #[stable(feature = "park_timeout", since = "1.4.0")]
470 pub fn park_timeout(dur: Duration) {
471     let thread = current();
472     let mut guard = thread.inner.lock.lock().unwrap();
473     if !*guard {
474         let (g, _) = thread.inner.cvar.wait_timeout(guard, dur).unwrap();
475         guard = g;
476     }
477     *guard = false;
478 }
479
480 ////////////////////////////////////////////////////////////////////////////////
481 // Thread
482 ////////////////////////////////////////////////////////////////////////////////
483
484 /// The internal representation of a `Thread` handle
485 struct Inner {
486     name: Option<String>,
487     lock: Mutex<bool>,          // true when there is a buffered unpark
488     cvar: Condvar,
489 }
490
491 #[derive(Clone)]
492 #[stable(feature = "rust1", since = "1.0.0")]
493 /// A handle to a thread.
494 pub struct Thread {
495     inner: Arc<Inner>,
496 }
497
498 impl Thread {
499     // Used only internally to construct a thread object without spawning
500     fn new(name: Option<String>) -> Thread {
501         Thread {
502             inner: Arc::new(Inner {
503                 name: name,
504                 lock: Mutex::new(false),
505                 cvar: Condvar::new(),
506             })
507         }
508     }
509
510     /// Atomically makes the handle's token available if it is not already.
511     ///
512     /// See the module doc for more detail.
513     #[stable(feature = "rust1", since = "1.0.0")]
514     pub fn unpark(&self) {
515         let mut guard = self.inner.lock.lock().unwrap();
516         if !*guard {
517             *guard = true;
518             self.inner.cvar.notify_one();
519         }
520     }
521
522     /// Gets the thread's name.
523     #[stable(feature = "rust1", since = "1.0.0")]
524     pub fn name(&self) -> Option<&str> {
525         self.inner.name.as_ref().map(|s| &**s)
526     }
527 }
528
529 #[stable(feature = "rust1", since = "1.0.0")]
530 impl fmt::Debug for Thread {
531     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
532         fmt::Debug::fmt(&self.name(), f)
533     }
534 }
535
536 // a hack to get around privacy restrictions
537 impl thread_info::NewThread for Thread {
538     fn new(name: Option<String>) -> Thread { Thread::new(name) }
539 }
540
541 ////////////////////////////////////////////////////////////////////////////////
542 // JoinHandle
543 ////////////////////////////////////////////////////////////////////////////////
544
545 /// Indicates the manner in which a thread exited.
546 ///
547 /// A thread that completes without panicking is considered to exit successfully.
548 #[stable(feature = "rust1", since = "1.0.0")]
549 pub type Result<T> = ::result::Result<T, Box<Any + Send + 'static>>;
550
551 // This packet is used to communicate the return value between the child thread
552 // and the parent thread. Memory is shared through the `Arc` within and there's
553 // no need for a mutex here because synchronization happens with `join()` (the
554 // parent thread never reads this packet until the child has exited).
555 //
556 // This packet itself is then stored into a `JoinInner` which in turns is placed
557 // in `JoinHandle` and `JoinGuard`. Due to the usage of `UnsafeCell` we need to
558 // manually worry about impls like Send and Sync. The type `T` should
559 // already always be Send (otherwise the thread could not have been created) and
560 // this type is inherently Sync because no methods take &self. Regardless,
561 // however, we add inheriting impls for Send/Sync to this type to ensure it's
562 // Send/Sync and that future modifications will still appropriately classify it.
563 struct Packet<T>(Arc<UnsafeCell<Option<Result<T>>>>);
564
565 unsafe impl<T: Send> Send for Packet<T> {}
566 unsafe impl<T: Sync> Sync for Packet<T> {}
567
568 /// Inner representation for JoinHandle
569 struct JoinInner<T> {
570     native: Option<imp::Thread>,
571     thread: Thread,
572     packet: Packet<T>,
573 }
574
575 impl<T> JoinInner<T> {
576     fn join(&mut self) -> Result<T> {
577         self.native.take().unwrap().join();
578         unsafe {
579             (*self.packet.0.get()).take().unwrap()
580         }
581     }
582 }
583
584 /// An owned permission to join on a thread (block on its termination).
585 ///
586 /// A `JoinHandle` *detaches* the child thread when it is dropped.
587 ///
588 /// Due to platform restrictions, it is not possible to `Clone` this
589 /// handle: the ability to join a child thread is a uniquely-owned
590 /// permission.
591 #[stable(feature = "rust1", since = "1.0.0")]
592 pub struct JoinHandle<T>(JoinInner<T>);
593
594 impl<T> JoinHandle<T> {
595     /// Extracts a handle to the underlying thread
596     #[stable(feature = "rust1", since = "1.0.0")]
597     pub fn thread(&self) -> &Thread {
598         &self.0.thread
599     }
600
601     /// Waits for the associated thread to finish.
602     ///
603     /// If the child thread panics, `Err` is returned with the parameter given
604     /// to `panic`.
605     #[stable(feature = "rust1", since = "1.0.0")]
606     pub fn join(mut self) -> Result<T> {
607         self.0.join()
608     }
609 }
610
611 impl<T> AsInner<imp::Thread> for JoinHandle<T> {
612     fn as_inner(&self) -> &imp::Thread { self.0.native.as_ref().unwrap() }
613 }
614
615 impl<T> IntoInner<imp::Thread> for JoinHandle<T> {
616     fn into_inner(self) -> imp::Thread { self.0.native.unwrap() }
617 }
618
619 fn _assert_sync_and_send() {
620     fn _assert_both<T: Send + Sync>() {}
621     _assert_both::<JoinHandle<()>>();
622     _assert_both::<Thread>();
623 }
624
625 ////////////////////////////////////////////////////////////////////////////////
626 // Tests
627 ////////////////////////////////////////////////////////////////////////////////
628
629 #[cfg(test)]
630 mod tests {
631     use prelude::v1::*;
632
633     use any::Any;
634     use sync::mpsc::{channel, Sender};
635     use result;
636     use super::{Builder};
637     use thread;
638     use time::Duration;
639     use u32;
640
641     // !!! These tests are dangerous. If something is buggy, they will hang, !!!
642     // !!! instead of exiting cleanly. This might wedge the buildbots.       !!!
643
644     #[test]
645     fn test_unnamed_thread() {
646         thread::spawn(move|| {
647             assert!(thread::current().name().is_none());
648         }).join().ok().unwrap();
649     }
650
651     #[test]
652     fn test_named_thread() {
653         Builder::new().name("ada lovelace".to_string()).spawn(move|| {
654             assert!(thread::current().name().unwrap() == "ada lovelace".to_string());
655         }).unwrap().join().unwrap();
656     }
657
658     #[test]
659     fn test_run_basic() {
660         let (tx, rx) = channel();
661         thread::spawn(move|| {
662             tx.send(()).unwrap();
663         });
664         rx.recv().unwrap();
665     }
666
667     #[test]
668     fn test_join_panic() {
669         match thread::spawn(move|| {
670             panic!()
671         }).join() {
672             result::Result::Err(_) => (),
673             result::Result::Ok(()) => panic!()
674         }
675     }
676
677     #[test]
678     fn test_spawn_sched() {
679         use clone::Clone;
680
681         let (tx, rx) = channel();
682
683         fn f(i: i32, tx: Sender<()>) {
684             let tx = tx.clone();
685             thread::spawn(move|| {
686                 if i == 0 {
687                     tx.send(()).unwrap();
688                 } else {
689                     f(i - 1, tx);
690                 }
691             });
692
693         }
694         f(10, tx);
695         rx.recv().unwrap();
696     }
697
698     #[test]
699     fn test_spawn_sched_childs_on_default_sched() {
700         let (tx, rx) = channel();
701
702         thread::spawn(move|| {
703             thread::spawn(move|| {
704                 tx.send(()).unwrap();
705             });
706         });
707
708         rx.recv().unwrap();
709     }
710
711     fn avoid_copying_the_body<F>(spawnfn: F) where F: FnOnce(Box<Fn() + Send>) {
712         let (tx, rx) = channel();
713
714         let x: Box<_> = box 1;
715         let x_in_parent = (&*x) as *const i32 as usize;
716
717         spawnfn(Box::new(move|| {
718             let x_in_child = (&*x) as *const i32 as usize;
719             tx.send(x_in_child).unwrap();
720         }));
721
722         let x_in_child = rx.recv().unwrap();
723         assert_eq!(x_in_parent, x_in_child);
724     }
725
726     #[test]
727     fn test_avoid_copying_the_body_spawn() {
728         avoid_copying_the_body(|v| {
729             thread::spawn(move || v());
730         });
731     }
732
733     #[test]
734     fn test_avoid_copying_the_body_thread_spawn() {
735         avoid_copying_the_body(|f| {
736             thread::spawn(move|| {
737                 f();
738             });
739         })
740     }
741
742     #[test]
743     fn test_avoid_copying_the_body_join() {
744         avoid_copying_the_body(|f| {
745             let _ = thread::spawn(move|| {
746                 f()
747             }).join();
748         })
749     }
750
751     #[test]
752     fn test_child_doesnt_ref_parent() {
753         // If the child refcounts the parent thread, this will stack overflow when
754         // climbing the thread tree to dereference each ancestor. (See #1789)
755         // (well, it would if the constant were 8000+ - I lowered it to be more
756         // valgrind-friendly. try this at home, instead..!)
757         const GENERATIONS: u32 = 16;
758         fn child_no(x: u32) -> Box<Fn() + Send> {
759             return Box::new(move|| {
760                 if x < GENERATIONS {
761                     thread::spawn(move|| child_no(x+1)());
762                 }
763             });
764         }
765         thread::spawn(|| child_no(0)());
766     }
767
768     #[test]
769     fn test_simple_newsched_spawn() {
770         thread::spawn(move || {});
771     }
772
773     #[test]
774     fn test_try_panic_message_static_str() {
775         match thread::spawn(move|| {
776             panic!("static string");
777         }).join() {
778             Err(e) => {
779                 type T = &'static str;
780                 assert!(e.is::<T>());
781                 assert_eq!(*e.downcast::<T>().unwrap(), "static string");
782             }
783             Ok(()) => panic!()
784         }
785     }
786
787     #[test]
788     fn test_try_panic_message_owned_str() {
789         match thread::spawn(move|| {
790             panic!("owned string".to_string());
791         }).join() {
792             Err(e) => {
793                 type T = String;
794                 assert!(e.is::<T>());
795                 assert_eq!(*e.downcast::<T>().unwrap(), "owned string".to_string());
796             }
797             Ok(()) => panic!()
798         }
799     }
800
801     #[test]
802     fn test_try_panic_message_any() {
803         match thread::spawn(move|| {
804             panic!(box 413u16 as Box<Any + Send>);
805         }).join() {
806             Err(e) => {
807                 type T = Box<Any + Send>;
808                 assert!(e.is::<T>());
809                 let any = e.downcast::<T>().unwrap();
810                 assert!(any.is::<u16>());
811                 assert_eq!(*any.downcast::<u16>().unwrap(), 413);
812             }
813             Ok(()) => panic!()
814         }
815     }
816
817     #[test]
818     fn test_try_panic_message_unit_struct() {
819         struct Juju;
820
821         match thread::spawn(move|| {
822             panic!(Juju)
823         }).join() {
824             Err(ref e) if e.is::<Juju>() => {}
825             Err(_) | Ok(()) => panic!()
826         }
827     }
828
829     #[test]
830     fn test_park_timeout_unpark_before() {
831         for _ in 0..10 {
832             thread::current().unpark();
833             thread::park_timeout(Duration::from_millis(u32::MAX as u64));
834         }
835     }
836
837     #[test]
838     fn test_park_timeout_unpark_not_called() {
839         for _ in 0..10 {
840             thread::park_timeout(Duration::from_millis(10));
841         }
842     }
843
844     #[test]
845     fn test_park_timeout_unpark_called_other_thread() {
846         for _ in 0..10 {
847             let th = thread::current();
848
849             let _guard = thread::spawn(move || {
850                 super::sleep(Duration::from_millis(50));
851                 th.unpark();
852             });
853
854             thread::park_timeout(Duration::from_millis(u32::MAX as u64));
855         }
856     }
857
858     #[test]
859     fn sleep_ms_smoke() {
860         thread::sleep(Duration::from_millis(2));
861     }
862
863     // NOTE: the corresponding test for stderr is in run-pass/thread-stderr, due
864     // to the test harness apparently interfering with stderr configuration.
865 }