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