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