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