]> git.lizzy.rs Git - rust.git/blob - src/libstd/thread/mod.rs
dda11e50380f516f6a031ebd18f6411c5f68ee80
[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. Threads can be named, and
17 //! provide some built-in support for low-level synchronization.
18 //!
19 //! Communication between threads can be done through
20 //! [channels], Rust's message-passing 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, [`Arc`].
25 //!
26 //! Fatal logic errors in Rust cause *thread panic*, during which
27 //! a thread will unwind the stack, running destructors and freeing
28 //! owned resources. Thread panic is unrecoverable from within
29 //! the panicking thread (i.e. there is no 'try/catch' in Rust), but
30 //! the panic may optionally be detected from a different thread. If
31 //! the main thread panics, the application will exit with a non-zero
32 //! exit code.
33 //!
34 //! When the main thread of a Rust program terminates, the entire program shuts
35 //! down, even if other threads are still running. However, this module provides
36 //! convenient facilities for automatically waiting for the termination of a
37 //! child thread (i.e., join).
38 //!
39 //! ## Spawning a thread
40 //!
41 //! A new thread can be spawned using the [`thread::spawn`][`spawn`] function:
42 //!
43 //! ```rust
44 //! use std::thread;
45 //!
46 //! thread::spawn(move || {
47 //!     // some work here
48 //! });
49 //! ```
50 //!
51 //! In this example, the spawned thread is "detached" from the current
52 //! thread. This means that it can outlive its parent (the thread that spawned
53 //! it), unless this parent is the main thread.
54 //!
55 //! The parent thread can also wait on the completion of the child
56 //! thread; a call to [`spawn`] produces a [`JoinHandle`], which provides
57 //! a `join` method for waiting:
58 //!
59 //! ```rust
60 //! use std::thread;
61 //!
62 //! let child = thread::spawn(move || {
63 //!     // some work here
64 //! });
65 //! // some work here
66 //! let res = child.join();
67 //! ```
68 //!
69 //! The [`join`] method returns a [`thread::Result`] containing [`Ok`] of the final
70 //! value produced by the child thread, or [`Err`] of the value given to
71 //! a call to [`panic!`] if the child panicked.
72 //!
73 //! ## Configuring threads
74 //!
75 //! A new thread can be configured before it is spawned via the [`Builder`] type,
76 //! which currently allows you to set the name and stack size for the child thread:
77 //!
78 //! ```rust
79 //! # #![allow(unused_must_use)]
80 //! use std::thread;
81 //!
82 //! thread::Builder::new().name("child1".to_string()).spawn(move || {
83 //!     println!("Hello, world!");
84 //! });
85 //! ```
86 //!
87 //! ## The `Thread` type
88 //!
89 //! Threads are represented via the [`Thread`] type, which you can get in one of
90 //! two ways:
91 //!
92 //! * By spawning a new thread, e.g. using the [`thread::spawn`][`spawn`]
93 //!   function, and calling [`thread`][`JoinHandle::thread`] on the [`JoinHandle`].
94 //! * By requesting the current thread, using the [`thread::current`] function.
95 //!
96 //! The [`thread::current`] function is available even for threads not spawned
97 //! by the APIs of this module.
98 //!
99 //! ## Thread-local storage
100 //!
101 //! This module also provides an implementation of thread-local storage for Rust
102 //! programs. Thread-local storage is a method of storing data into a global
103 //! variable that each thread in the program will have its own copy of.
104 //! Threads do not share this data, so accesses do not need to be synchronized.
105 //!
106 //! A thread-local key owns the value it contains and will destroy the value when the
107 //! thread exits. It is created with the [`thread_local!`] macro and can contain any
108 //! value that is `'static` (no borrowed pointers). It provides an accessor function,
109 //! [`with`], that yields a shared reference to the value to the specified
110 //! closure. Thread-local keys allow only shared access to values, as there would be no
111 //! way to guarantee uniqueness if mutable borrows were allowed. Most values
112 //! will want to make use of some form of **interior mutability** through the
113 //! [`Cell`] or [`RefCell`] types.
114 //!
115 //! [channels]: ../../std/sync/mpsc/index.html
116 //! [`Arc`]: ../../std/sync/struct.Arc.html
117 //! [`spawn`]: ../../std/thread/fn.spawn.html
118 //! [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
119 //! [`JoinHandle::thread`]: ../../std/thread/struct.JoinHandle.html#method.thread
120 //! [`join`]: ../../std/thread/struct.JoinHandle.html#method.join
121 //! [`Result`]: ../../std/result/enum.Result.html
122 //! [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
123 //! [`Err`]: ../../std/result/enum.Result.html#variant.Err
124 //! [`panic!`]: ../../std/macro.panic.html
125 //! [`Builder`]: ../../std/thread/struct.Builder.html
126 //! [`thread::current`]: ../../std/thread/fn.current.html
127 //! [`thread::Result`]: ../../std/thread/type.Result.html
128 //! [`Thread`]: ../../std/thread/struct.Thread.html
129 //! [`park`]: ../../std/thread/fn.park.html
130 //! [`unpark`]: ../../std/thread/struct.Thread.html#method.unpark
131 //! [`thread::park_timeout`]: ../../std/thread/fn.park_timeout.html
132 //! [`Cell`]: ../cell/struct.Cell.html
133 //! [`RefCell`]: ../cell/struct.RefCell.html
134 //! [`thread_local!`]: ../macro.thread_local.html
135 //! [`with`]: struct.LocalKey.html#method.with
136
137 #![stable(feature = "rust1", since = "1.0.0")]
138
139 use any::Any;
140 use cell::UnsafeCell;
141 use ffi::{CStr, CString};
142 use fmt;
143 use io;
144 use panic;
145 use panicking;
146 use str;
147 use sync::{Mutex, Condvar, Arc};
148 use sys::thread as imp;
149 use sys_common::mutex;
150 use sys_common::thread_info;
151 use sys_common::util;
152 use sys_common::{AsInner, IntoInner};
153 use time::Duration;
154
155 ////////////////////////////////////////////////////////////////////////////////
156 // Thread-local storage
157 ////////////////////////////////////////////////////////////////////////////////
158
159 #[macro_use] mod local;
160
161 #[stable(feature = "rust1", since = "1.0.0")]
162 pub use self::local::{LocalKey, LocalKeyState};
163
164 // The types used by the thread_local! macro to access TLS keys. Note that there
165 // are two types, the "OS" type and the "fast" type. The OS thread local key
166 // type is accessed via platform-specific API calls and is slow, while the fast
167 // key type is accessed via code generated via LLVM, where TLS keys are set up
168 // by the elf linker. Note that the OS TLS type is always available: on macOS
169 // the standard library is compiled with support for older platform versions
170 // where fast TLS was not available; end-user code is compiled with fast TLS
171 // where available, but both are needed.
172
173 #[unstable(feature = "libstd_thread_internals", issue = "0")]
174 #[cfg(target_thread_local)]
175 #[doc(hidden)] pub use sys::fast_thread_local::Key as __FastLocalKeyInner;
176 #[unstable(feature = "libstd_thread_internals", issue = "0")]
177 #[doc(hidden)] pub use self::local::os::Key as __OsLocalKeyInner;
178
179 ////////////////////////////////////////////////////////////////////////////////
180 // Builder
181 ////////////////////////////////////////////////////////////////////////////////
182
183 /// Thread factory, which can be used in order to configure the properties of
184 /// a new thread.
185 ///
186 /// Methods can be chained on it in order to configure it.
187 ///
188 /// The two configurations available are:
189 ///
190 /// - [`name`]: allows to give a name to the thread which is currently
191 ///   only used in `panic` messages.
192 /// - [`stack_size`]: specifies the desired stack size. Note that this can
193 ///   be overriden by the OS.
194 ///
195 /// If the [`stack_size`] field is not specified, the stack size
196 /// will be the `RUST_MIN_STACK` environment variable. If it is
197 /// not specified either, a sensible default will be set.
198 ///
199 /// If the [`name`] field is not specified, the thread will not be named.
200 ///
201 /// The [`spawn`] method will take ownership of the builder and create an
202 /// [`io::Result`] to the thread handle with the given configuration.
203 ///
204 /// The [`thread::spawn`] free function uses a `Builder` with default
205 /// configuration and [`unwrap`]s its return value.
206 ///
207 /// You may want to use [`spawn`] instead of [`thread::spawn`], when you want
208 /// to recover from a failure to launch a thread, indeed the free function will
209 /// panick where the `Builder` method will return a [`io::Result`].
210 ///
211 /// # Examples
212 ///
213 /// ```
214 /// use std::thread;
215 ///
216 /// let builder = thread::Builder::new();
217 ///
218 /// let handler = builder.spawn(|| {
219 ///     // thread code
220 /// }).unwrap();
221 ///
222 /// handler.join().unwrap();
223 /// ```
224 ///
225 /// [`thread::spawn`]: ../../std/thread/fn.spawn.html
226 /// [`stack_size`]: ../../std/thread/struct.Builder.html#method.stack_size
227 /// [`name`]: ../../std/thread/struct.Builder.html#method.name
228 /// [`spawn`]: ../../std/thread/struct.Builder.html#method.spawn
229 /// [`io::Result`]: ../../std/io/type.Result.html
230 /// [`unwrap`]: ../../std/result/enum.Result.html#method.unwrap
231 #[stable(feature = "rust1", since = "1.0.0")]
232 #[derive(Debug)]
233 pub struct Builder {
234     // A name for the thread-to-be, for identification in panic messages
235     name: Option<String>,
236     // The size of the stack for the spawned thread in bytes
237     stack_size: Option<usize>,
238 }
239
240 impl Builder {
241     /// Generates the base configuration for spawning a thread, from which
242     /// configuration methods can be chained.
243     ///
244     /// # Examples
245     ///
246     /// ```
247     /// use std::thread;
248     ///
249     /// let builder = thread::Builder::new()
250     ///                               .name("foo".into())
251     ///                               .stack_size(10);
252     ///
253     /// let handler = builder.spawn(|| {
254     ///     // thread code
255     /// }).unwrap();
256     ///
257     /// handler.join().unwrap();
258     /// ```
259     #[stable(feature = "rust1", since = "1.0.0")]
260     pub fn new() -> Builder {
261         Builder {
262             name: None,
263             stack_size: None,
264         }
265     }
266
267     /// Names the thread-to-be. Currently the name is used for identification
268     /// only in panic messages.
269     ///
270     /// # Examples
271     ///
272     /// ```
273     /// use std::thread;
274     ///
275     /// let builder = thread::Builder::new()
276     ///     .name("foo".into());
277     ///
278     /// let handler = builder.spawn(|| {
279     ///     assert_eq!(thread::current().name(), Some("foo"))
280     /// }).unwrap();
281     ///
282     /// handler.join().unwrap();
283     /// ```
284     #[stable(feature = "rust1", since = "1.0.0")]
285     pub fn name(mut self, name: String) -> Builder {
286         self.name = Some(name);
287         self
288     }
289
290     /// Sets the size of the stack (in bytes) for the new thread.
291     ///
292     /// The actual stack size may be greater than this value if
293     /// the platform specifies minimal stack size.
294     ///
295     /// # Examples
296     ///
297     /// ```
298     /// use std::thread;
299     ///
300     /// let builder = thread::Builder::new().stack_size(32 * 1024);
301     /// ```
302     #[stable(feature = "rust1", since = "1.0.0")]
303     pub fn stack_size(mut self, size: usize) -> Builder {
304         self.stack_size = Some(size);
305         self
306     }
307
308     /// Spawns a new thread by taking ownership of the `Builder`, and returns an
309     /// [`io::Result`] to its [`JoinHandle`].
310     ///
311     /// The spawned thread may outlive the caller (unless the caller thread
312     /// is the main thread; the whole process is terminated when the main
313     /// thread finishes). The join handle can be used to block on
314     /// termination of the child thread, including recovering its panics.
315     ///
316     /// For a more complete documentation see [`thread::spawn`][`spawn`].
317     ///
318     /// # Errors
319     ///
320     /// Unlike the [`spawn`] free function, this method yields an
321     /// [`io::Result`] to capture any failure to create the thread at
322     /// the OS level.
323     ///
324     /// [`spawn`]: ../../std/thread/fn.spawn.html
325     /// [`io::Result`]: ../../std/io/type.Result.html
326     /// [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
327     ///
328     /// # Examples
329     ///
330     /// ```
331     /// use std::thread;
332     ///
333     /// let builder = thread::Builder::new();
334     ///
335     /// let handler = builder.spawn(|| {
336     ///     // thread code
337     /// }).unwrap();
338     ///
339     /// handler.join().unwrap();
340     /// ```
341     #[stable(feature = "rust1", since = "1.0.0")]
342     pub fn spawn<F, T>(self, f: F) -> io::Result<JoinHandle<T>> where
343         F: FnOnce() -> T, F: Send + 'static, T: Send + 'static
344     {
345         let Builder { name, stack_size } = self;
346
347         let stack_size = stack_size.unwrap_or(util::min_stack());
348
349         let my_thread = Thread::new(name);
350         let their_thread = my_thread.clone();
351
352         let my_packet : Arc<UnsafeCell<Option<Result<T>>>>
353             = Arc::new(UnsafeCell::new(None));
354         let their_packet = my_packet.clone();
355
356         let main = move || {
357             if let Some(name) = their_thread.cname() {
358                 imp::Thread::set_name(name);
359             }
360             unsafe {
361                 thread_info::set(imp::guard::current(), their_thread);
362                 #[cfg(feature = "backtrace")]
363                 let try_result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
364                     ::sys_common::backtrace::__rust_begin_short_backtrace(f)
365                 }));
366                 #[cfg(not(feature = "backtrace"))]
367                 let try_result = panic::catch_unwind(panic::AssertUnwindSafe(f));
368                 *their_packet.get() = Some(try_result);
369             }
370         };
371
372         Ok(JoinHandle(JoinInner {
373             native: unsafe {
374                 Some(imp::Thread::new(stack_size, Box::new(main))?)
375             },
376             thread: my_thread,
377             packet: Packet(my_packet),
378         }))
379     }
380 }
381
382 ////////////////////////////////////////////////////////////////////////////////
383 // Free functions
384 ////////////////////////////////////////////////////////////////////////////////
385
386 /// Spawns a new thread, returning a [`JoinHandle`] for it.
387 ///
388 /// The join handle will implicitly *detach* the child thread upon being
389 /// dropped. In this case, the child thread may outlive the parent (unless
390 /// the parent thread is the main thread; the whole process is terminated when
391 /// the main thread finishes). Additionally, the join handle provides a [`join`]
392 /// method that can be used to join the child thread. If the child thread
393 /// panics, [`join`] will return an [`Err`] containing the argument given to
394 /// [`panic`].
395 ///
396 /// This will create a thread using default parameters of [`Builder`], if you
397 /// want to specify the stack size or the name of the thread, use this API
398 /// instead.
399 ///
400 /// As you can see in the signature of `spawn` there are two constraints on
401 /// both the closure given to `spawn` and its return value, let's explain them:
402 ///
403 /// - The `'static` constraint means that the closure and its return value
404 ///   must have a lifetime of the whole program execution. The reason for this
405 ///   is that threads can `detach` and outlive the lifetime they have been
406 ///   created in.
407 ///   Indeed if the thread, and by extension its return value, can outlive their
408 ///   caller, we need to make sure that they will be valid afterwards, and since
409 ///   we *can't* know when it will return we need to have them valid as long as
410 ///   possible, that is until the end of the program, hence the `'static`
411 ///   lifetime.
412 /// - The [`Send`] constraint is because the closure will need to be passed
413 ///   *by value* from the thread where it is spawned to the new thread. Its
414 ///   return value will need to be passed from the new thread to the thread
415 ///   where it is `join`ed.
416 ///   As a reminder, the [`Send`] marker trait, expresses that it is safe to be
417 ///   passed from thread to thread. [`Sync`] expresses that it is safe to have a
418 ///   reference be passed from thread to thread.
419 ///
420 /// # Panics
421 ///
422 /// Panics if the OS fails to create a thread; use [`Builder::spawn`]
423 /// to recover from such errors.
424 ///
425 /// # Examples
426 ///
427 /// Creating a thread.
428 ///
429 /// ```
430 /// use std::thread;
431 ///
432 /// let handler = thread::spawn(|| {
433 ///     // thread code
434 /// });
435 ///
436 /// handler.join().unwrap();
437 /// ```
438 ///
439 /// As mentioned in the module documentation, threads are usually made to
440 /// communicate using [`channels`], here is how it usually looks.
441 ///
442 /// This example also shows how to use `move`, in order to give ownership
443 /// of values to a thread.
444 ///
445 /// ```
446 /// use std::thread;
447 /// use std::sync::mpsc::channel;
448 ///
449 /// let (tx, rx) = channel();
450 ///
451 /// let sender = thread::spawn(move || {
452 ///     let _ = tx.send("Hello, thread".to_owned());
453 /// });
454 ///
455 /// let receiver = thread::spawn(move || {
456 ///     println!("{}", rx.recv().unwrap());
457 /// });
458 ///
459 /// let _ = sender.join();
460 /// let _ = receiver.join();
461 /// ```
462 ///
463 /// A thread can also return a value through its [`JoinHandle`], you can use
464 /// this to make asynchronous computations (futures might be more appropriate
465 /// though).
466 ///
467 /// ```
468 /// use std::thread;
469 ///
470 /// let computation = thread::spawn(|| {
471 ///     // Some expensive computation.
472 ///     42
473 /// });
474 ///
475 /// let result = computation.join().unwrap();
476 /// println!("{}", result);
477 /// ```
478 ///
479 /// [`channels`]: ../../std/sync/mpsc/index.html
480 /// [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
481 /// [`join`]: ../../std/thread/struct.JoinHandle.html#method.join
482 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
483 /// [`panic`]: ../../std/macro.panic.html
484 /// [`Builder::spawn`]: ../../std/thread/struct.Builder.html#method.spawn
485 /// [`Builder`]: ../../std/thread/struct.Builder.html
486 /// [`Send`]: ../../std/marker/trait.Send.html
487 /// [`Sync`]: ../../std/marker/trait.Sync.html
488 #[stable(feature = "rust1", since = "1.0.0")]
489 pub fn spawn<F, T>(f: F) -> JoinHandle<T> where
490     F: FnOnce() -> T, F: Send + 'static, T: Send + 'static
491 {
492     Builder::new().spawn(f).unwrap()
493 }
494
495 /// Gets a handle to the thread that invokes it.
496 ///
497 /// # Examples
498 ///
499 /// Getting a handle to the current thread with `thread::current()`:
500 ///
501 /// ```
502 /// use std::thread;
503 ///
504 /// let handler = thread::Builder::new()
505 ///     .name("named thread".into())
506 ///     .spawn(|| {
507 ///         let handle = thread::current();
508 ///         assert_eq!(handle.name(), Some("named thread"));
509 ///     })
510 ///     .unwrap();
511 ///
512 /// handler.join().unwrap();
513 /// ```
514 #[stable(feature = "rust1", since = "1.0.0")]
515 pub fn current() -> Thread {
516     thread_info::current_thread().expect("use of std::thread::current() is not \
517                                           possible after the thread's local \
518                                           data has been destroyed")
519 }
520
521 /// Cooperatively gives up a timeslice to the OS scheduler.
522 ///
523 /// This is used when the programmer knows that the thread will have nothing
524 /// to do for some time, and thus avoid wasting computing time.
525 ///
526 /// For example when polling on a resource, it is common to check that it is
527 /// available, and if not to yield in order to avoid busy waiting.
528 ///
529 /// Thus the pattern of `yield`ing after a failed poll is rather common when
530 /// implementing low-level shared resources or synchronization primitives.
531 ///
532 /// However programmers will usualy prefer to use, [`channel`]s, [`Condvar`]s,
533 /// [`Mutex`]es or [`join`] for their synchronisation routines, as they avoid
534 /// thinking about thread schedulling.
535 ///
536 /// Note that [`channel`]s for example are implemented using this primitive.
537 /// Indeed when you call `send` or `recv`, which are blocking, they will yield
538 /// if the channel is not available.
539 ///
540 /// # Examples
541 ///
542 /// ```
543 /// use std::thread;
544 ///
545 /// thread::yield_now();
546 /// ```
547 ///
548 /// [`channel`]: ../../std/sync/mpsc/index.html
549 /// [`spawn`]: ../../std/thread/fn.spawn.html
550 /// [`join`]: ../../std/thread/struct.JoinHandle.html#method.join
551 /// [`Mutex`]: ../../std/sync/struct.Mutex.html
552 /// [`Condvar`]: ../../std/sync/struct.Condvar.html
553 #[stable(feature = "rust1", since = "1.0.0")]
554 pub fn yield_now() {
555     imp::Thread::yield_now()
556 }
557
558 /// Determines whether the current thread is unwinding because of panic.
559 ///
560 /// A common use of this feature is to poison shared resources when writing
561 /// unsafe code, by checking `panicking` when the `drop` is called.
562 ///
563 /// This is usually not needed when writing safe code, as [`Mutex`es][Mutex]
564 /// already poison themselves when a thread panics while holding the lock.
565 ///
566 /// This can also be used in multithreaded applications, in order to send a
567 /// message to other threads warning that a thread has panicked (e.g. for
568 /// monitoring purposes).
569 ///
570 /// # Examples
571 ///
572 /// ```should_panic
573 /// use std::thread;
574 ///
575 /// struct SomeStruct;
576 ///
577 /// impl Drop for SomeStruct {
578 ///     fn drop(&mut self) {
579 ///         if thread::panicking() {
580 ///             println!("dropped while unwinding");
581 ///         } else {
582 ///             println!("dropped while not unwinding");
583 ///         }
584 ///     }
585 /// }
586 ///
587 /// {
588 ///     print!("a: ");
589 ///     let a = SomeStruct;
590 /// }
591 ///
592 /// {
593 ///     print!("b: ");
594 ///     let b = SomeStruct;
595 ///     panic!()
596 /// }
597 /// ```
598 ///
599 /// [Mutex]: ../../std/sync/struct.Mutex.html
600 #[inline]
601 #[stable(feature = "rust1", since = "1.0.0")]
602 pub fn panicking() -> bool {
603     panicking::panicking()
604 }
605
606 /// Puts the current thread to sleep for the specified amount of time.
607 ///
608 /// The thread may sleep longer than the duration specified due to scheduling
609 /// specifics or platform-dependent functionality.
610 ///
611 /// # Platform behavior
612 ///
613 /// On Unix platforms this function will not return early due to a
614 /// signal being received or a spurious wakeup.
615 ///
616 /// # Examples
617 ///
618 /// ```no_run
619 /// use std::thread;
620 ///
621 /// // Let's sleep for 2 seconds:
622 /// thread::sleep_ms(2000);
623 /// ```
624 #[stable(feature = "rust1", since = "1.0.0")]
625 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::sleep`")]
626 pub fn sleep_ms(ms: u32) {
627     sleep(Duration::from_millis(ms as u64))
628 }
629
630 /// Puts the current thread to sleep for the specified amount of time.
631 ///
632 /// The thread may sleep longer than the duration specified due to scheduling
633 /// specifics or platform-dependent functionality.
634 ///
635 /// # Platform behavior
636 ///
637 /// On Unix platforms this function will not return early due to a
638 /// signal being received or a spurious wakeup. Platforms which do not support
639 /// nanosecond precision for sleeping will have `dur` rounded up to the nearest
640 /// granularity of time they can sleep for.
641 ///
642 /// # Examples
643 ///
644 /// ```no_run
645 /// use std::{thread, time};
646 ///
647 /// let ten_millis = time::Duration::from_millis(10);
648 /// let now = time::Instant::now();
649 ///
650 /// thread::sleep(ten_millis);
651 ///
652 /// assert!(now.elapsed() >= ten_millis);
653 /// ```
654 #[stable(feature = "thread_sleep", since = "1.4.0")]
655 pub fn sleep(dur: Duration) {
656     imp::Thread::sleep(dur)
657 }
658
659 /// Blocks unless or until the current thread's token is made available.
660 ///
661 /// A call to `park` does not guarantee that the thread will remain parked
662 /// forever, and callers should be prepared for this possibility.
663 ///
664 /// # park and unpark
665 ///
666 /// Every thread is equipped with some basic low-level blocking support, via the
667 /// [`thread::park`][`park`] function and [`thread::Thread::unpark`][`unpark`]
668 /// method. [`park`] blocks the current thread, which can then be resumed from
669 /// another thread by calling the [`unpark`] method on the blocked thread's
670 /// handle.
671 ///
672 /// Conceptually, each [`Thread`] handle has an associated token, which is
673 /// initially not present:
674 ///
675 /// * The [`thread::park`][`park`] function blocks the current thread unless or
676 ///   until the token is available for its thread handle, at which point it
677 ///   atomically consumes the token. It may also return *spuriously*, without
678 ///   consuming the token. [`thread::park_timeout`] does the same, but allows
679 ///   specifying a maximum time to block the thread for.
680 ///
681 /// * The [`unpark`] method on a [`Thread`] atomically makes the token available
682 ///   if it wasn't already.
683 ///
684 /// In other words, each [`Thread`] acts a bit like a spinlock that can be
685 /// locked and unlocked using `park` and `unpark`.
686 ///
687 /// The API is typically used by acquiring a handle to the current thread,
688 /// placing that handle in a shared data structure so that other threads can
689 /// find it, and then `park`ing. When some desired condition is met, another
690 /// thread calls [`unpark`] on the handle.
691 ///
692 /// The motivation for this design is twofold:
693 ///
694 /// * It avoids the need to allocate mutexes and condvars when building new
695 ///   synchronization primitives; the threads already provide basic
696 ///   blocking/signaling.
697 ///
698 /// * It can be implemented very efficiently on many platforms.
699 ///
700 /// # Examples
701 ///
702 /// ```
703 /// use std::thread;
704 /// use std::time::Duration;
705 ///
706 /// let parked_thread = thread::Builder::new()
707 ///     .spawn(|| {
708 ///         println!("Parking thread");
709 ///         thread::park();
710 ///         println!("Thread unparked");
711 ///     })
712 ///     .unwrap();
713 ///
714 /// // Let some time pass for the thread to be spawned.
715 /// thread::sleep(Duration::from_millis(10));
716 ///
717 /// println!("Unpark the thread");
718 /// parked_thread.thread().unpark();
719 ///
720 /// parked_thread.join().unwrap();
721 /// ```
722 ///
723 /// [`Thread`]: ../../std/thread/struct.Thread.html
724 /// [`park`]: ../../std/thread/fn.park.html
725 /// [`unpark`]: ../../std/thread/struct.Thread.html#method.unpark
726 /// [`thread::park_timeout`]: ../../std/thread/fn.park_timeout.html
727 //
728 // The implementation currently uses the trivial strategy of a Mutex+Condvar
729 // with wakeup flag, which does not actually allow spurious wakeups. In the
730 // future, this will be implemented in a more efficient way, perhaps along the lines of
731 //   http://cr.openjdk.java.net/~stefank/6989984.1/raw_files/new/src/os/linux/vm/os_linux.cpp
732 // or futuxes, and in either case may allow spurious wakeups.
733 #[stable(feature = "rust1", since = "1.0.0")]
734 pub fn park() {
735     let thread = current();
736     let mut guard = thread.inner.lock.lock().unwrap();
737     while !*guard {
738         guard = thread.inner.cvar.wait(guard).unwrap();
739     }
740     *guard = false;
741 }
742
743 /// Use [`park_timeout`].
744 ///
745 /// Blocks unless or until the current thread's token is made available or
746 /// the specified duration has been reached (may wake spuriously).
747 ///
748 /// The semantics of this function are equivalent to [`park`] except
749 /// that the thread will be blocked for roughly no longer than `dur`. This
750 /// method should not be used for precise timing due to anomalies such as
751 /// preemption or platform differences that may not cause the maximum
752 /// amount of time waited to be precisely `ms` long.
753 ///
754 /// See the [park documentation][`park`] for more detail.
755 ///
756 /// [`park_timeout`]: fn.park_timeout.html
757 /// [`park`]: ../../std/thread/fn.park.html
758 #[stable(feature = "rust1", since = "1.0.0")]
759 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::park_timeout`")]
760 pub fn park_timeout_ms(ms: u32) {
761     park_timeout(Duration::from_millis(ms as u64))
762 }
763
764 /// Blocks unless or until the current thread's token is made available or
765 /// the specified duration has been reached (may wake spuriously).
766 ///
767 /// The semantics of this function are equivalent to [`park`][park] except
768 /// that the thread will be blocked for roughly no longer than `dur`. This
769 /// method should not be used for precise timing due to anomalies such as
770 /// preemption or platform differences that may not cause the maximum
771 /// amount of time waited to be precisely `dur` long.
772 ///
773 /// See the [park dococumentation][park] for more details.
774 ///
775 /// # Platform behavior
776 ///
777 /// Platforms which do not support nanosecond precision for sleeping will have
778 /// `dur` rounded up to the nearest granularity of time they can sleep for.
779 ///
780 /// # Example
781 ///
782 /// Waiting for the complete expiration of the timeout:
783 ///
784 /// ```rust,no_run
785 /// use std::thread::park_timeout;
786 /// use std::time::{Instant, Duration};
787 ///
788 /// let timeout = Duration::from_secs(2);
789 /// let beginning_park = Instant::now();
790 ///
791 /// let mut timeout_remaining = timeout;
792 /// loop {
793 ///     park_timeout(timeout_remaining);
794 ///     let elapsed = beginning_park.elapsed();
795 ///     if elapsed >= timeout {
796 ///         break;
797 ///     }
798 ///     println!("restarting park_timeout after {:?}", elapsed);
799 ///     timeout_remaining = timeout - elapsed;
800 /// }
801 /// ```
802 ///
803 /// [park]: fn.park.html
804 #[stable(feature = "park_timeout", since = "1.4.0")]
805 pub fn park_timeout(dur: Duration) {
806     let thread = current();
807     let mut guard = thread.inner.lock.lock().unwrap();
808     if !*guard {
809         let (g, _) = thread.inner.cvar.wait_timeout(guard, dur).unwrap();
810         guard = g;
811     }
812     *guard = false;
813 }
814
815 ////////////////////////////////////////////////////////////////////////////////
816 // ThreadId
817 ////////////////////////////////////////////////////////////////////////////////
818
819 /// A unique identifier for a running thread.
820 ///
821 /// A `ThreadId` is an opaque object that has a unique value for each thread
822 /// that creates one. `ThreadId`s are not guaranteed to correspond to a thread's
823 /// system-designated identifier.
824 ///
825 /// # Examples
826 ///
827 /// ```
828 /// #![feature(thread_id)]
829 ///
830 /// use std::thread;
831 ///
832 /// let other_thread = thread::spawn(|| {
833 ///     thread::current().id()
834 /// });
835 ///
836 /// let other_thread_id = other_thread.join().unwrap();
837 /// assert!(thread::current().id() != other_thread_id);
838 /// ```
839 #[unstable(feature = "thread_id", issue = "21507")]
840 #[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
841 pub struct ThreadId(u64);
842
843 impl ThreadId {
844     // Generate a new unique thread ID.
845     fn new() -> ThreadId {
846         static GUARD: mutex::Mutex = mutex::Mutex::new();
847         static mut COUNTER: u64 = 0;
848
849         unsafe {
850             GUARD.lock();
851
852             // If we somehow use up all our bits, panic so that we're not
853             // covering up subtle bugs of IDs being reused.
854             if COUNTER == ::u64::MAX {
855                 GUARD.unlock();
856                 panic!("failed to generate unique thread ID: bitspace exhausted");
857             }
858
859             let id = COUNTER;
860             COUNTER += 1;
861
862             GUARD.unlock();
863
864             ThreadId(id)
865         }
866     }
867 }
868
869 ////////////////////////////////////////////////////////////////////////////////
870 // Thread
871 ////////////////////////////////////////////////////////////////////////////////
872
873 /// The internal representation of a `Thread` handle
874 struct Inner {
875     name: Option<CString>,      // Guaranteed to be UTF-8
876     id: ThreadId,
877     lock: Mutex<bool>,          // true when there is a buffered unpark
878     cvar: Condvar,
879 }
880
881 #[derive(Clone)]
882 #[stable(feature = "rust1", since = "1.0.0")]
883 /// A handle to a thread.
884 ///
885 /// Threads are represented via the `Thread` type, which you can get in one of
886 /// two ways:
887 ///
888 /// * By spawning a new thread, e.g. using the [`thread::spawn`][`spawn`]
889 ///   function, and calling [`thread`][`JoinHandle::thread`] on the
890 ///   [`JoinHandle`].
891 /// * By requesting the current thread, using the [`thread::current`] function.
892 ///
893 /// The [`thread::current`] function is available even for threads not spawned
894 /// by the APIs of this module.
895 ///
896 /// There is usualy no need to create a `Thread` struct yourself, one
897 /// should instead use a function like `spawn` to create new threads, see the
898 /// docs of [`Builder`] and [`spawn`] for more details.
899 ///
900 /// [`Builder`]: ../../std/thread/struct.Builder.html
901 /// [`spawn`]: ../../std/thread/fn.spawn.html
902
903 pub struct Thread {
904     inner: Arc<Inner>,
905 }
906
907 impl Thread {
908     // Used only internally to construct a thread object without spawning
909     pub(crate) fn new(name: Option<String>) -> Thread {
910         let cname = name.map(|n| {
911             CString::new(n).expect("thread name may not contain interior null bytes")
912         });
913         Thread {
914             inner: Arc::new(Inner {
915                 name: cname,
916                 id: ThreadId::new(),
917                 lock: Mutex::new(false),
918                 cvar: Condvar::new(),
919             })
920         }
921     }
922
923     /// Atomically makes the handle's token available if it is not already.
924     ///
925     /// Every thread is equipped with some basic low-level blocking support, via
926     /// the [`park`][park] function and the `unpark()` method. These can be
927     /// used as a more CPU-efficient implementation of a spinlock.
928     ///
929     /// See the [park documentation][park] for more details.
930     ///
931     /// # Examples
932     ///
933     /// ```
934     /// use std::thread;
935     /// use std::time::Duration;
936     ///
937     /// let parked_thread = thread::Builder::new()
938     ///     .spawn(|| {
939     ///         println!("Parking thread");
940     ///         thread::park();
941     ///         println!("Thread unparked");
942     ///     })
943     ///     .unwrap();
944     ///
945     /// // Let some time pass for the thread to be spawned.
946     /// thread::sleep(Duration::from_millis(10));
947     ///
948     /// println!("Unpark the thread");
949     /// parked_thread.thread().unpark();
950     ///
951     /// parked_thread.join().unwrap();
952     /// ```
953     ///
954     /// [park]: fn.park.html
955     #[stable(feature = "rust1", since = "1.0.0")]
956     pub fn unpark(&self) {
957         let mut guard = self.inner.lock.lock().unwrap();
958         if !*guard {
959             *guard = true;
960             self.inner.cvar.notify_one();
961         }
962     }
963
964     /// Gets the thread's unique identifier.
965     ///
966     /// # Examples
967     ///
968     /// ```
969     /// #![feature(thread_id)]
970     ///
971     /// use std::thread;
972     ///
973     /// let other_thread = thread::spawn(|| {
974     ///     thread::current().id()
975     /// });
976     ///
977     /// let other_thread_id = other_thread.join().unwrap();
978     /// assert!(thread::current().id() != other_thread_id);
979     /// ```
980     #[unstable(feature = "thread_id", issue = "21507")]
981     pub fn id(&self) -> ThreadId {
982         self.inner.id
983     }
984
985     /// Gets the thread's name.
986     ///
987     /// # Examples
988     ///
989     /// Threads by default have no name specified:
990     ///
991     /// ```
992     /// use std::thread;
993     ///
994     /// let builder = thread::Builder::new();
995     ///
996     /// let handler = builder.spawn(|| {
997     ///     assert!(thread::current().name().is_none());
998     /// }).unwrap();
999     ///
1000     /// handler.join().unwrap();
1001     /// ```
1002     ///
1003     /// Thread with a specified name:
1004     ///
1005     /// ```
1006     /// use std::thread;
1007     ///
1008     /// let builder = thread::Builder::new()
1009     ///     .name("foo".into());
1010     ///
1011     /// let handler = builder.spawn(|| {
1012     ///     assert_eq!(thread::current().name(), Some("foo"))
1013     /// }).unwrap();
1014     ///
1015     /// handler.join().unwrap();
1016     /// ```
1017     #[stable(feature = "rust1", since = "1.0.0")]
1018     pub fn name(&self) -> Option<&str> {
1019         self.cname().map(|s| unsafe { str::from_utf8_unchecked(s.to_bytes()) } )
1020     }
1021
1022     fn cname(&self) -> Option<&CStr> {
1023         self.inner.name.as_ref().map(|s| &**s)
1024     }
1025 }
1026
1027 #[stable(feature = "rust1", since = "1.0.0")]
1028 impl fmt::Debug for Thread {
1029     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1030         fmt::Debug::fmt(&self.name(), f)
1031     }
1032 }
1033
1034 ////////////////////////////////////////////////////////////////////////////////
1035 // JoinHandle
1036 ////////////////////////////////////////////////////////////////////////////////
1037
1038 /// A specialized [`Result`] type for threads.
1039 ///
1040 /// Indicates the manner in which a thread exited.
1041 ///
1042 /// A thread that completes without panicking is considered to exit successfully.
1043 ///
1044 /// # Examples
1045 ///
1046 /// ```no_run
1047 /// use std::thread;
1048 /// use std::fs;
1049 ///
1050 /// fn copy_in_thread() -> thread::Result<()> {
1051 ///     thread::spawn(move || { fs::copy("foo.txt", "bar.txt").unwrap(); }).join()
1052 /// }
1053 ///
1054 /// fn main() {
1055 ///     match copy_in_thread() {
1056 ///         Ok(_) => println!("this is fine"),
1057 ///         Err(_) => println!("thread panicked"),
1058 ///     }
1059 /// }
1060 /// ```
1061 ///
1062 /// [`Result`]: ../../std/result/enum.Result.html
1063 #[stable(feature = "rust1", since = "1.0.0")]
1064 pub type Result<T> = ::result::Result<T, Box<Any + Send + 'static>>;
1065
1066 // This packet is used to communicate the return value between the child thread
1067 // and the parent thread. Memory is shared through the `Arc` within and there's
1068 // no need for a mutex here because synchronization happens with `join()` (the
1069 // parent thread never reads this packet until the child has exited).
1070 //
1071 // This packet itself is then stored into a `JoinInner` which in turns is placed
1072 // in `JoinHandle` and `JoinGuard`. Due to the usage of `UnsafeCell` we need to
1073 // manually worry about impls like Send and Sync. The type `T` should
1074 // already always be Send (otherwise the thread could not have been created) and
1075 // this type is inherently Sync because no methods take &self. Regardless,
1076 // however, we add inheriting impls for Send/Sync to this type to ensure it's
1077 // Send/Sync and that future modifications will still appropriately classify it.
1078 struct Packet<T>(Arc<UnsafeCell<Option<Result<T>>>>);
1079
1080 unsafe impl<T: Send> Send for Packet<T> {}
1081 unsafe impl<T: Sync> Sync for Packet<T> {}
1082
1083 /// Inner representation for JoinHandle
1084 struct JoinInner<T> {
1085     native: Option<imp::Thread>,
1086     thread: Thread,
1087     packet: Packet<T>,
1088 }
1089
1090 impl<T> JoinInner<T> {
1091     fn join(&mut self) -> Result<T> {
1092         self.native.take().unwrap().join();
1093         unsafe {
1094             (*self.packet.0.get()).take().unwrap()
1095         }
1096     }
1097 }
1098
1099 /// An owned permission to join on a thread (block on its termination).
1100 ///
1101 /// A `JoinHandle` *detaches* the associated thread when it is dropped, which
1102 /// means that there is no longer any handle to thread and no way to `join`
1103 /// on it.
1104 ///
1105 /// Due to platform restrictions, it is not possible to [`Clone`] this
1106 /// handle: the ability to join a thread is a uniquely-owned permission.
1107 ///
1108 /// This `struct` is created by the [`thread::spawn`] function and the
1109 /// [`thread::Builder::spawn`] method.
1110 ///
1111 /// # Examples
1112 ///
1113 /// Creation from [`thread::spawn`]:
1114 ///
1115 /// ```
1116 /// use std::thread;
1117 ///
1118 /// let join_handle: thread::JoinHandle<_> = thread::spawn(|| {
1119 ///     // some work here
1120 /// });
1121 /// ```
1122 ///
1123 /// Creation from [`thread::Builder::spawn`]:
1124 ///
1125 /// ```
1126 /// use std::thread;
1127 ///
1128 /// let builder = thread::Builder::new();
1129 ///
1130 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1131 ///     // some work here
1132 /// }).unwrap();
1133 /// ```
1134 ///
1135 /// Child being detached and outliving its parent:
1136 ///
1137 /// ```no_run
1138 /// use std::thread;
1139 /// use std::time::Duration;
1140 ///
1141 /// let original_thread = thread::spawn(|| {
1142 ///     let _detached_thread = thread::spawn(|| {
1143 ///         // Here we sleep to make sure that the first thread returns before.
1144 ///         thread::sleep(Duration::from_millis(10));
1145 ///         // This will be called, even though the JoinHandle is dropped.
1146 ///         println!("♫ Still alive â™«");
1147 ///     });
1148 /// });
1149 ///
1150 /// let _ = original_thread.join();
1151 /// println!("Original thread is joined.");
1152 ///
1153 /// // We make sure that the new thread has time to run, before the main
1154 /// // thread returns.
1155 ///
1156 /// thread::sleep(Duration::from_millis(1000));
1157 /// ```
1158 ///
1159 /// [`Clone`]: ../../std/clone/trait.Clone.html
1160 /// [`thread::spawn`]: fn.spawn.html
1161 /// [`thread::Builder::spawn`]: struct.Builder.html#method.spawn
1162 #[stable(feature = "rust1", since = "1.0.0")]
1163 pub struct JoinHandle<T>(JoinInner<T>);
1164
1165 impl<T> JoinHandle<T> {
1166     /// Extracts a handle to the underlying thread.
1167     ///
1168     /// # Examples
1169     ///
1170     /// ```
1171     /// #![feature(thread_id)]
1172     ///
1173     /// use std::thread;
1174     ///
1175     /// let builder = thread::Builder::new();
1176     ///
1177     /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1178     ///     // some work here
1179     /// }).unwrap();
1180     ///
1181     /// let thread = join_handle.thread();
1182     /// println!("thread id: {:?}", thread.id());
1183     /// ```
1184     #[stable(feature = "rust1", since = "1.0.0")]
1185     pub fn thread(&self) -> &Thread {
1186         &self.0.thread
1187     }
1188
1189     /// Waits for the associated thread to finish.
1190     ///
1191     /// If the child thread panics, [`Err`] is returned with the parameter given
1192     /// to [`panic`].
1193     ///
1194     /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1195     /// [`panic`]: ../../std/macro.panic.html
1196     ///
1197     /// # Examples
1198     ///
1199     /// ```
1200     /// use std::thread;
1201     ///
1202     /// let builder = thread::Builder::new();
1203     ///
1204     /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1205     ///     // some work here
1206     /// }).unwrap();
1207     /// join_handle.join().expect("Couldn't join on the associated thread");
1208     /// ```
1209     #[stable(feature = "rust1", since = "1.0.0")]
1210     pub fn join(mut self) -> Result<T> {
1211         self.0.join()
1212     }
1213 }
1214
1215 impl<T> AsInner<imp::Thread> for JoinHandle<T> {
1216     fn as_inner(&self) -> &imp::Thread { self.0.native.as_ref().unwrap() }
1217 }
1218
1219 impl<T> IntoInner<imp::Thread> for JoinHandle<T> {
1220     fn into_inner(self) -> imp::Thread { self.0.native.unwrap() }
1221 }
1222
1223 #[stable(feature = "std_debug", since = "1.16.0")]
1224 impl<T> fmt::Debug for JoinHandle<T> {
1225     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1226         f.pad("JoinHandle { .. }")
1227     }
1228 }
1229
1230 fn _assert_sync_and_send() {
1231     fn _assert_both<T: Send + Sync>() {}
1232     _assert_both::<JoinHandle<()>>();
1233     _assert_both::<Thread>();
1234 }
1235
1236 ////////////////////////////////////////////////////////////////////////////////
1237 // Tests
1238 ////////////////////////////////////////////////////////////////////////////////
1239
1240 #[cfg(all(test, not(target_os = "emscripten")))]
1241 mod tests {
1242     use any::Any;
1243     use sync::mpsc::{channel, Sender};
1244     use result;
1245     use super::{Builder};
1246     use thread;
1247     use time::Duration;
1248     use u32;
1249
1250     // !!! These tests are dangerous. If something is buggy, they will hang, !!!
1251     // !!! instead of exiting cleanly. This might wedge the buildbots.       !!!
1252
1253     #[test]
1254     fn test_unnamed_thread() {
1255         thread::spawn(move|| {
1256             assert!(thread::current().name().is_none());
1257         }).join().ok().unwrap();
1258     }
1259
1260     #[test]
1261     fn test_named_thread() {
1262         Builder::new().name("ada lovelace".to_string()).spawn(move|| {
1263             assert!(thread::current().name().unwrap() == "ada lovelace".to_string());
1264         }).unwrap().join().unwrap();
1265     }
1266
1267     #[test]
1268     #[should_panic]
1269     fn test_invalid_named_thread() {
1270         let _ = Builder::new().name("ada l\0velace".to_string()).spawn(|| {});
1271     }
1272
1273     #[test]
1274     fn test_run_basic() {
1275         let (tx, rx) = channel();
1276         thread::spawn(move|| {
1277             tx.send(()).unwrap();
1278         });
1279         rx.recv().unwrap();
1280     }
1281
1282     #[test]
1283     fn test_join_panic() {
1284         match thread::spawn(move|| {
1285             panic!()
1286         }).join() {
1287             result::Result::Err(_) => (),
1288             result::Result::Ok(()) => panic!()
1289         }
1290     }
1291
1292     #[test]
1293     fn test_spawn_sched() {
1294         let (tx, rx) = channel();
1295
1296         fn f(i: i32, tx: Sender<()>) {
1297             let tx = tx.clone();
1298             thread::spawn(move|| {
1299                 if i == 0 {
1300                     tx.send(()).unwrap();
1301                 } else {
1302                     f(i - 1, tx);
1303                 }
1304             });
1305
1306         }
1307         f(10, tx);
1308         rx.recv().unwrap();
1309     }
1310
1311     #[test]
1312     fn test_spawn_sched_childs_on_default_sched() {
1313         let (tx, rx) = channel();
1314
1315         thread::spawn(move|| {
1316             thread::spawn(move|| {
1317                 tx.send(()).unwrap();
1318             });
1319         });
1320
1321         rx.recv().unwrap();
1322     }
1323
1324     fn avoid_copying_the_body<F>(spawnfn: F) where F: FnOnce(Box<Fn() + Send>) {
1325         let (tx, rx) = channel();
1326
1327         let x: Box<_> = box 1;
1328         let x_in_parent = (&*x) as *const i32 as usize;
1329
1330         spawnfn(Box::new(move|| {
1331             let x_in_child = (&*x) as *const i32 as usize;
1332             tx.send(x_in_child).unwrap();
1333         }));
1334
1335         let x_in_child = rx.recv().unwrap();
1336         assert_eq!(x_in_parent, x_in_child);
1337     }
1338
1339     #[test]
1340     fn test_avoid_copying_the_body_spawn() {
1341         avoid_copying_the_body(|v| {
1342             thread::spawn(move || v());
1343         });
1344     }
1345
1346     #[test]
1347     fn test_avoid_copying_the_body_thread_spawn() {
1348         avoid_copying_the_body(|f| {
1349             thread::spawn(move|| {
1350                 f();
1351             });
1352         })
1353     }
1354
1355     #[test]
1356     fn test_avoid_copying_the_body_join() {
1357         avoid_copying_the_body(|f| {
1358             let _ = thread::spawn(move|| {
1359                 f()
1360             }).join();
1361         })
1362     }
1363
1364     #[test]
1365     fn test_child_doesnt_ref_parent() {
1366         // If the child refcounts the parent thread, this will stack overflow when
1367         // climbing the thread tree to dereference each ancestor. (See #1789)
1368         // (well, it would if the constant were 8000+ - I lowered it to be more
1369         // valgrind-friendly. try this at home, instead..!)
1370         const GENERATIONS: u32 = 16;
1371         fn child_no(x: u32) -> Box<Fn() + Send> {
1372             return Box::new(move|| {
1373                 if x < GENERATIONS {
1374                     thread::spawn(move|| child_no(x+1)());
1375                 }
1376             });
1377         }
1378         thread::spawn(|| child_no(0)());
1379     }
1380
1381     #[test]
1382     fn test_simple_newsched_spawn() {
1383         thread::spawn(move || {});
1384     }
1385
1386     #[test]
1387     fn test_try_panic_message_static_str() {
1388         match thread::spawn(move|| {
1389             panic!("static string");
1390         }).join() {
1391             Err(e) => {
1392                 type T = &'static str;
1393                 assert!(e.is::<T>());
1394                 assert_eq!(*e.downcast::<T>().unwrap(), "static string");
1395             }
1396             Ok(()) => panic!()
1397         }
1398     }
1399
1400     #[test]
1401     fn test_try_panic_message_owned_str() {
1402         match thread::spawn(move|| {
1403             panic!("owned string".to_string());
1404         }).join() {
1405             Err(e) => {
1406                 type T = String;
1407                 assert!(e.is::<T>());
1408                 assert_eq!(*e.downcast::<T>().unwrap(), "owned string".to_string());
1409             }
1410             Ok(()) => panic!()
1411         }
1412     }
1413
1414     #[test]
1415     fn test_try_panic_message_any() {
1416         match thread::spawn(move|| {
1417             panic!(box 413u16 as Box<Any + Send>);
1418         }).join() {
1419             Err(e) => {
1420                 type T = Box<Any + Send>;
1421                 assert!(e.is::<T>());
1422                 let any = e.downcast::<T>().unwrap();
1423                 assert!(any.is::<u16>());
1424                 assert_eq!(*any.downcast::<u16>().unwrap(), 413);
1425             }
1426             Ok(()) => panic!()
1427         }
1428     }
1429
1430     #[test]
1431     fn test_try_panic_message_unit_struct() {
1432         struct Juju;
1433
1434         match thread::spawn(move|| {
1435             panic!(Juju)
1436         }).join() {
1437             Err(ref e) if e.is::<Juju>() => {}
1438             Err(_) | Ok(()) => panic!()
1439         }
1440     }
1441
1442     #[test]
1443     fn test_park_timeout_unpark_before() {
1444         for _ in 0..10 {
1445             thread::current().unpark();
1446             thread::park_timeout(Duration::from_millis(u32::MAX as u64));
1447         }
1448     }
1449
1450     #[test]
1451     fn test_park_timeout_unpark_not_called() {
1452         for _ in 0..10 {
1453             thread::park_timeout(Duration::from_millis(10));
1454         }
1455     }
1456
1457     #[test]
1458     fn test_park_timeout_unpark_called_other_thread() {
1459         for _ in 0..10 {
1460             let th = thread::current();
1461
1462             let _guard = thread::spawn(move || {
1463                 super::sleep(Duration::from_millis(50));
1464                 th.unpark();
1465             });
1466
1467             thread::park_timeout(Duration::from_millis(u32::MAX as u64));
1468         }
1469     }
1470
1471     #[test]
1472     fn sleep_ms_smoke() {
1473         thread::sleep(Duration::from_millis(2));
1474     }
1475
1476     #[test]
1477     fn test_thread_id_equal() {
1478         assert!(thread::current().id() == thread::current().id());
1479     }
1480
1481     #[test]
1482     fn test_thread_id_not_equal() {
1483         let spawned_id = thread::spawn(|| thread::current().id()).join().unwrap();
1484         assert!(thread::current().id() != spawned_id);
1485     }
1486
1487     // NOTE: the corresponding test for stderr is in run-pass/thread-stderr, due
1488     // to the test harness apparently interfering with stderr configuration.
1489 }