]> git.lizzy.rs Git - rust.git/blob - library/std/src/thread/mod.rs
Added docs to internal_macro const
[rust.git] / library / std / src / thread / mod.rs
1 //! Native threads.
2 //!
3 //! ## The threading model
4 //!
5 //! An executing Rust program consists of a collection of native OS threads,
6 //! each with their own stack and local state. Threads can be named, and
7 //! provide some built-in support for low-level synchronization.
8 //!
9 //! Communication between threads can be done through
10 //! [channels], Rust's message-passing types, along with [other forms of thread
11 //! synchronization](../../std/sync/index.html) and shared-memory data
12 //! structures. In particular, types that are guaranteed to be
13 //! threadsafe are easily shared between threads using the
14 //! atomically-reference-counted container, [`Arc`].
15 //!
16 //! Fatal logic errors in Rust cause *thread panic*, during which
17 //! a thread will unwind the stack, running destructors and freeing
18 //! owned resources. While not meant as a 'try/catch' mechanism, panics
19 //! in Rust can nonetheless be caught (unless compiling with `panic=abort`) with
20 //! [`catch_unwind`](../../std/panic/fn.catch_unwind.html) and recovered
21 //! from, or alternatively be resumed with
22 //! [`resume_unwind`](../../std/panic/fn.resume_unwind.html). If the panic
23 //! is not caught the thread will exit, but the panic may optionally be
24 //! detected from a different thread with [`join`]. If the main thread panics
25 //! without the panic being caught, the application will exit with a
26 //! non-zero exit code.
27 //!
28 //! When the main thread of a Rust program terminates, the entire program shuts
29 //! down, even if other threads are still running. However, this module provides
30 //! convenient facilities for automatically waiting for the termination of a
31 //! thread (i.e., join).
32 //!
33 //! ## Spawning a thread
34 //!
35 //! A new thread can be spawned using the [`thread::spawn`][`spawn`] function:
36 //!
37 //! ```rust
38 //! use std::thread;
39 //!
40 //! thread::spawn(move || {
41 //!     // some work here
42 //! });
43 //! ```
44 //!
45 //! In this example, the spawned thread is "detached," which means that there is
46 //! no way for the program to learn when the spawned thread completes or otherwise
47 //! terminates.
48 //!
49 //! To learn when a thread completes, it is necessary to capture the [`JoinHandle`]
50 //! object that is returned by the call to [`spawn`], which provides
51 //! a `join` method that allows the caller to wait for the completion of the
52 //! spawned thread:
53 //!
54 //! ```rust
55 //! use std::thread;
56 //!
57 //! let thread_join_handle = thread::spawn(move || {
58 //!     // some work here
59 //! });
60 //! // some work here
61 //! let res = thread_join_handle.join();
62 //! ```
63 //!
64 //! The [`join`] method returns a [`thread::Result`] containing [`Ok`] of the final
65 //! value produced by the spawned thread, or [`Err`] of the value given to
66 //! a call to [`panic!`] if the thread panicked.
67 //!
68 //! Note that there is no parent/child relationship between a thread that spawns a
69 //! new thread and the thread being spawned.  In particular, the spawned thread may or
70 //! may not outlive the spawning thread, unless the spawning thread is the main thread.
71 //!
72 //! ## Configuring threads
73 //!
74 //! A new thread can be configured before it is spawned via the [`Builder`] type,
75 //! which currently allows you to set the name and stack size for the thread:
76 //!
77 //! ```rust
78 //! # #![allow(unused_must_use)]
79 //! use std::thread;
80 //!
81 //! thread::Builder::new().name("thread1".to_string()).spawn(move || {
82 //!     println!("Hello, world!");
83 //! });
84 //! ```
85 //!
86 //! ## The `Thread` type
87 //!
88 //! Threads are represented via the [`Thread`] type, which you can get in one of
89 //! two ways:
90 //!
91 //! * By spawning a new thread, e.g., using the [`thread::spawn`][`spawn`]
92 //!   function, and calling [`thread`][`JoinHandle::thread`] on the [`JoinHandle`].
93 //! * By requesting the current thread, using the [`thread::current`] function.
94 //!
95 //! The [`thread::current`] function is available even for threads not spawned
96 //! by the APIs of this module.
97 //!
98 //! ## Thread-local storage
99 //!
100 //! This module also provides an implementation of thread-local storage for Rust
101 //! programs. Thread-local storage is a method of storing data into a global
102 //! variable that each thread in the program will have its own copy of.
103 //! Threads do not share this data, so accesses do not need to be synchronized.
104 //!
105 //! A thread-local key owns the value it contains and will destroy the value when the
106 //! thread exits. It is created with the [`thread_local!`] macro and can contain any
107 //! value that is `'static` (no borrowed pointers). It provides an accessor function,
108 //! [`with`], that yields a shared reference to the value to the specified
109 //! closure. Thread-local keys allow only shared access to values, as there would be no
110 //! way to guarantee uniqueness if mutable borrows were allowed. Most values
111 //! will want to make use of some form of **interior mutability** through the
112 //! [`Cell`] or [`RefCell`] types.
113 //!
114 //! ## Naming threads
115 //!
116 //! Threads are able to have associated names for identification purposes. By default, spawned
117 //! threads are unnamed. To specify a name for a thread, build the thread with [`Builder`] and pass
118 //! the desired thread name to [`Builder::name`]. To retrieve the thread name from within the
119 //! thread, use [`Thread::name`]. A couple examples of where the name of a thread gets used:
120 //!
121 //! * If a panic occurs in a named thread, the thread name will be printed in the panic message.
122 //! * The thread name is provided to the OS where applicable (e.g., `pthread_setname_np` in
123 //!   unix-like platforms).
124 //!
125 //! ## Stack size
126 //!
127 //! The default stack size for spawned threads is 2 MiB, though this particular stack size is
128 //! subject to change in the future. There are two ways to manually specify the stack size for
129 //! spawned threads:
130 //!
131 //! * Build the thread with [`Builder`] and pass the desired stack size to [`Builder::stack_size`].
132 //! * Set the `RUST_MIN_STACK` environment variable to an integer representing the desired stack
133 //!   size (in bytes). Note that setting [`Builder::stack_size`] will override this.
134 //!
135 //! Note that the stack size of the main thread is *not* determined by Rust.
136 //!
137 //! [channels]: crate::sync::mpsc
138 //! [`join`]: JoinHandle::join
139 //! [`Result`]: crate::result::Result
140 //! [`Ok`]: crate::result::Result::Ok
141 //! [`Err`]: crate::result::Result::Err
142 //! [`thread::current`]: current
143 //! [`thread::Result`]: Result
144 //! [`unpark`]: Thread::unpark
145 //! [`thread::park_timeout`]: park_timeout
146 //! [`Cell`]: crate::cell::Cell
147 //! [`RefCell`]: crate::cell::RefCell
148 //! [`with`]: LocalKey::with
149
150 #![stable(feature = "rust1", since = "1.0.0")]
151 #![deny(unsafe_op_in_unsafe_fn)]
152
153 #[cfg(all(test, not(target_os = "emscripten")))]
154 mod tests;
155
156 use crate::any::Any;
157 use crate::cell::UnsafeCell;
158 use crate::ffi::{CStr, CString};
159 use crate::fmt;
160 use crate::io;
161 use crate::mem;
162 use crate::num::NonZeroU64;
163 use crate::num::NonZeroUsize;
164 use crate::panic;
165 use crate::panicking;
166 use crate::str;
167 use crate::sync::Arc;
168 use crate::sys::thread as imp;
169 use crate::sys_common::mutex;
170 use crate::sys_common::thread;
171 use crate::sys_common::thread_info;
172 use crate::sys_common::thread_parker::Parker;
173 use crate::sys_common::{AsInner, IntoInner};
174 use crate::time::Duration;
175
176 ////////////////////////////////////////////////////////////////////////////////
177 // Thread-local storage
178 ////////////////////////////////////////////////////////////////////////////////
179
180 #[macro_use]
181 mod local;
182
183 #[stable(feature = "rust1", since = "1.0.0")]
184 pub use self::local::{AccessError, LocalKey};
185
186 // The types used by the thread_local! macro to access TLS keys. Note that there
187 // are two types, the "OS" type and the "fast" type. The OS thread local key
188 // type is accessed via platform-specific API calls and is slow, while the fast
189 // key type is accessed via code generated via LLVM, where TLS keys are set up
190 // by the elf linker. Note that the OS TLS type is always available: on macOS
191 // the standard library is compiled with support for older platform versions
192 // where fast TLS was not available; end-user code is compiled with fast TLS
193 // where available, but both are needed.
194
195 #[unstable(feature = "libstd_thread_internals", issue = "none")]
196 #[cfg(target_thread_local)]
197 #[doc(hidden)]
198 pub use self::local::fast::Key as __FastLocalKeyInner;
199 #[unstable(feature = "libstd_thread_internals", issue = "none")]
200 #[doc(hidden)]
201 pub use self::local::os::Key as __OsLocalKeyInner;
202 #[unstable(feature = "libstd_thread_internals", issue = "none")]
203 #[cfg(all(target_arch = "wasm32", not(target_feature = "atomics")))]
204 #[doc(hidden)]
205 pub use self::local::statik::Key as __StaticLocalKeyInner;
206
207 // This is only used to make thread locals with `const { .. }` initialization
208 // expressions unstable. If and/or when that syntax is stabilized with thread
209 // locals this will simply be removed.
210 #[doc(hidden)]
211 #[unstable(feature = "thread_local_const_init", issue = "84223")]
212 pub const fn require_unstable_const_init_thread_local() {}
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 /// panic 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 /// [`stack_size`]: Builder::stack_size
253 /// [`name`]: Builder::name
254 /// [`spawn`]: Builder::spawn
255 /// [`thread::spawn`]: spawn
256 /// [`io::Result`]: crate::io::Result
257 /// [`unwrap`]: crate::result::Result::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(32 * 1024);
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 { name: None, stack_size: None }
291     }
292
293     /// Names the thread-to-be. Currently the name is used for identification
294     /// only in panic messages.
295     ///
296     /// The name must not contain null bytes (`\0`).
297     ///
298     /// For more information about named threads, see
299     /// [this module-level documentation][naming-threads].
300     ///
301     /// # Examples
302     ///
303     /// ```
304     /// use std::thread;
305     ///
306     /// let builder = thread::Builder::new()
307     ///     .name("foo".into());
308     ///
309     /// let handler = builder.spawn(|| {
310     ///     assert_eq!(thread::current().name(), Some("foo"))
311     /// }).unwrap();
312     ///
313     /// handler.join().unwrap();
314     /// ```
315     ///
316     /// [naming-threads]: ./index.html#naming-threads
317     #[stable(feature = "rust1", since = "1.0.0")]
318     pub fn name(mut self, name: String) -> Builder {
319         self.name = Some(name);
320         self
321     }
322
323     /// Sets the size of the stack (in bytes) for the new thread.
324     ///
325     /// The actual stack size may be greater than this value if
326     /// the platform specifies a minimal stack size.
327     ///
328     /// For more information about the stack size for threads, see
329     /// [this module-level documentation][stack-size].
330     ///
331     /// # Examples
332     ///
333     /// ```
334     /// use std::thread;
335     ///
336     /// let builder = thread::Builder::new().stack_size(32 * 1024);
337     /// ```
338     ///
339     /// [stack-size]: ./index.html#stack-size
340     #[stable(feature = "rust1", since = "1.0.0")]
341     pub fn stack_size(mut self, size: usize) -> Builder {
342         self.stack_size = Some(size);
343         self
344     }
345
346     /// Spawns a new thread by taking ownership of the `Builder`, and returns an
347     /// [`io::Result`] to its [`JoinHandle`].
348     ///
349     /// The spawned thread may outlive the caller (unless the caller thread
350     /// is the main thread; the whole process is terminated when the main
351     /// thread finishes). The join handle can be used to block on
352     /// termination of the spawned thread, including recovering its panics.
353     ///
354     /// For a more complete documentation see [`thread::spawn`][`spawn`].
355     ///
356     /// # Errors
357     ///
358     /// Unlike the [`spawn`] free function, this method yields an
359     /// [`io::Result`] to capture any failure to create the thread at
360     /// the OS level.
361     ///
362     /// [`io::Result`]: crate::io::Result
363     ///
364     /// # Panics
365     ///
366     /// Panics if a thread name was set and it contained null bytes.
367     ///
368     /// # Examples
369     ///
370     /// ```
371     /// use std::thread;
372     ///
373     /// let builder = thread::Builder::new();
374     ///
375     /// let handler = builder.spawn(|| {
376     ///     // thread code
377     /// }).unwrap();
378     ///
379     /// handler.join().unwrap();
380     /// ```
381     #[stable(feature = "rust1", since = "1.0.0")]
382     pub fn spawn<F, T>(self, f: F) -> io::Result<JoinHandle<T>>
383     where
384         F: FnOnce() -> T,
385         F: Send + 'static,
386         T: Send + 'static,
387     {
388         unsafe { self.spawn_unchecked(f) }
389     }
390
391     /// Spawns a new thread without any lifetime restrictions by taking ownership
392     /// of the `Builder`, and returns an [`io::Result`] to its [`JoinHandle`].
393     ///
394     /// The spawned thread may outlive the caller (unless the caller thread
395     /// is the main thread; the whole process is terminated when the main
396     /// thread finishes). The join handle can be used to block on
397     /// termination of the spawned thread, including recovering its panics.
398     ///
399     /// This method is identical to [`thread::Builder::spawn`][`Builder::spawn`],
400     /// except for the relaxed lifetime bounds, which render it unsafe.
401     /// For a more complete documentation see [`thread::spawn`][`spawn`].
402     ///
403     /// # Errors
404     ///
405     /// Unlike the [`spawn`] free function, this method yields an
406     /// [`io::Result`] to capture any failure to create the thread at
407     /// the OS level.
408     ///
409     /// # Panics
410     ///
411     /// Panics if a thread name was set and it contained null bytes.
412     ///
413     /// # Safety
414     ///
415     /// The caller has to ensure that the spawned thread does not outlive any
416     /// references in the supplied thread closure and its return type.
417     /// This can be guaranteed in two ways:
418     ///
419     /// - ensure that [`join`][`JoinHandle::join`] is called before any referenced
420     /// data is dropped
421     /// - use only types with `'static` lifetime bounds, i.e., those with no or only
422     /// `'static` references (both [`thread::Builder::spawn`][`Builder::spawn`]
423     /// and [`thread::spawn`][`spawn`] enforce this property statically)
424     ///
425     /// # Examples
426     ///
427     /// ```
428     /// #![feature(thread_spawn_unchecked)]
429     /// use std::thread;
430     ///
431     /// let builder = thread::Builder::new();
432     ///
433     /// let x = 1;
434     /// let thread_x = &x;
435     ///
436     /// let handler = unsafe {
437     ///     builder.spawn_unchecked(move || {
438     ///         println!("x = {}", *thread_x);
439     ///     }).unwrap()
440     /// };
441     ///
442     /// // caller has to ensure `join()` is called, otherwise
443     /// // it is possible to access freed memory if `x` gets
444     /// // dropped before the thread closure is executed!
445     /// handler.join().unwrap();
446     /// ```
447     ///
448     /// [`io::Result`]: crate::io::Result
449     #[unstable(feature = "thread_spawn_unchecked", issue = "55132")]
450     pub unsafe fn spawn_unchecked<'a, F, T>(self, f: F) -> io::Result<JoinHandle<T>>
451     where
452         F: FnOnce() -> T,
453         F: Send + 'a,
454         T: Send + 'a,
455     {
456         let Builder { name, stack_size } = self;
457
458         let stack_size = stack_size.unwrap_or_else(thread::min_stack);
459
460         let my_thread = Thread::new(name.map(|name| {
461             CString::new(name).expect("thread name may not contain interior null bytes")
462         }));
463         let their_thread = my_thread.clone();
464
465         let my_packet: Arc<UnsafeCell<Option<Result<T>>>> = Arc::new(UnsafeCell::new(None));
466         let their_packet = my_packet.clone();
467
468         let output_capture = crate::io::set_output_capture(None);
469         crate::io::set_output_capture(output_capture.clone());
470
471         let main = move || {
472             if let Some(name) = their_thread.cname() {
473                 imp::Thread::set_name(name);
474             }
475
476             crate::io::set_output_capture(output_capture);
477
478             // SAFETY: the stack guard passed is the one for the current thread.
479             // This means the current thread's stack and the new thread's stack
480             // are properly set and protected from each other.
481             thread_info::set(unsafe { imp::guard::current() }, their_thread);
482             let try_result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
483                 crate::sys_common::backtrace::__rust_begin_short_backtrace(f)
484             }));
485             // SAFETY: `their_packet` as been built just above and moved by the
486             // closure (it is an Arc<...>) and `my_packet` will be stored in the
487             // same `JoinInner` as this closure meaning the mutation will be
488             // safe (not modify it and affect a value far away).
489             unsafe { *their_packet.get() = Some(try_result) };
490         };
491
492         Ok(JoinHandle(JoinInner {
493             // SAFETY:
494             //
495             // `imp::Thread::new` takes a closure with a `'static` lifetime, since it's passed
496             // through FFI or otherwise used with low-level threading primitives that have no
497             // notion of or way to enforce lifetimes.
498             //
499             // As mentioned in the `Safety` section of this function's documentation, the caller of
500             // this function needs to guarantee that the passed-in lifetime is sufficiently long
501             // for the lifetime of the thread.
502             //
503             // Similarly, the `sys` implementation must guarantee that no references to the closure
504             // exist after the thread has terminated, which is signaled by `Thread::join`
505             // returning.
506             native: unsafe {
507                 Some(imp::Thread::new(
508                     stack_size,
509                     mem::transmute::<Box<dyn FnOnce() + 'a>, Box<dyn FnOnce() + 'static>>(
510                         Box::new(main),
511                     ),
512                 )?)
513             },
514             thread: my_thread,
515             packet: Packet(my_packet),
516         }))
517     }
518 }
519
520 ////////////////////////////////////////////////////////////////////////////////
521 // Free functions
522 ////////////////////////////////////////////////////////////////////////////////
523
524 /// Spawns a new thread, returning a [`JoinHandle`] for it.
525 ///
526 /// The join handle provides a [`join`] method that can be used to join the spawned
527 /// thread. If the spawned thread panics, [`join`] will return an [`Err`] containing
528 /// the argument given to [`panic!`].
529 ///
530 /// If the join handle is dropped, the spawned thread will implicitly be *detached*.
531 /// In this case, the spawned thread may no longer be joined.
532 /// (It is the responsibility of the program to either eventually join threads it
533 /// creates or detach them; otherwise, a resource leak will result.)
534 ///
535 /// This call will create a thread using default parameters of [`Builder`], if you
536 /// want to specify the stack size or the name of the thread, use this API
537 /// instead.
538 ///
539 /// As you can see in the signature of `spawn` there are two constraints on
540 /// both the closure given to `spawn` and its return value, let's explain them:
541 ///
542 /// - The `'static` constraint means that the closure and its return value
543 ///   must have a lifetime of the whole program execution. The reason for this
544 ///   is that threads can outlive the lifetime they have been created in.
545 ///
546 ///   Indeed if the thread, and by extension its return value, can outlive their
547 ///   caller, we need to make sure that they will be valid afterwards, and since
548 ///   we *can't* know when it will return we need to have them valid as long as
549 ///   possible, that is until the end of the program, hence the `'static`
550 ///   lifetime.
551 /// - The [`Send`] constraint is because the closure will need to be passed
552 ///   *by value* from the thread where it is spawned to the new thread. Its
553 ///   return value will need to be passed from the new thread to the thread
554 ///   where it is `join`ed.
555 ///   As a reminder, the [`Send`] marker trait expresses that it is safe to be
556 ///   passed from thread to thread. [`Sync`] expresses that it is safe to have a
557 ///   reference be passed from thread to thread.
558 ///
559 /// # Panics
560 ///
561 /// Panics if the OS fails to create a thread; use [`Builder::spawn`]
562 /// to recover from such errors.
563 ///
564 /// # Examples
565 ///
566 /// Creating a thread.
567 ///
568 /// ```
569 /// use std::thread;
570 ///
571 /// let handler = thread::spawn(|| {
572 ///     // thread code
573 /// });
574 ///
575 /// handler.join().unwrap();
576 /// ```
577 ///
578 /// As mentioned in the module documentation, threads are usually made to
579 /// communicate using [`channels`], here is how it usually looks.
580 ///
581 /// This example also shows how to use `move`, in order to give ownership
582 /// of values to a thread.
583 ///
584 /// ```
585 /// use std::thread;
586 /// use std::sync::mpsc::channel;
587 ///
588 /// let (tx, rx) = channel();
589 ///
590 /// let sender = thread::spawn(move || {
591 ///     tx.send("Hello, thread".to_owned())
592 ///         .expect("Unable to send on channel");
593 /// });
594 ///
595 /// let receiver = thread::spawn(move || {
596 ///     let value = rx.recv().expect("Unable to receive from channel");
597 ///     println!("{}", value);
598 /// });
599 ///
600 /// sender.join().expect("The sender thread has panicked");
601 /// receiver.join().expect("The receiver thread has panicked");
602 /// ```
603 ///
604 /// A thread can also return a value through its [`JoinHandle`], you can use
605 /// this to make asynchronous computations (futures might be more appropriate
606 /// though).
607 ///
608 /// ```
609 /// use std::thread;
610 ///
611 /// let computation = thread::spawn(|| {
612 ///     // Some expensive computation.
613 ///     42
614 /// });
615 ///
616 /// let result = computation.join().unwrap();
617 /// println!("{}", result);
618 /// ```
619 ///
620 /// [`channels`]: crate::sync::mpsc
621 /// [`join`]: JoinHandle::join
622 /// [`Err`]: crate::result::Result::Err
623 #[stable(feature = "rust1", since = "1.0.0")]
624 pub fn spawn<F, T>(f: F) -> JoinHandle<T>
625 where
626     F: FnOnce() -> T,
627     F: Send + 'static,
628     T: Send + 'static,
629 {
630     Builder::new().spawn(f).expect("failed to spawn thread")
631 }
632
633 /// Gets a handle to the thread that invokes it.
634 ///
635 /// # Examples
636 ///
637 /// Getting a handle to the current thread with `thread::current()`:
638 ///
639 /// ```
640 /// use std::thread;
641 ///
642 /// let handler = thread::Builder::new()
643 ///     .name("named thread".into())
644 ///     .spawn(|| {
645 ///         let handle = thread::current();
646 ///         assert_eq!(handle.name(), Some("named thread"));
647 ///     })
648 ///     .unwrap();
649 ///
650 /// handler.join().unwrap();
651 /// ```
652 #[stable(feature = "rust1", since = "1.0.0")]
653 pub fn current() -> Thread {
654     thread_info::current_thread().expect(
655         "use of std::thread::current() is not possible \
656          after the thread's local data has been destroyed",
657     )
658 }
659
660 /// Cooperatively gives up a timeslice to the OS scheduler.
661 ///
662 /// This calls the underlying OS scheduler's yield primitive, signaling
663 /// that the calling thread is willing to give up its remaining timeslice
664 /// so that the OS may schedule other threads on the CPU.
665 ///
666 /// A drawback of yielding in a loop is that if the OS does not have any
667 /// other ready threads to run on the current CPU, the thread will effectively
668 /// busy-wait, which wastes CPU time and energy.
669 ///
670 /// Therefore, when waiting for events of interest, a programmer's first
671 /// choice should be to use synchronization devices such as [`channel`]s,
672 /// [`Condvar`]s, [`Mutex`]es or [`join`] since these primitives are
673 /// implemented in a blocking manner, giving up the CPU until the event
674 /// of interest has occurred which avoids repeated yielding.
675 ///
676 /// `yield_now` should thus be used only rarely, mostly in situations where
677 /// repeated polling is required because there is no other suitable way to
678 /// learn when an event of interest has occurred.
679 ///
680 /// # Examples
681 ///
682 /// ```
683 /// use std::thread;
684 ///
685 /// thread::yield_now();
686 /// ```
687 ///
688 /// [`channel`]: crate::sync::mpsc
689 /// [`join`]: JoinHandle::join
690 /// [`Condvar`]: crate::sync::Condvar
691 /// [`Mutex`]: crate::sync::Mutex
692 #[stable(feature = "rust1", since = "1.0.0")]
693 pub fn yield_now() {
694     imp::Thread::yield_now()
695 }
696
697 /// Determines whether the current thread is unwinding because of panic.
698 ///
699 /// A common use of this feature is to poison shared resources when writing
700 /// unsafe code, by checking `panicking` when the `drop` is called.
701 ///
702 /// This is usually not needed when writing safe code, as [`Mutex`es][Mutex]
703 /// already poison themselves when a thread panics while holding the lock.
704 ///
705 /// This can also be used in multithreaded applications, in order to send a
706 /// message to other threads warning that a thread has panicked (e.g., for
707 /// monitoring purposes).
708 ///
709 /// # Examples
710 ///
711 /// ```should_panic
712 /// use std::thread;
713 ///
714 /// struct SomeStruct;
715 ///
716 /// impl Drop for SomeStruct {
717 ///     fn drop(&mut self) {
718 ///         if thread::panicking() {
719 ///             println!("dropped while unwinding");
720 ///         } else {
721 ///             println!("dropped while not unwinding");
722 ///         }
723 ///     }
724 /// }
725 ///
726 /// {
727 ///     print!("a: ");
728 ///     let a = SomeStruct;
729 /// }
730 ///
731 /// {
732 ///     print!("b: ");
733 ///     let b = SomeStruct;
734 ///     panic!()
735 /// }
736 /// ```
737 ///
738 /// [Mutex]: crate::sync::Mutex
739 #[inline]
740 #[stable(feature = "rust1", since = "1.0.0")]
741 pub fn panicking() -> bool {
742     panicking::panicking()
743 }
744
745 /// Puts the current thread to sleep for at least the specified amount of time.
746 ///
747 /// The thread may sleep longer than the duration specified due to scheduling
748 /// specifics or platform-dependent functionality. It will never sleep less.
749 ///
750 /// This function is blocking, and should not be used in `async` functions.
751 ///
752 /// # Platform-specific behavior
753 ///
754 /// On Unix platforms, the underlying syscall may be interrupted by a
755 /// spurious wakeup or signal handler. To ensure the sleep occurs for at least
756 /// the specified duration, this function may invoke that system call multiple
757 /// times.
758 ///
759 /// # Examples
760 ///
761 /// ```no_run
762 /// use std::thread;
763 ///
764 /// // Let's sleep for 2 seconds:
765 /// thread::sleep_ms(2000);
766 /// ```
767 #[stable(feature = "rust1", since = "1.0.0")]
768 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::sleep`")]
769 pub fn sleep_ms(ms: u32) {
770     sleep(Duration::from_millis(ms as u64))
771 }
772
773 /// Puts the current thread to sleep for at least the specified amount of time.
774 ///
775 /// The thread may sleep longer than the duration specified due to scheduling
776 /// specifics or platform-dependent functionality. It will never sleep less.
777 ///
778 /// This function is blocking, and should not be used in `async` functions.
779 ///
780 /// # Platform-specific behavior
781 ///
782 /// On Unix platforms, the underlying syscall may be interrupted by a
783 /// spurious wakeup or signal handler. To ensure the sleep occurs for at least
784 /// the specified duration, this function may invoke that system call multiple
785 /// times.
786 /// Platforms which do not support nanosecond precision for sleeping will
787 /// have `dur` rounded up to the nearest granularity of time they can sleep for.
788 ///
789 /// Currently, specifying a zero duration on Unix platforms returns immediately
790 /// without invoking the underlying [`nanosleep`] syscall, whereas on Windows
791 /// platforms the underlying [`Sleep`] syscall is always invoked.
792 /// If the intention is to yield the current time-slice you may want to use
793 /// [`yield_now`] instead.
794 ///
795 /// [`nanosleep`]: https://linux.die.net/man/2/nanosleep
796 /// [`Sleep`]: https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-sleep
797 ///
798 /// # Examples
799 ///
800 /// ```no_run
801 /// use std::{thread, time};
802 ///
803 /// let ten_millis = time::Duration::from_millis(10);
804 /// let now = time::Instant::now();
805 ///
806 /// thread::sleep(ten_millis);
807 ///
808 /// assert!(now.elapsed() >= ten_millis);
809 /// ```
810 #[stable(feature = "thread_sleep", since = "1.4.0")]
811 pub fn sleep(dur: Duration) {
812     imp::Thread::sleep(dur)
813 }
814
815 /// Blocks unless or until the current thread's token is made available.
816 ///
817 /// A call to `park` does not guarantee that the thread will remain parked
818 /// forever, and callers should be prepared for this possibility.
819 ///
820 /// # park and unpark
821 ///
822 /// Every thread is equipped with some basic low-level blocking support, via the
823 /// [`thread::park`][`park`] function and [`thread::Thread::unpark`][`unpark`]
824 /// method. [`park`] blocks the current thread, which can then be resumed from
825 /// another thread by calling the [`unpark`] method on the blocked thread's
826 /// handle.
827 ///
828 /// Conceptually, each [`Thread`] handle has an associated token, which is
829 /// initially not present:
830 ///
831 /// * The [`thread::park`][`park`] function blocks the current thread unless or
832 ///   until the token is available for its thread handle, at which point it
833 ///   atomically consumes the token. It may also return *spuriously*, without
834 ///   consuming the token. [`thread::park_timeout`] does the same, but allows
835 ///   specifying a maximum time to block the thread for.
836 ///
837 /// * The [`unpark`] method on a [`Thread`] atomically makes the token available
838 ///   if it wasn't already. Because the token is initially absent, [`unpark`]
839 ///   followed by [`park`] will result in the second call returning immediately.
840 ///
841 /// In other words, each [`Thread`] acts a bit like a spinlock that can be
842 /// locked and unlocked using `park` and `unpark`.
843 ///
844 /// Notice that being unblocked does not imply any synchronization with someone
845 /// that unparked this thread, it could also be spurious.
846 /// For example, it would be a valid, but inefficient, implementation to make both [`park`] and
847 /// [`unpark`] return immediately without doing anything.
848 ///
849 /// The API is typically used by acquiring a handle to the current thread,
850 /// placing that handle in a shared data structure so that other threads can
851 /// find it, and then `park`ing in a loop. When some desired condition is met, another
852 /// thread calls [`unpark`] on the handle.
853 ///
854 /// The motivation for this design is twofold:
855 ///
856 /// * It avoids the need to allocate mutexes and condvars when building new
857 ///   synchronization primitives; the threads already provide basic
858 ///   blocking/signaling.
859 ///
860 /// * It can be implemented very efficiently on many platforms.
861 ///
862 /// # Examples
863 ///
864 /// ```
865 /// use std::thread;
866 /// use std::sync::{Arc, atomic::{Ordering, AtomicBool}};
867 /// use std::time::Duration;
868 ///
869 /// let flag = Arc::new(AtomicBool::new(false));
870 /// let flag2 = Arc::clone(&flag);
871 ///
872 /// let parked_thread = thread::spawn(move || {
873 ///     // We want to wait until the flag is set. We *could* just spin, but using
874 ///     // park/unpark is more efficient.
875 ///     while !flag2.load(Ordering::Acquire) {
876 ///         println!("Parking thread");
877 ///         thread::park();
878 ///         // We *could* get here spuriously, i.e., way before the 10ms below are over!
879 ///         // But that is no problem, we are in a loop until the flag is set anyway.
880 ///         println!("Thread unparked");
881 ///     }
882 ///     println!("Flag received");
883 /// });
884 ///
885 /// // Let some time pass for the thread to be spawned.
886 /// thread::sleep(Duration::from_millis(10));
887 ///
888 /// // Set the flag, and let the thread wake up.
889 /// // There is no race condition here, if `unpark`
890 /// // happens first, `park` will return immediately.
891 /// // Hence there is no risk of a deadlock.
892 /// flag.store(true, Ordering::Release);
893 /// println!("Unpark the thread");
894 /// parked_thread.thread().unpark();
895 ///
896 /// parked_thread.join().unwrap();
897 /// ```
898 ///
899 /// [`unpark`]: Thread::unpark
900 /// [`thread::park_timeout`]: park_timeout
901 #[stable(feature = "rust1", since = "1.0.0")]
902 pub fn park() {
903     // SAFETY: park_timeout is called on the parker owned by this thread.
904     unsafe {
905         current().inner.parker.park();
906     }
907 }
908
909 /// Use [`park_timeout`].
910 ///
911 /// Blocks unless or until the current thread's token is made available or
912 /// the specified duration has been reached (may wake spuriously).
913 ///
914 /// The semantics of this function are equivalent to [`park`] except
915 /// that the thread will be blocked for roughly no longer than `dur`. This
916 /// method should not be used for precise timing due to anomalies such as
917 /// preemption or platform differences that might not cause the maximum
918 /// amount of time waited to be precisely `ms` long.
919 ///
920 /// See the [park documentation][`park`] for more detail.
921 #[stable(feature = "rust1", since = "1.0.0")]
922 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::park_timeout`")]
923 pub fn park_timeout_ms(ms: u32) {
924     park_timeout(Duration::from_millis(ms as u64))
925 }
926
927 /// Blocks unless or until the current thread's token is made available or
928 /// the specified duration has been reached (may wake spuriously).
929 ///
930 /// The semantics of this function are equivalent to [`park`][park] except
931 /// that the thread will be blocked for roughly no longer than `dur`. This
932 /// method should not be used for precise timing due to anomalies such as
933 /// preemption or platform differences that might not cause the maximum
934 /// amount of time waited to be precisely `dur` long.
935 ///
936 /// See the [park documentation][park] for more details.
937 ///
938 /// # Platform-specific behavior
939 ///
940 /// Platforms which do not support nanosecond precision for sleeping will have
941 /// `dur` rounded up to the nearest granularity of time they can sleep for.
942 ///
943 /// # Examples
944 ///
945 /// Waiting for the complete expiration of the timeout:
946 ///
947 /// ```rust,no_run
948 /// use std::thread::park_timeout;
949 /// use std::time::{Instant, Duration};
950 ///
951 /// let timeout = Duration::from_secs(2);
952 /// let beginning_park = Instant::now();
953 ///
954 /// let mut timeout_remaining = timeout;
955 /// loop {
956 ///     park_timeout(timeout_remaining);
957 ///     let elapsed = beginning_park.elapsed();
958 ///     if elapsed >= timeout {
959 ///         break;
960 ///     }
961 ///     println!("restarting park_timeout after {:?}", elapsed);
962 ///     timeout_remaining = timeout - elapsed;
963 /// }
964 /// ```
965 #[stable(feature = "park_timeout", since = "1.4.0")]
966 pub fn park_timeout(dur: Duration) {
967     // SAFETY: park_timeout is called on the parker owned by this thread.
968     unsafe {
969         current().inner.parker.park_timeout(dur);
970     }
971 }
972
973 ////////////////////////////////////////////////////////////////////////////////
974 // ThreadId
975 ////////////////////////////////////////////////////////////////////////////////
976
977 /// A unique identifier for a running thread.
978 ///
979 /// A `ThreadId` is an opaque object that has a unique value for each thread
980 /// that creates one. `ThreadId`s are not guaranteed to correspond to a thread's
981 /// system-designated identifier. A `ThreadId` can be retrieved from the [`id`]
982 /// method on a [`Thread`].
983 ///
984 /// # Examples
985 ///
986 /// ```
987 /// use std::thread;
988 ///
989 /// let other_thread = thread::spawn(|| {
990 ///     thread::current().id()
991 /// });
992 ///
993 /// let other_thread_id = other_thread.join().unwrap();
994 /// assert!(thread::current().id() != other_thread_id);
995 /// ```
996 ///
997 /// [`id`]: Thread::id
998 #[stable(feature = "thread_id", since = "1.19.0")]
999 #[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
1000 pub struct ThreadId(NonZeroU64);
1001
1002 impl ThreadId {
1003     // Generate a new unique thread ID.
1004     fn new() -> ThreadId {
1005         // It is UB to attempt to acquire this mutex reentrantly!
1006         static GUARD: mutex::StaticMutex = mutex::StaticMutex::new();
1007         static mut COUNTER: u64 = 1;
1008
1009         unsafe {
1010             let guard = GUARD.lock();
1011
1012             // If we somehow use up all our bits, panic so that we're not
1013             // covering up subtle bugs of IDs being reused.
1014             if COUNTER == u64::MAX {
1015                 drop(guard); // in case the panic handler ends up calling `ThreadId::new()`, avoid reentrant lock acquire.
1016                 panic!("failed to generate unique thread ID: bitspace exhausted");
1017             }
1018
1019             let id = COUNTER;
1020             COUNTER += 1;
1021
1022             ThreadId(NonZeroU64::new(id).unwrap())
1023         }
1024     }
1025
1026     /// This returns a numeric identifier for the thread identified by this
1027     /// `ThreadId`.
1028     ///
1029     /// As noted in the documentation for the type itself, it is essentially an
1030     /// opaque ID, but is guaranteed to be unique for each thread. The returned
1031     /// value is entirely opaque -- only equality testing is stable. Note that
1032     /// it is not guaranteed which values new threads will return, and this may
1033     /// change across Rust versions.
1034     #[must_use]
1035     #[unstable(feature = "thread_id_value", issue = "67939")]
1036     pub fn as_u64(&self) -> NonZeroU64 {
1037         self.0
1038     }
1039 }
1040
1041 ////////////////////////////////////////////////////////////////////////////////
1042 // Thread
1043 ////////////////////////////////////////////////////////////////////////////////
1044
1045 /// The internal representation of a `Thread` handle
1046 struct Inner {
1047     name: Option<CString>, // Guaranteed to be UTF-8
1048     id: ThreadId,
1049     parker: Parker,
1050 }
1051
1052 #[derive(Clone)]
1053 #[stable(feature = "rust1", since = "1.0.0")]
1054 /// A handle to a thread.
1055 ///
1056 /// Threads are represented via the `Thread` type, which you can get in one of
1057 /// two ways:
1058 ///
1059 /// * By spawning a new thread, e.g., using the [`thread::spawn`][`spawn`]
1060 ///   function, and calling [`thread`][`JoinHandle::thread`] on the
1061 ///   [`JoinHandle`].
1062 /// * By requesting the current thread, using the [`thread::current`] function.
1063 ///
1064 /// The [`thread::current`] function is available even for threads not spawned
1065 /// by the APIs of this module.
1066 ///
1067 /// There is usually no need to create a `Thread` struct yourself, one
1068 /// should instead use a function like `spawn` to create new threads, see the
1069 /// docs of [`Builder`] and [`spawn`] for more details.
1070 ///
1071 /// [`thread::current`]: current
1072 pub struct Thread {
1073     inner: Arc<Inner>,
1074 }
1075
1076 impl Thread {
1077     // Used only internally to construct a thread object without spawning
1078     // Panics if the name contains nuls.
1079     pub(crate) fn new(name: Option<CString>) -> Thread {
1080         Thread { inner: Arc::new(Inner { name, id: ThreadId::new(), parker: Parker::new() }) }
1081     }
1082
1083     /// Atomically makes the handle's token available if it is not already.
1084     ///
1085     /// Every thread is equipped with some basic low-level blocking support, via
1086     /// the [`park`][park] function and the `unpark()` method. These can be
1087     /// used as a more CPU-efficient implementation of a spinlock.
1088     ///
1089     /// See the [park documentation][park] for more details.
1090     ///
1091     /// # Examples
1092     ///
1093     /// ```
1094     /// use std::thread;
1095     /// use std::time::Duration;
1096     ///
1097     /// let parked_thread = thread::Builder::new()
1098     ///     .spawn(|| {
1099     ///         println!("Parking thread");
1100     ///         thread::park();
1101     ///         println!("Thread unparked");
1102     ///     })
1103     ///     .unwrap();
1104     ///
1105     /// // Let some time pass for the thread to be spawned.
1106     /// thread::sleep(Duration::from_millis(10));
1107     ///
1108     /// println!("Unpark the thread");
1109     /// parked_thread.thread().unpark();
1110     ///
1111     /// parked_thread.join().unwrap();
1112     /// ```
1113     #[stable(feature = "rust1", since = "1.0.0")]
1114     #[inline]
1115     pub fn unpark(&self) {
1116         self.inner.parker.unpark();
1117     }
1118
1119     /// Gets the thread's unique identifier.
1120     ///
1121     /// # Examples
1122     ///
1123     /// ```
1124     /// use std::thread;
1125     ///
1126     /// let other_thread = thread::spawn(|| {
1127     ///     thread::current().id()
1128     /// });
1129     ///
1130     /// let other_thread_id = other_thread.join().unwrap();
1131     /// assert!(thread::current().id() != other_thread_id);
1132     /// ```
1133     #[stable(feature = "thread_id", since = "1.19.0")]
1134     pub fn id(&self) -> ThreadId {
1135         self.inner.id
1136     }
1137
1138     /// Gets the thread's name.
1139     ///
1140     /// For more information about named threads, see
1141     /// [this module-level documentation][naming-threads].
1142     ///
1143     /// # Examples
1144     ///
1145     /// Threads by default have no name specified:
1146     ///
1147     /// ```
1148     /// use std::thread;
1149     ///
1150     /// let builder = thread::Builder::new();
1151     ///
1152     /// let handler = builder.spawn(|| {
1153     ///     assert!(thread::current().name().is_none());
1154     /// }).unwrap();
1155     ///
1156     /// handler.join().unwrap();
1157     /// ```
1158     ///
1159     /// Thread with a specified name:
1160     ///
1161     /// ```
1162     /// use std::thread;
1163     ///
1164     /// let builder = thread::Builder::new()
1165     ///     .name("foo".into());
1166     ///
1167     /// let handler = builder.spawn(|| {
1168     ///     assert_eq!(thread::current().name(), Some("foo"))
1169     /// }).unwrap();
1170     ///
1171     /// handler.join().unwrap();
1172     /// ```
1173     ///
1174     /// [naming-threads]: ./index.html#naming-threads
1175     #[stable(feature = "rust1", since = "1.0.0")]
1176     pub fn name(&self) -> Option<&str> {
1177         self.cname().map(|s| unsafe { str::from_utf8_unchecked(s.to_bytes()) })
1178     }
1179
1180     fn cname(&self) -> Option<&CStr> {
1181         self.inner.name.as_deref()
1182     }
1183 }
1184
1185 #[stable(feature = "rust1", since = "1.0.0")]
1186 impl fmt::Debug for Thread {
1187     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1188         f.debug_struct("Thread")
1189             .field("id", &self.id())
1190             .field("name", &self.name())
1191             .finish_non_exhaustive()
1192     }
1193 }
1194
1195 ////////////////////////////////////////////////////////////////////////////////
1196 // JoinHandle
1197 ////////////////////////////////////////////////////////////////////////////////
1198
1199 /// A specialized [`Result`] type for threads.
1200 ///
1201 /// Indicates the manner in which a thread exited.
1202 ///
1203 /// The value contained in the `Result::Err` variant
1204 /// is the value the thread panicked with;
1205 /// that is, the argument the `panic!` macro was called with.
1206 /// Unlike with normal errors, this value doesn't implement
1207 /// the [`Error`](crate::error::Error) trait.
1208 ///
1209 /// Thus, a sensible way to handle a thread panic is to either:
1210 ///
1211 /// 1. propagate the panic with [`std::panic::resume_unwind`]
1212 /// 2. or in case the thread is intended to be a subsystem boundary
1213 /// that is supposed to isolate system-level failures,
1214 /// match on the `Err` variant and handle the panic in an appropriate way
1215 ///
1216 /// A thread that completes without panicking is considered to exit successfully.
1217 ///
1218 /// # Examples
1219 ///
1220 /// Matching on the result of a joined thread:
1221 ///
1222 /// ```no_run
1223 /// use std::{fs, thread, panic};
1224 ///
1225 /// fn copy_in_thread() -> thread::Result<()> {
1226 ///     thread::spawn(|| {
1227 ///         fs::copy("foo.txt", "bar.txt").unwrap();
1228 ///     }).join()
1229 /// }
1230 ///
1231 /// fn main() {
1232 ///     match copy_in_thread() {
1233 ///         Ok(_) => println!("copy succeeded"),
1234 ///         Err(e) => panic::resume_unwind(e),
1235 ///     }
1236 /// }
1237 /// ```
1238 ///
1239 /// [`Result`]: crate::result::Result
1240 /// [`std::panic::resume_unwind`]: crate::panic::resume_unwind
1241 #[stable(feature = "rust1", since = "1.0.0")]
1242 pub type Result<T> = crate::result::Result<T, Box<dyn Any + Send + 'static>>;
1243
1244 // This packet is used to communicate the return value between the spawned thread
1245 // and the rest of the program. Memory is shared through the `Arc` within and there's
1246 // no need for a mutex here because synchronization happens with `join()` (the
1247 // caller will never read this packet until the thread has exited).
1248 //
1249 // This packet itself is then stored into a `JoinInner` which in turns is placed
1250 // in `JoinHandle` and `JoinGuard`. Due to the usage of `UnsafeCell` we need to
1251 // manually worry about impls like Send and Sync. The type `T` should
1252 // already always be Send (otherwise the thread could not have been created) and
1253 // this type is inherently Sync because no methods take &self. Regardless,
1254 // however, we add inheriting impls for Send/Sync to this type to ensure it's
1255 // Send/Sync and that future modifications will still appropriately classify it.
1256 struct Packet<T>(Arc<UnsafeCell<Option<Result<T>>>>);
1257
1258 unsafe impl<T: Send> Send for Packet<T> {}
1259 unsafe impl<T: Sync> Sync for Packet<T> {}
1260
1261 /// Inner representation for JoinHandle
1262 struct JoinInner<T> {
1263     native: Option<imp::Thread>,
1264     thread: Thread,
1265     packet: Packet<T>,
1266 }
1267
1268 impl<T> JoinInner<T> {
1269     fn join(&mut self) -> Result<T> {
1270         self.native.take().unwrap().join();
1271         unsafe { (*self.packet.0.get()).take().unwrap() }
1272     }
1273 }
1274
1275 /// An owned permission to join on a thread (block on its termination).
1276 ///
1277 /// A `JoinHandle` *detaches* the associated thread when it is dropped, which
1278 /// means that there is no longer any handle to thread and no way to `join`
1279 /// on it.
1280 ///
1281 /// Due to platform restrictions, it is not possible to [`Clone`] this
1282 /// handle: the ability to join a thread is a uniquely-owned permission.
1283 ///
1284 /// This `struct` is created by the [`thread::spawn`] function and the
1285 /// [`thread::Builder::spawn`] method.
1286 ///
1287 /// # Examples
1288 ///
1289 /// Creation from [`thread::spawn`]:
1290 ///
1291 /// ```
1292 /// use std::thread;
1293 ///
1294 /// let join_handle: thread::JoinHandle<_> = thread::spawn(|| {
1295 ///     // some work here
1296 /// });
1297 /// ```
1298 ///
1299 /// Creation from [`thread::Builder::spawn`]:
1300 ///
1301 /// ```
1302 /// use std::thread;
1303 ///
1304 /// let builder = thread::Builder::new();
1305 ///
1306 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1307 ///     // some work here
1308 /// }).unwrap();
1309 /// ```
1310 ///
1311 /// A thread being detached and outliving the thread that spawned it:
1312 ///
1313 /// ```no_run
1314 /// use std::thread;
1315 /// use std::time::Duration;
1316 ///
1317 /// let original_thread = thread::spawn(|| {
1318 ///     let _detached_thread = thread::spawn(|| {
1319 ///         // Here we sleep to make sure that the first thread returns before.
1320 ///         thread::sleep(Duration::from_millis(10));
1321 ///         // This will be called, even though the JoinHandle is dropped.
1322 ///         println!("♫ Still alive ♫");
1323 ///     });
1324 /// });
1325 ///
1326 /// original_thread.join().expect("The thread being joined has panicked");
1327 /// println!("Original thread is joined.");
1328 ///
1329 /// // We make sure that the new thread has time to run, before the main
1330 /// // thread returns.
1331 ///
1332 /// thread::sleep(Duration::from_millis(1000));
1333 /// ```
1334 ///
1335 /// [`thread::Builder::spawn`]: Builder::spawn
1336 /// [`thread::spawn`]: spawn
1337 #[stable(feature = "rust1", since = "1.0.0")]
1338 pub struct JoinHandle<T>(JoinInner<T>);
1339
1340 #[stable(feature = "joinhandle_impl_send_sync", since = "1.29.0")]
1341 unsafe impl<T> Send for JoinHandle<T> {}
1342 #[stable(feature = "joinhandle_impl_send_sync", since = "1.29.0")]
1343 unsafe impl<T> Sync for JoinHandle<T> {}
1344
1345 impl<T> JoinHandle<T> {
1346     /// Extracts a handle to the underlying thread.
1347     ///
1348     /// # Examples
1349     ///
1350     /// ```
1351     /// use std::thread;
1352     ///
1353     /// let builder = thread::Builder::new();
1354     ///
1355     /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1356     ///     // some work here
1357     /// }).unwrap();
1358     ///
1359     /// let thread = join_handle.thread();
1360     /// println!("thread id: {:?}", thread.id());
1361     /// ```
1362     #[stable(feature = "rust1", since = "1.0.0")]
1363     pub fn thread(&self) -> &Thread {
1364         &self.0.thread
1365     }
1366
1367     /// Waits for the associated thread to finish.
1368     ///
1369     /// This function will return immediately if the associated thread has already finished.
1370     ///
1371     /// In terms of [atomic memory orderings],  the completion of the associated
1372     /// thread synchronizes with this function returning. In other words, all
1373     /// operations performed by that thread [happen
1374     /// before](https://doc.rust-lang.org/nomicon/atomics.html#data-accesses) all
1375     /// operations that happen after `join` returns.
1376     ///
1377     /// If the associated thread panics, [`Err`] is returned with the parameter given
1378     /// to [`panic!`].
1379     ///
1380     /// [`Err`]: crate::result::Result::Err
1381     /// [atomic memory orderings]: crate::sync::atomic
1382     ///
1383     /// # Panics
1384     ///
1385     /// This function may panic on some platforms if a thread attempts to join
1386     /// itself or otherwise may create a deadlock with joining threads.
1387     ///
1388     /// # Examples
1389     ///
1390     /// ```
1391     /// use std::thread;
1392     ///
1393     /// let builder = thread::Builder::new();
1394     ///
1395     /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1396     ///     // some work here
1397     /// }).unwrap();
1398     /// join_handle.join().expect("Couldn't join on the associated thread");
1399     /// ```
1400     #[stable(feature = "rust1", since = "1.0.0")]
1401     pub fn join(mut self) -> Result<T> {
1402         self.0.join()
1403     }
1404 }
1405
1406 impl<T> AsInner<imp::Thread> for JoinHandle<T> {
1407     fn as_inner(&self) -> &imp::Thread {
1408         self.0.native.as_ref().unwrap()
1409     }
1410 }
1411
1412 impl<T> IntoInner<imp::Thread> for JoinHandle<T> {
1413     fn into_inner(self) -> imp::Thread {
1414         self.0.native.unwrap()
1415     }
1416 }
1417
1418 #[stable(feature = "std_debug", since = "1.16.0")]
1419 impl<T> fmt::Debug for JoinHandle<T> {
1420     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1421         f.debug_struct("JoinHandle").finish_non_exhaustive()
1422     }
1423 }
1424
1425 fn _assert_sync_and_send() {
1426     fn _assert_both<T: Send + Sync>() {}
1427     _assert_both::<JoinHandle<()>>();
1428     _assert_both::<Thread>();
1429 }
1430
1431 /// Returns an estimate of the default amount of parallelism a program should use.
1432 ///
1433 /// Parallelism is a resource. A given machine provides a certain capacity for
1434 /// parallelism, i.e., a bound on the number of computations it can perform
1435 /// simultaneously. This number often corresponds to the amount of CPUs or
1436 /// computer has, but it may diverge in various cases.
1437 ///
1438 /// Host environments such as VMs or container orchestrators may want to
1439 /// restrict the amount of parallelism made available to programs in them. This
1440 /// is often done to limit the potential impact of (unintentionally)
1441 /// resource-intensive programs on other programs running on the same machine.
1442 ///
1443 /// # Limitations
1444 ///
1445 /// The purpose of this API is to provide an easy and portable way to query
1446 /// the default amount of parallelism the program should use. Among other things it
1447 /// does not expose information on NUMA regions, does not account for
1448 /// differences in (co)processor capabilities, and will not modify the program's
1449 /// global state in order to more accurately query the amount of available
1450 /// parallelism.
1451 ///
1452 /// The value returned by this function should be considered a simplified
1453 /// approximation of the actual amount of parallelism available at any given
1454 /// time. To get a more detailed or precise overview of the amount of
1455 /// parallelism available to the program, you may wish to use
1456 /// platform-specific APIs as well. The following platform limitations currently
1457 /// apply to `available_parallelism`:
1458 ///
1459 /// On Windows:
1460 /// - It may undercount the amount of parallelism available on systems with more
1461 ///   than 64 logical CPUs. However, programs typically need specific support to
1462 ///   take advantage of more than 64 logical CPUs, and in the absence of such
1463 ///   support, the number returned by this function accurately reflects the
1464 ///   number of logical CPUs the program can use by default.
1465 /// - It may overcount the amount of parallelism available on systems limited by
1466 ///   process-wide affinity masks, or job object limitations.
1467 ///
1468 /// On Linux:
1469 /// - It may overcount the amount of parallelism available when limited by a
1470 ///   process-wide affinity mask, or when affected by cgroup limits.
1471 ///
1472 /// On all targets:
1473 /// - It may overcount the amount of parallelism available when running in a VM
1474 /// with CPU usage limits (e.g. an overcommitted host).
1475 ///
1476 /// # Errors
1477 ///
1478 /// This function will, but is not limited to, return errors in the following
1479 /// cases:
1480 ///
1481 /// - If the amount of parallelism is not known for the target platform.
1482 /// - If the program lacks permission to query the amount of parallelism made
1483 ///   available to it.
1484 ///
1485 /// # Examples
1486 ///
1487 /// ```
1488 /// # #![allow(dead_code)]
1489 /// #![feature(available_parallelism)]
1490 /// use std::{io, thread};
1491 ///
1492 /// fn main() -> io::Result<()> {
1493 ///     let count = thread::available_parallelism()?.get();
1494 ///     assert!(count >= 1_usize);
1495 ///     Ok(())
1496 /// }
1497 /// ```
1498 #[doc(alias = "available_concurrency")] // Alias for a previous name we gave this API on unstable.
1499 #[doc(alias = "hardware_concurrency")] // Alias for C++ `std::thread::hardware_concurrency`.
1500 #[doc(alias = "num_cpus")] // Alias for a popular ecosystem crate which provides similar functionality.
1501 #[unstable(feature = "available_parallelism", issue = "74479")]
1502 pub fn available_parallelism() -> io::Result<NonZeroUsize> {
1503     imp::available_parallelism()
1504 }