]> git.lizzy.rs Git - rust.git/blob - library/std/src/thread/mod.rs
Rollup merge of #100559 - nnethercote:parser-simplifications, r=compiler-errors
[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 //! [`thread_local!`]: crate::thread_local
150
151 #![stable(feature = "rust1", since = "1.0.0")]
152 #![deny(unsafe_op_in_unsafe_fn)]
153
154 #[cfg(all(test, not(target_os = "emscripten")))]
155 mod tests;
156
157 use crate::any::Any;
158 use crate::cell::UnsafeCell;
159 use crate::ffi::{CStr, CString};
160 use crate::fmt;
161 use crate::io;
162 use crate::marker::PhantomData;
163 use crate::mem;
164 use crate::num::NonZeroU64;
165 use crate::num::NonZeroUsize;
166 use crate::panic;
167 use crate::panicking;
168 use crate::pin::Pin;
169 use crate::ptr::addr_of_mut;
170 use crate::str;
171 use crate::sync::Arc;
172 use crate::sys::thread as imp;
173 use crate::sys_common::thread;
174 use crate::sys_common::thread_info;
175 use crate::sys_common::thread_parker::Parker;
176 use crate::sys_common::{AsInner, IntoInner};
177 use crate::time::Duration;
178
179 ////////////////////////////////////////////////////////////////////////////////
180 // Thread-local storage
181 ////////////////////////////////////////////////////////////////////////////////
182
183 #[macro_use]
184 mod local;
185
186 #[stable(feature = "scoped_threads", since = "1.63.0")]
187 mod scoped;
188
189 #[stable(feature = "scoped_threads", since = "1.63.0")]
190 pub use scoped::{scope, Scope, ScopedJoinHandle};
191
192 #[stable(feature = "rust1", since = "1.0.0")]
193 pub use self::local::{AccessError, LocalKey};
194
195 // The types used by the thread_local! macro to access TLS keys. Note that there
196 // are two types, the "OS" type and the "fast" type. The OS thread local key
197 // type is accessed via platform-specific API calls and is slow, while the fast
198 // key type is accessed via code generated via LLVM, where TLS keys are set up
199 // by the elf linker. Note that the OS TLS type is always available: on macOS
200 // the standard library is compiled with support for older platform versions
201 // where fast TLS was not available; end-user code is compiled with fast TLS
202 // where available, but both are needed.
203
204 #[unstable(feature = "libstd_thread_internals", issue = "none")]
205 #[cfg(target_thread_local)]
206 #[doc(hidden)]
207 pub use self::local::fast::Key as __FastLocalKeyInner;
208 #[unstable(feature = "libstd_thread_internals", issue = "none")]
209 #[doc(hidden)]
210 pub use self::local::os::Key as __OsLocalKeyInner;
211 #[unstable(feature = "libstd_thread_internals", issue = "none")]
212 #[cfg(all(target_family = "wasm", not(target_feature = "atomics")))]
213 #[doc(hidden)]
214 pub use self::local::statik::Key as __StaticLocalKeyInner;
215
216 ////////////////////////////////////////////////////////////////////////////////
217 // Builder
218 ////////////////////////////////////////////////////////////////////////////////
219
220 /// Thread factory, which can be used in order to configure the properties of
221 /// a new thread.
222 ///
223 /// Methods can be chained on it in order to configure it.
224 ///
225 /// The two configurations available are:
226 ///
227 /// - [`name`]: specifies an [associated name for the thread][naming-threads]
228 /// - [`stack_size`]: specifies the [desired stack size for the thread][stack-size]
229 ///
230 /// The [`spawn`] method will take ownership of the builder and create an
231 /// [`io::Result`] to the thread handle with the given configuration.
232 ///
233 /// The [`thread::spawn`] free function uses a `Builder` with default
234 /// configuration and [`unwrap`]s its return value.
235 ///
236 /// You may want to use [`spawn`] instead of [`thread::spawn`], when you want
237 /// to recover from a failure to launch a thread, indeed the free function will
238 /// panic where the `Builder` method will return a [`io::Result`].
239 ///
240 /// # Examples
241 ///
242 /// ```
243 /// use std::thread;
244 ///
245 /// let builder = thread::Builder::new();
246 ///
247 /// let handler = builder.spawn(|| {
248 ///     // thread code
249 /// }).unwrap();
250 ///
251 /// handler.join().unwrap();
252 /// ```
253 ///
254 /// [`stack_size`]: Builder::stack_size
255 /// [`name`]: Builder::name
256 /// [`spawn`]: Builder::spawn
257 /// [`thread::spawn`]: spawn
258 /// [`io::Result`]: crate::io::Result
259 /// [`unwrap`]: crate::result::Result::unwrap
260 /// [naming-threads]: ./index.html#naming-threads
261 /// [stack-size]: ./index.html#stack-size
262 #[must_use = "must eventually spawn the thread"]
263 #[stable(feature = "rust1", since = "1.0.0")]
264 #[derive(Debug)]
265 pub struct Builder {
266     // A name for the thread-to-be, for identification in panic messages
267     name: Option<String>,
268     // The size of the stack for the spawned thread in bytes
269     stack_size: Option<usize>,
270 }
271
272 impl Builder {
273     /// Generates the base configuration for spawning a thread, from which
274     /// configuration methods can be chained.
275     ///
276     /// # Examples
277     ///
278     /// ```
279     /// use std::thread;
280     ///
281     /// let builder = thread::Builder::new()
282     ///                               .name("foo".into())
283     ///                               .stack_size(32 * 1024);
284     ///
285     /// let handler = builder.spawn(|| {
286     ///     // thread code
287     /// }).unwrap();
288     ///
289     /// handler.join().unwrap();
290     /// ```
291     #[stable(feature = "rust1", since = "1.0.0")]
292     pub fn new() -> Builder {
293         Builder { name: None, stack_size: None }
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 a 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 spawned 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     /// [`io::Result`]: crate::io::Result
366     ///
367     /// # Panics
368     ///
369     /// Panics if a thread name was set and it contained null bytes.
370     ///
371     /// # Examples
372     ///
373     /// ```
374     /// use std::thread;
375     ///
376     /// let builder = thread::Builder::new();
377     ///
378     /// let handler = builder.spawn(|| {
379     ///     // thread code
380     /// }).unwrap();
381     ///
382     /// handler.join().unwrap();
383     /// ```
384     #[stable(feature = "rust1", since = "1.0.0")]
385     pub fn spawn<F, T>(self, f: F) -> io::Result<JoinHandle<T>>
386     where
387         F: FnOnce() -> T,
388         F: Send + 'static,
389         T: Send + 'static,
390     {
391         unsafe { self.spawn_unchecked(f) }
392     }
393
394     /// Spawns a new thread without any lifetime restrictions by taking ownership
395     /// of the `Builder`, and returns an [`io::Result`] to its [`JoinHandle`].
396     ///
397     /// The spawned thread may outlive the caller (unless the caller thread
398     /// is the main thread; the whole process is terminated when the main
399     /// thread finishes). The join handle can be used to block on
400     /// termination of the spawned thread, including recovering its panics.
401     ///
402     /// This method is identical to [`thread::Builder::spawn`][`Builder::spawn`],
403     /// except for the relaxed lifetime bounds, which render it unsafe.
404     /// For a more complete documentation see [`thread::spawn`][`spawn`].
405     ///
406     /// # Errors
407     ///
408     /// Unlike the [`spawn`] free function, this method yields an
409     /// [`io::Result`] to capture any failure to create the thread at
410     /// the OS level.
411     ///
412     /// # Panics
413     ///
414     /// Panics if a thread name was set and it contained null bytes.
415     ///
416     /// # Safety
417     ///
418     /// The caller has to ensure that the spawned thread does not outlive any
419     /// references in the supplied thread closure and its return type.
420     /// This can be guaranteed in two ways:
421     ///
422     /// - ensure that [`join`][`JoinHandle::join`] is called before any referenced
423     /// data is dropped
424     /// - use only types with `'static` lifetime bounds, i.e., those with no or only
425     /// `'static` references (both [`thread::Builder::spawn`][`Builder::spawn`]
426     /// and [`thread::spawn`][`spawn`] enforce this property statically)
427     ///
428     /// # Examples
429     ///
430     /// ```
431     /// #![feature(thread_spawn_unchecked)]
432     /// use std::thread;
433     ///
434     /// let builder = thread::Builder::new();
435     ///
436     /// let x = 1;
437     /// let thread_x = &x;
438     ///
439     /// let handler = unsafe {
440     ///     builder.spawn_unchecked(move || {
441     ///         println!("x = {}", *thread_x);
442     ///     }).unwrap()
443     /// };
444     ///
445     /// // caller has to ensure `join()` is called, otherwise
446     /// // it is possible to access freed memory if `x` gets
447     /// // dropped before the thread closure is executed!
448     /// handler.join().unwrap();
449     /// ```
450     ///
451     /// [`io::Result`]: crate::io::Result
452     #[unstable(feature = "thread_spawn_unchecked", issue = "55132")]
453     pub unsafe fn spawn_unchecked<'a, F, T>(self, f: F) -> io::Result<JoinHandle<T>>
454     where
455         F: FnOnce() -> T,
456         F: Send + 'a,
457         T: Send + 'a,
458     {
459         Ok(JoinHandle(unsafe { self.spawn_unchecked_(f, None) }?))
460     }
461
462     unsafe fn spawn_unchecked_<'a, 'scope, F, T>(
463         self,
464         f: F,
465         scope_data: Option<Arc<scoped::ScopeData>>,
466     ) -> io::Result<JoinInner<'scope, T>>
467     where
468         F: FnOnce() -> T,
469         F: Send + 'a,
470         T: Send + 'a,
471         'scope: 'a,
472     {
473         let Builder { name, stack_size } = self;
474
475         let stack_size = stack_size.unwrap_or_else(thread::min_stack);
476
477         let my_thread = Thread::new(name.map(|name| {
478             CString::new(name).expect("thread name may not contain interior null bytes")
479         }));
480         let their_thread = my_thread.clone();
481
482         let my_packet: Arc<Packet<'scope, T>> = Arc::new(Packet {
483             scope: scope_data,
484             result: UnsafeCell::new(None),
485             _marker: PhantomData,
486         });
487         let their_packet = my_packet.clone();
488
489         let output_capture = crate::io::set_output_capture(None);
490         crate::io::set_output_capture(output_capture.clone());
491
492         let main = move || {
493             if let Some(name) = their_thread.cname() {
494                 imp::Thread::set_name(name);
495             }
496
497             crate::io::set_output_capture(output_capture);
498
499             // SAFETY: the stack guard passed is the one for the current thread.
500             // This means the current thread's stack and the new thread's stack
501             // are properly set and protected from each other.
502             thread_info::set(unsafe { imp::guard::current() }, their_thread);
503             let try_result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
504                 crate::sys_common::backtrace::__rust_begin_short_backtrace(f)
505             }));
506             // SAFETY: `their_packet` as been built just above and moved by the
507             // closure (it is an Arc<...>) and `my_packet` will be stored in the
508             // same `JoinInner` as this closure meaning the mutation will be
509             // safe (not modify it and affect a value far away).
510             unsafe { *their_packet.result.get() = Some(try_result) };
511         };
512
513         if let Some(scope_data) = &my_packet.scope {
514             scope_data.increment_num_running_threads();
515         }
516
517         Ok(JoinInner {
518             // SAFETY:
519             //
520             // `imp::Thread::new` takes a closure with a `'static` lifetime, since it's passed
521             // through FFI or otherwise used with low-level threading primitives that have no
522             // notion of or way to enforce lifetimes.
523             //
524             // As mentioned in the `Safety` section of this function's documentation, the caller of
525             // this function needs to guarantee that the passed-in lifetime is sufficiently long
526             // for the lifetime of the thread.
527             //
528             // Similarly, the `sys` implementation must guarantee that no references to the closure
529             // exist after the thread has terminated, which is signaled by `Thread::join`
530             // returning.
531             native: unsafe {
532                 imp::Thread::new(
533                     stack_size,
534                     mem::transmute::<Box<dyn FnOnce() + 'a>, Box<dyn FnOnce() + 'static>>(
535                         Box::new(main),
536                     ),
537                 )?
538             },
539             thread: my_thread,
540             packet: my_packet,
541         })
542     }
543 }
544
545 ////////////////////////////////////////////////////////////////////////////////
546 // Free functions
547 ////////////////////////////////////////////////////////////////////////////////
548
549 /// Spawns a new thread, returning a [`JoinHandle`] for it.
550 ///
551 /// The join handle provides a [`join`] method that can be used to join the spawned
552 /// thread. If the spawned thread panics, [`join`] will return an [`Err`] containing
553 /// the argument given to [`panic!`].
554 ///
555 /// If the join handle is dropped, the spawned thread will implicitly be *detached*.
556 /// In this case, the spawned thread may no longer be joined.
557 /// (It is the responsibility of the program to either eventually join threads it
558 /// creates or detach them; otherwise, a resource leak will result.)
559 ///
560 /// This call will create a thread using default parameters of [`Builder`], if you
561 /// want to specify the stack size or the name of the thread, use this API
562 /// instead.
563 ///
564 /// As you can see in the signature of `spawn` there are two constraints on
565 /// both the closure given to `spawn` and its return value, let's explain them:
566 ///
567 /// - The `'static` constraint means that the closure and its return value
568 ///   must have a lifetime of the whole program execution. The reason for this
569 ///   is that threads can outlive the lifetime they have been created in.
570 ///
571 ///   Indeed if the thread, and by extension its return value, can outlive their
572 ///   caller, we need to make sure that they will be valid afterwards, and since
573 ///   we *can't* know when it will return we need to have them valid as long as
574 ///   possible, that is until the end of the program, hence the `'static`
575 ///   lifetime.
576 /// - The [`Send`] constraint is because the closure will need to be passed
577 ///   *by value* from the thread where it is spawned to the new thread. Its
578 ///   return value will need to be passed from the new thread to the thread
579 ///   where it is `join`ed.
580 ///   As a reminder, the [`Send`] marker trait expresses that it is safe to be
581 ///   passed from thread to thread. [`Sync`] expresses that it is safe to have a
582 ///   reference be passed from thread to thread.
583 ///
584 /// # Panics
585 ///
586 /// Panics if the OS fails to create a thread; use [`Builder::spawn`]
587 /// to recover from such errors.
588 ///
589 /// # Examples
590 ///
591 /// Creating a thread.
592 ///
593 /// ```
594 /// use std::thread;
595 ///
596 /// let handler = thread::spawn(|| {
597 ///     // thread code
598 /// });
599 ///
600 /// handler.join().unwrap();
601 /// ```
602 ///
603 /// As mentioned in the module documentation, threads are usually made to
604 /// communicate using [`channels`], here is how it usually looks.
605 ///
606 /// This example also shows how to use `move`, in order to give ownership
607 /// of values to a thread.
608 ///
609 /// ```
610 /// use std::thread;
611 /// use std::sync::mpsc::channel;
612 ///
613 /// let (tx, rx) = channel();
614 ///
615 /// let sender = thread::spawn(move || {
616 ///     tx.send("Hello, thread".to_owned())
617 ///         .expect("Unable to send on channel");
618 /// });
619 ///
620 /// let receiver = thread::spawn(move || {
621 ///     let value = rx.recv().expect("Unable to receive from channel");
622 ///     println!("{value}");
623 /// });
624 ///
625 /// sender.join().expect("The sender thread has panicked");
626 /// receiver.join().expect("The receiver thread has panicked");
627 /// ```
628 ///
629 /// A thread can also return a value through its [`JoinHandle`], you can use
630 /// this to make asynchronous computations (futures might be more appropriate
631 /// though).
632 ///
633 /// ```
634 /// use std::thread;
635 ///
636 /// let computation = thread::spawn(|| {
637 ///     // Some expensive computation.
638 ///     42
639 /// });
640 ///
641 /// let result = computation.join().unwrap();
642 /// println!("{result}");
643 /// ```
644 ///
645 /// [`channels`]: crate::sync::mpsc
646 /// [`join`]: JoinHandle::join
647 /// [`Err`]: crate::result::Result::Err
648 #[stable(feature = "rust1", since = "1.0.0")]
649 pub fn spawn<F, T>(f: F) -> JoinHandle<T>
650 where
651     F: FnOnce() -> T,
652     F: Send + 'static,
653     T: Send + 'static,
654 {
655     Builder::new().spawn(f).expect("failed to spawn thread")
656 }
657
658 /// Gets a handle to the thread that invokes it.
659 ///
660 /// # Examples
661 ///
662 /// Getting a handle to the current thread with `thread::current()`:
663 ///
664 /// ```
665 /// use std::thread;
666 ///
667 /// let handler = thread::Builder::new()
668 ///     .name("named thread".into())
669 ///     .spawn(|| {
670 ///         let handle = thread::current();
671 ///         assert_eq!(handle.name(), Some("named thread"));
672 ///     })
673 ///     .unwrap();
674 ///
675 /// handler.join().unwrap();
676 /// ```
677 #[must_use]
678 #[stable(feature = "rust1", since = "1.0.0")]
679 pub fn current() -> Thread {
680     thread_info::current_thread().expect(
681         "use of std::thread::current() is not possible \
682          after the thread's local data has been destroyed",
683     )
684 }
685
686 /// Cooperatively gives up a timeslice to the OS scheduler.
687 ///
688 /// This calls the underlying OS scheduler's yield primitive, signaling
689 /// that the calling thread is willing to give up its remaining timeslice
690 /// so that the OS may schedule other threads on the CPU.
691 ///
692 /// A drawback of yielding in a loop is that if the OS does not have any
693 /// other ready threads to run on the current CPU, the thread will effectively
694 /// busy-wait, which wastes CPU time and energy.
695 ///
696 /// Therefore, when waiting for events of interest, a programmer's first
697 /// choice should be to use synchronization devices such as [`channel`]s,
698 /// [`Condvar`]s, [`Mutex`]es or [`join`] since these primitives are
699 /// implemented in a blocking manner, giving up the CPU until the event
700 /// of interest has occurred which avoids repeated yielding.
701 ///
702 /// `yield_now` should thus be used only rarely, mostly in situations where
703 /// repeated polling is required because there is no other suitable way to
704 /// learn when an event of interest has occurred.
705 ///
706 /// # Examples
707 ///
708 /// ```
709 /// use std::thread;
710 ///
711 /// thread::yield_now();
712 /// ```
713 ///
714 /// [`channel`]: crate::sync::mpsc
715 /// [`join`]: JoinHandle::join
716 /// [`Condvar`]: crate::sync::Condvar
717 /// [`Mutex`]: crate::sync::Mutex
718 #[stable(feature = "rust1", since = "1.0.0")]
719 pub fn yield_now() {
720     imp::Thread::yield_now()
721 }
722
723 /// Determines whether the current thread is unwinding because of panic.
724 ///
725 /// A common use of this feature is to poison shared resources when writing
726 /// unsafe code, by checking `panicking` when the `drop` is called.
727 ///
728 /// This is usually not needed when writing safe code, as [`Mutex`es][Mutex]
729 /// already poison themselves when a thread panics while holding the lock.
730 ///
731 /// This can also be used in multithreaded applications, in order to send a
732 /// message to other threads warning that a thread has panicked (e.g., for
733 /// monitoring purposes).
734 ///
735 /// # Examples
736 ///
737 /// ```should_panic
738 /// use std::thread;
739 ///
740 /// struct SomeStruct;
741 ///
742 /// impl Drop for SomeStruct {
743 ///     fn drop(&mut self) {
744 ///         if thread::panicking() {
745 ///             println!("dropped while unwinding");
746 ///         } else {
747 ///             println!("dropped while not unwinding");
748 ///         }
749 ///     }
750 /// }
751 ///
752 /// {
753 ///     print!("a: ");
754 ///     let a = SomeStruct;
755 /// }
756 ///
757 /// {
758 ///     print!("b: ");
759 ///     let b = SomeStruct;
760 ///     panic!()
761 /// }
762 /// ```
763 ///
764 /// [Mutex]: crate::sync::Mutex
765 #[inline]
766 #[must_use]
767 #[stable(feature = "rust1", since = "1.0.0")]
768 pub fn panicking() -> bool {
769     panicking::panicking()
770 }
771
772 /// Puts the current thread to sleep for at least the specified amount of time.
773 ///
774 /// The thread may sleep longer than the duration specified due to scheduling
775 /// specifics or platform-dependent functionality. It will never sleep less.
776 ///
777 /// This function is blocking, and should not be used in `async` functions.
778 ///
779 /// # Platform-specific behavior
780 ///
781 /// On Unix platforms, the underlying syscall may be interrupted by a
782 /// spurious wakeup or signal handler. To ensure the sleep occurs for at least
783 /// the specified duration, this function may invoke that system call multiple
784 /// times.
785 ///
786 /// # Examples
787 ///
788 /// ```no_run
789 /// use std::thread;
790 ///
791 /// // Let's sleep for 2 seconds:
792 /// thread::sleep_ms(2000);
793 /// ```
794 #[stable(feature = "rust1", since = "1.0.0")]
795 #[deprecated(since = "1.6.0", note = "replaced by `std::thread::sleep`")]
796 pub fn sleep_ms(ms: u32) {
797     sleep(Duration::from_millis(ms as u64))
798 }
799
800 /// Puts the current thread to sleep for at least the specified amount of time.
801 ///
802 /// The thread may sleep longer than the duration specified due to scheduling
803 /// specifics or platform-dependent functionality. It will never sleep less.
804 ///
805 /// This function is blocking, and should not be used in `async` functions.
806 ///
807 /// # Platform-specific behavior
808 ///
809 /// On Unix platforms, the underlying syscall may be interrupted by a
810 /// spurious wakeup or signal handler. To ensure the sleep occurs for at least
811 /// the specified duration, this function may invoke that system call multiple
812 /// times.
813 /// Platforms which do not support nanosecond precision for sleeping will
814 /// have `dur` rounded up to the nearest granularity of time they can sleep for.
815 ///
816 /// Currently, specifying a zero duration on Unix platforms returns immediately
817 /// without invoking the underlying [`nanosleep`] syscall, whereas on Windows
818 /// platforms the underlying [`Sleep`] syscall is always invoked.
819 /// If the intention is to yield the current time-slice you may want to use
820 /// [`yield_now`] instead.
821 ///
822 /// [`nanosleep`]: https://linux.die.net/man/2/nanosleep
823 /// [`Sleep`]: https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-sleep
824 ///
825 /// # Examples
826 ///
827 /// ```no_run
828 /// use std::{thread, time};
829 ///
830 /// let ten_millis = time::Duration::from_millis(10);
831 /// let now = time::Instant::now();
832 ///
833 /// thread::sleep(ten_millis);
834 ///
835 /// assert!(now.elapsed() >= ten_millis);
836 /// ```
837 #[stable(feature = "thread_sleep", since = "1.4.0")]
838 pub fn sleep(dur: Duration) {
839     imp::Thread::sleep(dur)
840 }
841
842 /// Blocks unless or until the current thread's token is made available.
843 ///
844 /// A call to `park` does not guarantee that the thread will remain parked
845 /// forever, and callers should be prepared for this possibility.
846 ///
847 /// # park and unpark
848 ///
849 /// Every thread is equipped with some basic low-level blocking support, via the
850 /// [`thread::park`][`park`] function and [`thread::Thread::unpark`][`unpark`]
851 /// method. [`park`] blocks the current thread, which can then be resumed from
852 /// another thread by calling the [`unpark`] method on the blocked thread's
853 /// handle.
854 ///
855 /// Conceptually, each [`Thread`] handle has an associated token, which is
856 /// initially not present:
857 ///
858 /// * The [`thread::park`][`park`] function blocks the current thread unless or
859 ///   until the token is available for its thread handle, at which point it
860 ///   atomically consumes the token. It may also return *spuriously*, without
861 ///   consuming the token. [`thread::park_timeout`] does the same, but allows
862 ///   specifying a maximum time to block the thread for.
863 ///
864 /// * The [`unpark`] method on a [`Thread`] atomically makes the token available
865 ///   if it wasn't already. Because the token is initially absent, [`unpark`]
866 ///   followed by [`park`] will result in the second call returning immediately.
867 ///
868 /// In other words, each [`Thread`] acts a bit like a spinlock that can be
869 /// locked and unlocked using `park` and `unpark`.
870 ///
871 /// Notice that being unblocked does not imply any synchronization with someone
872 /// that unparked this thread, it could also be spurious.
873 /// For example, it would be a valid, but inefficient, implementation to make both [`park`] and
874 /// [`unpark`] return immediately without doing anything.
875 ///
876 /// The API is typically used by acquiring a handle to the current thread,
877 /// placing that handle in a shared data structure so that other threads can
878 /// find it, and then `park`ing in a loop. When some desired condition is met, another
879 /// thread calls [`unpark`] on the handle.
880 ///
881 /// The motivation for this design is twofold:
882 ///
883 /// * It avoids the need to allocate mutexes and condvars when building new
884 ///   synchronization primitives; the threads already provide basic
885 ///   blocking/signaling.
886 ///
887 /// * It can be implemented very efficiently on many platforms.
888 ///
889 /// # Examples
890 ///
891 /// ```
892 /// use std::thread;
893 /// use std::sync::{Arc, atomic::{Ordering, AtomicBool}};
894 /// use std::time::Duration;
895 ///
896 /// let flag = Arc::new(AtomicBool::new(false));
897 /// let flag2 = Arc::clone(&flag);
898 ///
899 /// let parked_thread = thread::spawn(move || {
900 ///     // We want to wait until the flag is set. We *could* just spin, but using
901 ///     // park/unpark is more efficient.
902 ///     while !flag2.load(Ordering::Acquire) {
903 ///         println!("Parking thread");
904 ///         thread::park();
905 ///         // We *could* get here spuriously, i.e., way before the 10ms below are over!
906 ///         // But that is no problem, we are in a loop until the flag is set anyway.
907 ///         println!("Thread unparked");
908 ///     }
909 ///     println!("Flag received");
910 /// });
911 ///
912 /// // Let some time pass for the thread to be spawned.
913 /// thread::sleep(Duration::from_millis(10));
914 ///
915 /// // Set the flag, and let the thread wake up.
916 /// // There is no race condition here, if `unpark`
917 /// // happens first, `park` will return immediately.
918 /// // Hence there is no risk of a deadlock.
919 /// flag.store(true, Ordering::Release);
920 /// println!("Unpark the thread");
921 /// parked_thread.thread().unpark();
922 ///
923 /// parked_thread.join().unwrap();
924 /// ```
925 ///
926 /// [`unpark`]: Thread::unpark
927 /// [`thread::park_timeout`]: park_timeout
928 #[stable(feature = "rust1", since = "1.0.0")]
929 pub fn park() {
930     // SAFETY: park_timeout is called on the parker owned by this thread.
931     unsafe {
932         current().inner.as_ref().parker().park();
933     }
934 }
935
936 /// Use [`park_timeout`].
937 ///
938 /// Blocks unless or until the current thread's token is made available or
939 /// the specified duration has been reached (may wake spuriously).
940 ///
941 /// The semantics of this function are equivalent to [`park`] except
942 /// that the thread will be blocked for roughly no longer than `dur`. This
943 /// method should not be used for precise timing due to anomalies such as
944 /// preemption or platform differences that might not cause the maximum
945 /// amount of time waited to be precisely `ms` long.
946 ///
947 /// See the [park documentation][`park`] for more detail.
948 #[stable(feature = "rust1", since = "1.0.0")]
949 #[deprecated(since = "1.6.0", note = "replaced by `std::thread::park_timeout`")]
950 pub fn park_timeout_ms(ms: u32) {
951     park_timeout(Duration::from_millis(ms as u64))
952 }
953
954 /// Blocks unless or until the current thread's token is made available or
955 /// the specified duration has been reached (may wake spuriously).
956 ///
957 /// The semantics of this function are equivalent to [`park`][park] except
958 /// that the thread will be blocked for roughly no longer than `dur`. This
959 /// method should not be used for precise timing due to anomalies such as
960 /// preemption or platform differences that might not cause the maximum
961 /// amount of time waited to be precisely `dur` long.
962 ///
963 /// See the [park documentation][park] for more details.
964 ///
965 /// # Platform-specific behavior
966 ///
967 /// Platforms which do not support nanosecond precision for sleeping will have
968 /// `dur` rounded up to the nearest granularity of time they can sleep for.
969 ///
970 /// # Examples
971 ///
972 /// Waiting for the complete expiration of the timeout:
973 ///
974 /// ```rust,no_run
975 /// use std::thread::park_timeout;
976 /// use std::time::{Instant, Duration};
977 ///
978 /// let timeout = Duration::from_secs(2);
979 /// let beginning_park = Instant::now();
980 ///
981 /// let mut timeout_remaining = timeout;
982 /// loop {
983 ///     park_timeout(timeout_remaining);
984 ///     let elapsed = beginning_park.elapsed();
985 ///     if elapsed >= timeout {
986 ///         break;
987 ///     }
988 ///     println!("restarting park_timeout after {elapsed:?}");
989 ///     timeout_remaining = timeout - elapsed;
990 /// }
991 /// ```
992 #[stable(feature = "park_timeout", since = "1.4.0")]
993 pub fn park_timeout(dur: Duration) {
994     // SAFETY: park_timeout is called on the parker owned by this thread.
995     unsafe {
996         current().inner.as_ref().parker().park_timeout(dur);
997     }
998 }
999
1000 ////////////////////////////////////////////////////////////////////////////////
1001 // ThreadId
1002 ////////////////////////////////////////////////////////////////////////////////
1003
1004 /// A unique identifier for a running thread.
1005 ///
1006 /// A `ThreadId` is an opaque object that uniquely identifies each thread
1007 /// created during the lifetime of a process. `ThreadId`s are guaranteed not to
1008 /// be reused, even when a thread terminates. `ThreadId`s are under the control
1009 /// of Rust's standard library and there may not be any relationship between
1010 /// `ThreadId` and the underlying platform's notion of a thread identifier --
1011 /// the two concepts cannot, therefore, be used interchangeably. A `ThreadId`
1012 /// can be retrieved from the [`id`] method on a [`Thread`].
1013 ///
1014 /// # Examples
1015 ///
1016 /// ```
1017 /// use std::thread;
1018 ///
1019 /// let other_thread = thread::spawn(|| {
1020 ///     thread::current().id()
1021 /// });
1022 ///
1023 /// let other_thread_id = other_thread.join().unwrap();
1024 /// assert!(thread::current().id() != other_thread_id);
1025 /// ```
1026 ///
1027 /// [`id`]: Thread::id
1028 #[stable(feature = "thread_id", since = "1.19.0")]
1029 #[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
1030 pub struct ThreadId(NonZeroU64);
1031
1032 impl ThreadId {
1033     // Generate a new unique thread ID.
1034     fn new() -> ThreadId {
1035         #[cold]
1036         fn exhausted() -> ! {
1037             panic!("failed to generate unique thread ID: bitspace exhausted")
1038         }
1039
1040         cfg_if::cfg_if! {
1041             if #[cfg(target_has_atomic = "64")] {
1042                 use crate::sync::atomic::{AtomicU64, Ordering::Relaxed};
1043
1044                 static COUNTER: AtomicU64 = AtomicU64::new(0);
1045
1046                 let mut last = COUNTER.load(Relaxed);
1047                 loop {
1048                     let Some(id) = last.checked_add(1) else {
1049                         exhausted();
1050                     };
1051
1052                     match COUNTER.compare_exchange_weak(last, id, Relaxed, Relaxed) {
1053                         Ok(_) => return ThreadId(NonZeroU64::new(id).unwrap()),
1054                         Err(id) => last = id,
1055                     }
1056                 }
1057             } else {
1058                 use crate::sys_common::mutex::StaticMutex;
1059
1060                 // It is UB to attempt to acquire this mutex reentrantly!
1061                 static GUARD: StaticMutex = StaticMutex::new();
1062                 static mut COUNTER: u64 = 0;
1063
1064                 unsafe {
1065                     let guard = GUARD.lock();
1066
1067                     let Some(id) = COUNTER.checked_add(1) else {
1068                         drop(guard); // in case the panic handler ends up calling `ThreadId::new()`, avoid reentrant lock acquire.
1069                         exhausted();
1070                     };
1071
1072                     COUNTER = id;
1073                     drop(guard);
1074                     ThreadId(NonZeroU64::new(id).unwrap())
1075                 }
1076             }
1077         }
1078     }
1079
1080     /// This returns a numeric identifier for the thread identified by this
1081     /// `ThreadId`.
1082     ///
1083     /// As noted in the documentation for the type itself, it is essentially an
1084     /// opaque ID, but is guaranteed to be unique for each thread. The returned
1085     /// value is entirely opaque -- only equality testing is stable. Note that
1086     /// it is not guaranteed which values new threads will return, and this may
1087     /// change across Rust versions.
1088     #[must_use]
1089     #[unstable(feature = "thread_id_value", issue = "67939")]
1090     pub fn as_u64(&self) -> NonZeroU64 {
1091         self.0
1092     }
1093 }
1094
1095 ////////////////////////////////////////////////////////////////////////////////
1096 // Thread
1097 ////////////////////////////////////////////////////////////////////////////////
1098
1099 /// The internal representation of a `Thread` handle
1100 struct Inner {
1101     name: Option<CString>, // Guaranteed to be UTF-8
1102     id: ThreadId,
1103     parker: Parker,
1104 }
1105
1106 impl Inner {
1107     fn parker(self: Pin<&Self>) -> Pin<&Parker> {
1108         unsafe { Pin::map_unchecked(self, |inner| &inner.parker) }
1109     }
1110 }
1111
1112 #[derive(Clone)]
1113 #[stable(feature = "rust1", since = "1.0.0")]
1114 /// A handle to a thread.
1115 ///
1116 /// Threads are represented via the `Thread` type, which you can get in one of
1117 /// two ways:
1118 ///
1119 /// * By spawning a new thread, e.g., using the [`thread::spawn`][`spawn`]
1120 ///   function, and calling [`thread`][`JoinHandle::thread`] on the
1121 ///   [`JoinHandle`].
1122 /// * By requesting the current thread, using the [`thread::current`] function.
1123 ///
1124 /// The [`thread::current`] function is available even for threads not spawned
1125 /// by the APIs of this module.
1126 ///
1127 /// There is usually no need to create a `Thread` struct yourself, one
1128 /// should instead use a function like `spawn` to create new threads, see the
1129 /// docs of [`Builder`] and [`spawn`] for more details.
1130 ///
1131 /// [`thread::current`]: current
1132 pub struct Thread {
1133     inner: Pin<Arc<Inner>>,
1134 }
1135
1136 impl Thread {
1137     // Used only internally to construct a thread object without spawning
1138     // Panics if the name contains nuls.
1139     pub(crate) fn new(name: Option<CString>) -> Thread {
1140         // We have to use `unsafe` here to construct the `Parker` in-place,
1141         // which is required for the UNIX implementation.
1142         //
1143         // SAFETY: We pin the Arc immediately after creation, so its address never
1144         // changes.
1145         let inner = unsafe {
1146             let mut arc = Arc::<Inner>::new_uninit();
1147             let ptr = Arc::get_mut_unchecked(&mut arc).as_mut_ptr();
1148             addr_of_mut!((*ptr).name).write(name);
1149             addr_of_mut!((*ptr).id).write(ThreadId::new());
1150             Parker::new(addr_of_mut!((*ptr).parker));
1151             Pin::new_unchecked(arc.assume_init())
1152         };
1153
1154         Thread { inner }
1155     }
1156
1157     /// Atomically makes the handle's token available if it is not already.
1158     ///
1159     /// Every thread is equipped with some basic low-level blocking support, via
1160     /// the [`park`][park] function and the `unpark()` method. These can be
1161     /// used as a more CPU-efficient implementation of a spinlock.
1162     ///
1163     /// See the [park documentation][park] for more details.
1164     ///
1165     /// # Examples
1166     ///
1167     /// ```
1168     /// use std::thread;
1169     /// use std::time::Duration;
1170     ///
1171     /// let parked_thread = thread::Builder::new()
1172     ///     .spawn(|| {
1173     ///         println!("Parking thread");
1174     ///         thread::park();
1175     ///         println!("Thread unparked");
1176     ///     })
1177     ///     .unwrap();
1178     ///
1179     /// // Let some time pass for the thread to be spawned.
1180     /// thread::sleep(Duration::from_millis(10));
1181     ///
1182     /// println!("Unpark the thread");
1183     /// parked_thread.thread().unpark();
1184     ///
1185     /// parked_thread.join().unwrap();
1186     /// ```
1187     #[stable(feature = "rust1", since = "1.0.0")]
1188     #[inline]
1189     pub fn unpark(&self) {
1190         self.inner.as_ref().parker().unpark();
1191     }
1192
1193     /// Gets the thread's unique identifier.
1194     ///
1195     /// # Examples
1196     ///
1197     /// ```
1198     /// use std::thread;
1199     ///
1200     /// let other_thread = thread::spawn(|| {
1201     ///     thread::current().id()
1202     /// });
1203     ///
1204     /// let other_thread_id = other_thread.join().unwrap();
1205     /// assert!(thread::current().id() != other_thread_id);
1206     /// ```
1207     #[stable(feature = "thread_id", since = "1.19.0")]
1208     #[must_use]
1209     pub fn id(&self) -> ThreadId {
1210         self.inner.id
1211     }
1212
1213     /// Gets the thread's name.
1214     ///
1215     /// For more information about named threads, see
1216     /// [this module-level documentation][naming-threads].
1217     ///
1218     /// # Examples
1219     ///
1220     /// Threads by default have no name specified:
1221     ///
1222     /// ```
1223     /// use std::thread;
1224     ///
1225     /// let builder = thread::Builder::new();
1226     ///
1227     /// let handler = builder.spawn(|| {
1228     ///     assert!(thread::current().name().is_none());
1229     /// }).unwrap();
1230     ///
1231     /// handler.join().unwrap();
1232     /// ```
1233     ///
1234     /// Thread with a specified name:
1235     ///
1236     /// ```
1237     /// use std::thread;
1238     ///
1239     /// let builder = thread::Builder::new()
1240     ///     .name("foo".into());
1241     ///
1242     /// let handler = builder.spawn(|| {
1243     ///     assert_eq!(thread::current().name(), Some("foo"))
1244     /// }).unwrap();
1245     ///
1246     /// handler.join().unwrap();
1247     /// ```
1248     ///
1249     /// [naming-threads]: ./index.html#naming-threads
1250     #[stable(feature = "rust1", since = "1.0.0")]
1251     #[must_use]
1252     pub fn name(&self) -> Option<&str> {
1253         self.cname().map(|s| unsafe { str::from_utf8_unchecked(s.to_bytes()) })
1254     }
1255
1256     fn cname(&self) -> Option<&CStr> {
1257         self.inner.name.as_deref()
1258     }
1259 }
1260
1261 #[stable(feature = "rust1", since = "1.0.0")]
1262 impl fmt::Debug for Thread {
1263     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1264         f.debug_struct("Thread")
1265             .field("id", &self.id())
1266             .field("name", &self.name())
1267             .finish_non_exhaustive()
1268     }
1269 }
1270
1271 ////////////////////////////////////////////////////////////////////////////////
1272 // JoinHandle
1273 ////////////////////////////////////////////////////////////////////////////////
1274
1275 /// A specialized [`Result`] type for threads.
1276 ///
1277 /// Indicates the manner in which a thread exited.
1278 ///
1279 /// The value contained in the `Result::Err` variant
1280 /// is the value the thread panicked with;
1281 /// that is, the argument the `panic!` macro was called with.
1282 /// Unlike with normal errors, this value doesn't implement
1283 /// the [`Error`](crate::error::Error) trait.
1284 ///
1285 /// Thus, a sensible way to handle a thread panic is to either:
1286 ///
1287 /// 1. propagate the panic with [`std::panic::resume_unwind`]
1288 /// 2. or in case the thread is intended to be a subsystem boundary
1289 /// that is supposed to isolate system-level failures,
1290 /// match on the `Err` variant and handle the panic in an appropriate way
1291 ///
1292 /// A thread that completes without panicking is considered to exit successfully.
1293 ///
1294 /// # Examples
1295 ///
1296 /// Matching on the result of a joined thread:
1297 ///
1298 /// ```no_run
1299 /// use std::{fs, thread, panic};
1300 ///
1301 /// fn copy_in_thread() -> thread::Result<()> {
1302 ///     thread::spawn(|| {
1303 ///         fs::copy("foo.txt", "bar.txt").unwrap();
1304 ///     }).join()
1305 /// }
1306 ///
1307 /// fn main() {
1308 ///     match copy_in_thread() {
1309 ///         Ok(_) => println!("copy succeeded"),
1310 ///         Err(e) => panic::resume_unwind(e),
1311 ///     }
1312 /// }
1313 /// ```
1314 ///
1315 /// [`Result`]: crate::result::Result
1316 /// [`std::panic::resume_unwind`]: crate::panic::resume_unwind
1317 #[stable(feature = "rust1", since = "1.0.0")]
1318 pub type Result<T> = crate::result::Result<T, Box<dyn Any + Send + 'static>>;
1319
1320 // This packet is used to communicate the return value between the spawned
1321 // thread and the rest of the program. It is shared through an `Arc` and
1322 // there's no need for a mutex here because synchronization happens with `join()`
1323 // (the caller will never read this packet until the thread has exited).
1324 //
1325 // An Arc to the packet is stored into a `JoinInner` which in turns is placed
1326 // in `JoinHandle`.
1327 struct Packet<'scope, T> {
1328     scope: Option<Arc<scoped::ScopeData>>,
1329     result: UnsafeCell<Option<Result<T>>>,
1330     _marker: PhantomData<Option<&'scope scoped::ScopeData>>,
1331 }
1332
1333 // Due to the usage of `UnsafeCell` we need to manually implement Sync.
1334 // The type `T` should already always be Send (otherwise the thread could not
1335 // have been created) and the Packet is Sync because all access to the
1336 // `UnsafeCell` synchronized (by the `join()` boundary), and `ScopeData` is Sync.
1337 unsafe impl<'scope, T: Sync> Sync for Packet<'scope, T> {}
1338
1339 impl<'scope, T> Drop for Packet<'scope, T> {
1340     fn drop(&mut self) {
1341         // If this packet was for a thread that ran in a scope, the thread
1342         // panicked, and nobody consumed the panic payload, we make sure
1343         // the scope function will panic.
1344         let unhandled_panic = matches!(self.result.get_mut(), Some(Err(_)));
1345         // Drop the result without causing unwinding.
1346         // This is only relevant for threads that aren't join()ed, as
1347         // join() will take the `result` and set it to None, such that
1348         // there is nothing left to drop here.
1349         // If this panics, we should handle that, because we're outside the
1350         // outermost `catch_unwind` of our thread.
1351         // We just abort in that case, since there's nothing else we can do.
1352         // (And even if we tried to handle it somehow, we'd also need to handle
1353         // the case where the panic payload we get out of it also panics on
1354         // drop, and so on. See issue #86027.)
1355         if let Err(_) = panic::catch_unwind(panic::AssertUnwindSafe(|| {
1356             *self.result.get_mut() = None;
1357         })) {
1358             rtabort!("thread result panicked on drop");
1359         }
1360         // Book-keeping so the scope knows when it's done.
1361         if let Some(scope) = &self.scope {
1362             // Now that there will be no more user code running on this thread
1363             // that can use 'scope, mark the thread as 'finished'.
1364             // It's important we only do this after the `result` has been dropped,
1365             // since dropping it might still use things it borrowed from 'scope.
1366             scope.decrement_num_running_threads(unhandled_panic);
1367         }
1368     }
1369 }
1370
1371 /// Inner representation for JoinHandle
1372 struct JoinInner<'scope, T> {
1373     native: imp::Thread,
1374     thread: Thread,
1375     packet: Arc<Packet<'scope, T>>,
1376 }
1377
1378 impl<'scope, T> JoinInner<'scope, T> {
1379     fn join(mut self) -> Result<T> {
1380         self.native.join();
1381         Arc::get_mut(&mut self.packet).unwrap().result.get_mut().take().unwrap()
1382     }
1383 }
1384
1385 /// An owned permission to join on a thread (block on its termination).
1386 ///
1387 /// A `JoinHandle` *detaches* the associated thread when it is dropped, which
1388 /// means that there is no longer any handle to the thread and no way to `join`
1389 /// on it.
1390 ///
1391 /// Due to platform restrictions, it is not possible to [`Clone`] this
1392 /// handle: the ability to join a thread is a uniquely-owned permission.
1393 ///
1394 /// This `struct` is created by the [`thread::spawn`] function and the
1395 /// [`thread::Builder::spawn`] method.
1396 ///
1397 /// # Examples
1398 ///
1399 /// Creation from [`thread::spawn`]:
1400 ///
1401 /// ```
1402 /// use std::thread;
1403 ///
1404 /// let join_handle: thread::JoinHandle<_> = thread::spawn(|| {
1405 ///     // some work here
1406 /// });
1407 /// ```
1408 ///
1409 /// Creation from [`thread::Builder::spawn`]:
1410 ///
1411 /// ```
1412 /// use std::thread;
1413 ///
1414 /// let builder = thread::Builder::new();
1415 ///
1416 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1417 ///     // some work here
1418 /// }).unwrap();
1419 /// ```
1420 ///
1421 /// A thread being detached and outliving the thread that spawned it:
1422 ///
1423 /// ```no_run
1424 /// use std::thread;
1425 /// use std::time::Duration;
1426 ///
1427 /// let original_thread = thread::spawn(|| {
1428 ///     let _detached_thread = thread::spawn(|| {
1429 ///         // Here we sleep to make sure that the first thread returns before.
1430 ///         thread::sleep(Duration::from_millis(10));
1431 ///         // This will be called, even though the JoinHandle is dropped.
1432 ///         println!("♫ Still alive ♫");
1433 ///     });
1434 /// });
1435 ///
1436 /// original_thread.join().expect("The thread being joined has panicked");
1437 /// println!("Original thread is joined.");
1438 ///
1439 /// // We make sure that the new thread has time to run, before the main
1440 /// // thread returns.
1441 ///
1442 /// thread::sleep(Duration::from_millis(1000));
1443 /// ```
1444 ///
1445 /// [`thread::Builder::spawn`]: Builder::spawn
1446 /// [`thread::spawn`]: spawn
1447 #[stable(feature = "rust1", since = "1.0.0")]
1448 pub struct JoinHandle<T>(JoinInner<'static, T>);
1449
1450 #[stable(feature = "joinhandle_impl_send_sync", since = "1.29.0")]
1451 unsafe impl<T> Send for JoinHandle<T> {}
1452 #[stable(feature = "joinhandle_impl_send_sync", since = "1.29.0")]
1453 unsafe impl<T> Sync for JoinHandle<T> {}
1454
1455 impl<T> JoinHandle<T> {
1456     /// Extracts a handle to the underlying thread.
1457     ///
1458     /// # Examples
1459     ///
1460     /// ```
1461     /// use std::thread;
1462     ///
1463     /// let builder = thread::Builder::new();
1464     ///
1465     /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1466     ///     // some work here
1467     /// }).unwrap();
1468     ///
1469     /// let thread = join_handle.thread();
1470     /// println!("thread id: {:?}", thread.id());
1471     /// ```
1472     #[stable(feature = "rust1", since = "1.0.0")]
1473     #[must_use]
1474     pub fn thread(&self) -> &Thread {
1475         &self.0.thread
1476     }
1477
1478     /// Waits for the associated thread to finish.
1479     ///
1480     /// This function will return immediately if the associated thread has already finished.
1481     ///
1482     /// In terms of [atomic memory orderings],  the completion of the associated
1483     /// thread synchronizes with this function returning. In other words, all
1484     /// operations performed by that thread [happen
1485     /// before](https://doc.rust-lang.org/nomicon/atomics.html#data-accesses) all
1486     /// operations that happen after `join` returns.
1487     ///
1488     /// If the associated thread panics, [`Err`] is returned with the parameter given
1489     /// to [`panic!`].
1490     ///
1491     /// [`Err`]: crate::result::Result::Err
1492     /// [atomic memory orderings]: crate::sync::atomic
1493     ///
1494     /// # Panics
1495     ///
1496     /// This function may panic on some platforms if a thread attempts to join
1497     /// itself or otherwise may create a deadlock with joining threads.
1498     ///
1499     /// # Examples
1500     ///
1501     /// ```
1502     /// use std::thread;
1503     ///
1504     /// let builder = thread::Builder::new();
1505     ///
1506     /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1507     ///     // some work here
1508     /// }).unwrap();
1509     /// join_handle.join().expect("Couldn't join on the associated thread");
1510     /// ```
1511     #[stable(feature = "rust1", since = "1.0.0")]
1512     pub fn join(self) -> Result<T> {
1513         self.0.join()
1514     }
1515
1516     /// Checks if the associated thread has finished running its main function.
1517     ///
1518     /// `is_finished` supports implementing a non-blocking join operation, by checking
1519     /// `is_finished`, and calling `join` if it returns `true`. This function does not block. To
1520     /// block while waiting on the thread to finish, use [`join`][Self::join].
1521     ///
1522     /// This might return `true` for a brief moment after the thread's main
1523     /// function has returned, but before the thread itself has stopped running.
1524     /// However, once this returns `true`, [`join`][Self::join] can be expected
1525     /// to return quickly, without blocking for any significant amount of time.
1526     #[stable(feature = "thread_is_running", since = "1.61.0")]
1527     pub fn is_finished(&self) -> bool {
1528         Arc::strong_count(&self.0.packet) == 1
1529     }
1530 }
1531
1532 impl<T> AsInner<imp::Thread> for JoinHandle<T> {
1533     fn as_inner(&self) -> &imp::Thread {
1534         &self.0.native
1535     }
1536 }
1537
1538 impl<T> IntoInner<imp::Thread> for JoinHandle<T> {
1539     fn into_inner(self) -> imp::Thread {
1540         self.0.native
1541     }
1542 }
1543
1544 #[stable(feature = "std_debug", since = "1.16.0")]
1545 impl<T> fmt::Debug for JoinHandle<T> {
1546     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1547         f.debug_struct("JoinHandle").finish_non_exhaustive()
1548     }
1549 }
1550
1551 fn _assert_sync_and_send() {
1552     fn _assert_both<T: Send + Sync>() {}
1553     _assert_both::<JoinHandle<()>>();
1554     _assert_both::<Thread>();
1555 }
1556
1557 /// Returns an estimate of the default amount of parallelism a program should use.
1558 ///
1559 /// Parallelism is a resource. A given machine provides a certain capacity for
1560 /// parallelism, i.e., a bound on the number of computations it can perform
1561 /// simultaneously. This number often corresponds to the amount of CPUs a
1562 /// computer has, but it may diverge in various cases.
1563 ///
1564 /// Host environments such as VMs or container orchestrators may want to
1565 /// restrict the amount of parallelism made available to programs in them. This
1566 /// is often done to limit the potential impact of (unintentionally)
1567 /// resource-intensive programs on other programs running on the same machine.
1568 ///
1569 /// # Limitations
1570 ///
1571 /// The purpose of this API is to provide an easy and portable way to query
1572 /// the default amount of parallelism the program should use. Among other things it
1573 /// does not expose information on NUMA regions, does not account for
1574 /// differences in (co)processor capabilities or current system load,
1575 /// and will not modify the program's global state in order to more accurately
1576 /// query the amount of available parallelism.
1577 ///
1578 /// Where both fixed steady-state and burst limits are available the steady-state
1579 /// capacity will be used to ensure more predictable latencies.
1580 ///
1581 /// Resource limits can be changed during the runtime of a program, therefore the value is
1582 /// not cached and instead recomputed every time this function is called. It should not be
1583 /// called from hot code.
1584 ///
1585 /// The value returned by this function should be considered a simplified
1586 /// approximation of the actual amount of parallelism available at any given
1587 /// time. To get a more detailed or precise overview of the amount of
1588 /// parallelism available to the program, you may wish to use
1589 /// platform-specific APIs as well. The following platform limitations currently
1590 /// apply to `available_parallelism`:
1591 ///
1592 /// On Windows:
1593 /// - It may undercount the amount of parallelism available on systems with more
1594 ///   than 64 logical CPUs. However, programs typically need specific support to
1595 ///   take advantage of more than 64 logical CPUs, and in the absence of such
1596 ///   support, the number returned by this function accurately reflects the
1597 ///   number of logical CPUs the program can use by default.
1598 /// - It may overcount the amount of parallelism available on systems limited by
1599 ///   process-wide affinity masks, or job object limitations.
1600 ///
1601 /// On Linux:
1602 /// - It may overcount the amount of parallelism available when limited by a
1603 ///   process-wide affinity mask or cgroup quotas and `sched_getaffinity()` or cgroup fs can't be
1604 ///   queried, e.g. due to sandboxing.
1605 /// - It may undercount the amount of parallelism if the current thread's affinity mask
1606 ///   does not reflect the process' cpuset, e.g. due to pinned threads.
1607 /// - If the process is in a cgroup v1 cpu controller, this may need to
1608 ///   scan mountpoints to find the corresponding cgroup v1 controller,
1609 ///   which may take time on systems with large numbers of mountpoints.
1610 ///   (This does not apply to cgroup v2, or to processes not in a
1611 ///   cgroup.)
1612 ///
1613 /// On all targets:
1614 /// - It may overcount the amount of parallelism available when running in a VM
1615 /// with CPU usage limits (e.g. an overcommitted host).
1616 ///
1617 /// # Errors
1618 ///
1619 /// This function will, but is not limited to, return errors in the following
1620 /// cases:
1621 ///
1622 /// - If the amount of parallelism is not known for the target platform.
1623 /// - If the program lacks permission to query the amount of parallelism made
1624 ///   available to it.
1625 ///
1626 /// # Examples
1627 ///
1628 /// ```
1629 /// # #![allow(dead_code)]
1630 /// use std::{io, thread};
1631 ///
1632 /// fn main() -> io::Result<()> {
1633 ///     let count = thread::available_parallelism()?.get();
1634 ///     assert!(count >= 1_usize);
1635 ///     Ok(())
1636 /// }
1637 /// ```
1638 #[doc(alias = "available_concurrency")] // Alias for a previous name we gave this API on unstable.
1639 #[doc(alias = "hardware_concurrency")] // Alias for C++ `std::thread::hardware_concurrency`.
1640 #[doc(alias = "num_cpus")] // Alias for a popular ecosystem crate which provides similar functionality.
1641 #[stable(feature = "available_parallelism", since = "1.59.0")]
1642 pub fn available_parallelism() -> io::Result<NonZeroUsize> {
1643     imp::available_parallelism()
1644 }