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