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