std/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 of examples 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 is platform-dependent and subject to change.
128//! Currently, it is 2 MiB on all Tier-1 platforms.
129//!
130//! There are two ways to manually specify the stack size for spawned threads:
131//!
132//! * Build the thread with [`Builder`] and pass the desired stack size to [`Builder::stack_size`].
133//! * Set the `RUST_MIN_STACK` environment variable to an integer representing the desired stack
134//! size (in bytes). Note that setting [`Builder::stack_size`] will override this. Be aware that
135//! changes to `RUST_MIN_STACK` may be ignored after program start.
136//!
137//! Note that the stack size of the main thread is *not* determined by Rust.
138//!
139//! [channels]: crate::sync::mpsc
140//! [`join`]: JoinHandle::join
141//! [`Result`]: crate::result::Result
142//! [`Ok`]: crate::result::Result::Ok
143//! [`Err`]: crate::result::Result::Err
144//! [`thread::current`]: current::current
145//! [`thread::Result`]: Result
146//! [`unpark`]: Thread::unpark
147//! [`thread::park_timeout`]: park_timeout
148//! [`Cell`]: crate::cell::Cell
149//! [`RefCell`]: crate::cell::RefCell
150//! [`with`]: LocalKey::with
151//! [`thread_local!`]: crate::thread_local
152
153#![stable(feature = "rust1", since = "1.0.0")]
154#![deny(unsafe_op_in_unsafe_fn)]
155// Under `test`, `__FastLocalKeyInner` seems unused.
156#![cfg_attr(test, allow(dead_code))]
157
158#[cfg(all(test, not(any(target_os = "emscripten", target_os = "wasi"))))]
159mod tests;
160
161use crate::any::Any;
162use crate::cell::UnsafeCell;
163use crate::ffi::CStr;
164use crate::marker::PhantomData;
165use crate::mem::{self, ManuallyDrop, forget};
166use crate::num::NonZero;
167use crate::pin::Pin;
168use crate::sync::Arc;
169use crate::sync::atomic::{Atomic, AtomicUsize, Ordering};
170use crate::sys::sync::Parker;
171use crate::sys::thread as imp;
172use crate::sys_common::{AsInner, IntoInner};
173use crate::time::{Duration, Instant};
174use crate::{env, fmt, io, panic, panicking, str};
175
176#[stable(feature = "scoped_threads", since = "1.63.0")]
177mod scoped;
178
179#[stable(feature = "scoped_threads", since = "1.63.0")]
180pub use scoped::{Scope, ScopedJoinHandle, scope};
181
182mod current;
183
184#[stable(feature = "rust1", since = "1.0.0")]
185pub use current::current;
186#[unstable(feature = "current_thread_id", issue = "147194")]
187pub use current::current_id;
188pub(crate) use current::{current_or_unnamed, current_os_id, drop_current};
189use current::{set_current, try_with_current};
190
191mod spawnhook;
192
193#[unstable(feature = "thread_spawn_hook", issue = "132951")]
194pub use spawnhook::add_spawn_hook;
195
196////////////////////////////////////////////////////////////////////////////////
197// Thread-local storage
198////////////////////////////////////////////////////////////////////////////////
199
200#[macro_use]
201mod local;
202
203#[stable(feature = "rust1", since = "1.0.0")]
204pub use self::local::{AccessError, LocalKey};
205
206// Implementation details used by the thread_local!{} macro.
207#[doc(hidden)]
208#[unstable(feature = "thread_local_internals", issue = "none")]
209pub mod local_impl {
210 pub use super::local::thread_local_process_attrs;
211 pub use crate::sys::thread_local::*;
212}
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#[must_use = "must eventually spawn the thread"]
261#[stable(feature = "rust1", since = "1.0.0")]
262#[derive(Debug)]
263pub struct Builder {
264 // A name for the thread-to-be, for identification in panic messages
265 name: Option<String>,
266 // The size of the stack for the spawned thread in bytes
267 stack_size: Option<usize>,
268 // Skip running and inheriting the thread spawn hooks
269 no_hooks: bool,
270}
271
272impl 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, no_hooks: false }
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 /// Disables running and inheriting [spawn hooks](add_spawn_hook).
350 ///
351 /// Use this if the parent thread is in no way relevant for the child thread.
352 /// For example, when lazily spawning threads for a thread pool.
353 #[unstable(feature = "thread_spawn_hook", issue = "132951")]
354 pub fn no_hooks(mut self) -> Builder {
355 self.no_hooks = true;
356 self
357 }
358
359 /// Spawns a new thread by taking ownership of the `Builder`, and returns an
360 /// [`io::Result`] to its [`JoinHandle`].
361 ///
362 /// The spawned thread may outlive the caller (unless the caller thread
363 /// is the main thread; the whole process is terminated when the main
364 /// thread finishes). The join handle can be used to block on
365 /// termination of the spawned thread, including recovering its panics.
366 ///
367 /// For a more complete documentation see [`thread::spawn`][`spawn`].
368 ///
369 /// # Errors
370 ///
371 /// Unlike the [`spawn`] free function, this method yields an
372 /// [`io::Result`] to capture any failure to create the thread at
373 /// the OS level.
374 ///
375 /// [`io::Result`]: crate::io::Result
376 ///
377 /// # Panics
378 ///
379 /// Panics if a thread name was set and it contained null bytes.
380 ///
381 /// # Examples
382 ///
383 /// ```
384 /// use std::thread;
385 ///
386 /// let builder = thread::Builder::new();
387 ///
388 /// let handler = builder.spawn(|| {
389 /// // thread code
390 /// }).unwrap();
391 ///
392 /// handler.join().unwrap();
393 /// ```
394 #[stable(feature = "rust1", since = "1.0.0")]
395 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
396 pub fn spawn<F, T>(self, f: F) -> io::Result<JoinHandle<T>>
397 where
398 F: FnOnce() -> T,
399 F: Send + 'static,
400 T: Send + 'static,
401 {
402 unsafe { self.spawn_unchecked(f) }
403 }
404
405 /// Spawns a new thread without any lifetime restrictions by taking ownership
406 /// of the `Builder`, and returns an [`io::Result`] to its [`JoinHandle`].
407 ///
408 /// The spawned thread may outlive the caller (unless the caller thread
409 /// is the main thread; the whole process is terminated when the main
410 /// thread finishes). The join handle can be used to block on
411 /// termination of the spawned thread, including recovering its panics.
412 ///
413 /// This method is identical to [`thread::Builder::spawn`][`Builder::spawn`],
414 /// except for the relaxed lifetime bounds, which render it unsafe.
415 /// For a more complete documentation see [`thread::spawn`][`spawn`].
416 ///
417 /// # Errors
418 ///
419 /// Unlike the [`spawn`] free function, this method yields an
420 /// [`io::Result`] to capture any failure to create the thread at
421 /// the OS level.
422 ///
423 /// # Panics
424 ///
425 /// Panics if a thread name was set and it contained null bytes.
426 ///
427 /// # Safety
428 ///
429 /// The caller has to ensure that the spawned thread does not outlive any
430 /// references in the supplied thread closure and its return type.
431 /// This can be guaranteed in two ways:
432 ///
433 /// - ensure that [`join`][`JoinHandle::join`] is called before any referenced
434 /// data is dropped
435 /// - use only types with `'static` lifetime bounds, i.e., those with no or only
436 /// `'static` references (both [`thread::Builder::spawn`][`Builder::spawn`]
437 /// and [`thread::spawn`][`spawn`] enforce this property statically)
438 ///
439 /// # Examples
440 ///
441 /// ```
442 /// use std::thread;
443 ///
444 /// let builder = thread::Builder::new();
445 ///
446 /// let x = 1;
447 /// let thread_x = &x;
448 ///
449 /// let handler = unsafe {
450 /// builder.spawn_unchecked(move || {
451 /// println!("x = {}", *thread_x);
452 /// }).unwrap()
453 /// };
454 ///
455 /// // caller has to ensure `join()` is called, otherwise
456 /// // it is possible to access freed memory if `x` gets
457 /// // dropped before the thread closure is executed!
458 /// handler.join().unwrap();
459 /// ```
460 ///
461 /// [`io::Result`]: crate::io::Result
462 #[stable(feature = "thread_spawn_unchecked", since = "1.82.0")]
463 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
464 pub unsafe fn spawn_unchecked<F, T>(self, f: F) -> io::Result<JoinHandle<T>>
465 where
466 F: FnOnce() -> T,
467 F: Send,
468 T: Send,
469 {
470 Ok(JoinHandle(unsafe { self.spawn_unchecked_(f, None) }?))
471 }
472
473 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
474 unsafe fn spawn_unchecked_<'scope, F, T>(
475 self,
476 f: F,
477 scope_data: Option<Arc<scoped::ScopeData>>,
478 ) -> io::Result<JoinInner<'scope, T>>
479 where
480 F: FnOnce() -> T,
481 F: Send,
482 T: Send,
483 {
484 let Builder { name, stack_size, no_hooks } = self;
485
486 let stack_size = stack_size.unwrap_or_else(|| {
487 static MIN: Atomic<usize> = AtomicUsize::new(0);
488
489 match MIN.load(Ordering::Relaxed) {
490 0 => {}
491 n => return n - 1,
492 }
493
494 let amt = env::var_os("RUST_MIN_STACK")
495 .and_then(|s| s.to_str().and_then(|s| s.parse().ok()))
496 .unwrap_or(imp::DEFAULT_MIN_STACK_SIZE);
497
498 // 0 is our sentinel value, so ensure that we'll never see 0 after
499 // initialization has run
500 MIN.store(amt + 1, Ordering::Relaxed);
501 amt
502 });
503
504 let id = ThreadId::new();
505 let my_thread = Thread::new(id, name);
506
507 let hooks = if no_hooks {
508 spawnhook::ChildSpawnHooks::default()
509 } else {
510 spawnhook::run_spawn_hooks(&my_thread)
511 };
512
513 let their_thread = my_thread.clone();
514
515 let my_packet: Arc<Packet<'scope, T>> = Arc::new(Packet {
516 scope: scope_data,
517 result: UnsafeCell::new(None),
518 _marker: PhantomData,
519 });
520 let their_packet = my_packet.clone();
521
522 // Pass `f` in `MaybeUninit` because actually that closure might *run longer than the lifetime of `F`*.
523 // See <https://github.com/rust-lang/rust/issues/101983> for more details.
524 // To prevent leaks we use a wrapper that drops its contents.
525 #[repr(transparent)]
526 struct MaybeDangling<T>(mem::MaybeUninit<T>);
527 impl<T> MaybeDangling<T> {
528 fn new(x: T) -> Self {
529 MaybeDangling(mem::MaybeUninit::new(x))
530 }
531 fn into_inner(self) -> T {
532 // Make sure we don't drop.
533 let this = ManuallyDrop::new(self);
534 // SAFETY: we are always initialized.
535 unsafe { this.0.assume_init_read() }
536 }
537 }
538 impl<T> Drop for MaybeDangling<T> {
539 fn drop(&mut self) {
540 // SAFETY: we are always initialized.
541 unsafe { self.0.assume_init_drop() };
542 }
543 }
544
545 let f = MaybeDangling::new(f);
546 let main = move || {
547 if let Err(_thread) = set_current(their_thread.clone()) {
548 // Both the current thread handle and the ID should not be
549 // initialized yet. Since only the C runtime and some of our
550 // platform code run before this, this point shouldn't be
551 // reachable. Use an abort to save binary size (see #123356).
552 rtabort!("something here is badly broken!");
553 }
554
555 if let Some(name) = their_thread.cname() {
556 imp::set_name(name);
557 }
558
559 let f = f.into_inner();
560 let try_result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
561 crate::sys::backtrace::__rust_begin_short_backtrace(|| hooks.run());
562 crate::sys::backtrace::__rust_begin_short_backtrace(f)
563 }));
564 // SAFETY: `their_packet` as been built just above and moved by the
565 // closure (it is an Arc<...>) and `my_packet` will be stored in the
566 // same `JoinInner` as this closure meaning the mutation will be
567 // safe (not modify it and affect a value far away).
568 unsafe { *their_packet.result.get() = Some(try_result) };
569 // Here `their_packet` gets dropped, and if this is the last `Arc` for that packet that
570 // will call `decrement_num_running_threads` and therefore signal that this thread is
571 // done.
572 drop(their_packet);
573 // Here, the lifetime `'scope` can end. `main` keeps running for a bit
574 // after that before returning itself.
575 };
576
577 if let Some(scope_data) = &my_packet.scope {
578 scope_data.increment_num_running_threads();
579 }
580
581 let main = Box::new(main);
582 // SAFETY: dynamic size and alignment of the Box remain the same. See below for why the
583 // lifetime change is justified.
584 let main =
585 unsafe { Box::from_raw(Box::into_raw(main) as *mut (dyn FnOnce() + Send + 'static)) };
586
587 Ok(JoinInner {
588 // SAFETY:
589 //
590 // `imp::Thread::new` takes a closure with a `'static` lifetime, since it's passed
591 // through FFI or otherwise used with low-level threading primitives that have no
592 // notion of or way to enforce lifetimes.
593 //
594 // As mentioned in the `Safety` section of this function's documentation, the caller of
595 // this function needs to guarantee that the passed-in lifetime is sufficiently long
596 // for the lifetime of the thread.
597 //
598 // Similarly, the `sys` implementation must guarantee that no references to the closure
599 // exist after the thread has terminated, which is signaled by `Thread::join`
600 // returning.
601 native: unsafe { imp::Thread::new(stack_size, my_thread.name(), main)? },
602 thread: my_thread,
603 packet: my_packet,
604 })
605 }
606}
607
608////////////////////////////////////////////////////////////////////////////////
609// Free functions
610////////////////////////////////////////////////////////////////////////////////
611
612/// Spawns a new thread, returning a [`JoinHandle`] for it.
613///
614/// The join handle provides a [`join`] method that can be used to join the spawned
615/// thread. If the spawned thread panics, [`join`] will return an [`Err`] containing
616/// the argument given to [`panic!`].
617///
618/// If the join handle is dropped, the spawned thread will implicitly be *detached*.
619/// In this case, the spawned thread may no longer be joined.
620/// (It is the responsibility of the program to either eventually join threads it
621/// creates or detach them; otherwise, a resource leak will result.)
622///
623/// This call will create a thread using default parameters of [`Builder`], if you
624/// want to specify the stack size or the name of the thread, use this API
625/// instead.
626///
627/// As you can see in the signature of `spawn` there are two constraints on
628/// both the closure given to `spawn` and its return value, let's explain them:
629///
630/// - The `'static` constraint means that the closure and its return value
631/// must have a lifetime of the whole program execution. The reason for this
632/// is that threads can outlive the lifetime they have been created in.
633///
634/// Indeed if the thread, and by extension its return value, can outlive their
635/// caller, we need to make sure that they will be valid afterwards, and since
636/// we *can't* know when it will return we need to have them valid as long as
637/// possible, that is until the end of the program, hence the `'static`
638/// lifetime.
639/// - The [`Send`] constraint is because the closure will need to be passed
640/// *by value* from the thread where it is spawned to the new thread. Its
641/// return value will need to be passed from the new thread to the thread
642/// where it is `join`ed.
643/// As a reminder, the [`Send`] marker trait expresses that it is safe to be
644/// passed from thread to thread. [`Sync`] expresses that it is safe to have a
645/// reference be passed from thread to thread.
646///
647/// # Panics
648///
649/// Panics if the OS fails to create a thread; use [`Builder::spawn`]
650/// to recover from such errors.
651///
652/// # Examples
653///
654/// Creating a thread.
655///
656/// ```
657/// use std::thread;
658///
659/// let handler = thread::spawn(|| {
660/// // thread code
661/// });
662///
663/// handler.join().unwrap();
664/// ```
665///
666/// As mentioned in the module documentation, threads are usually made to
667/// communicate using [`channels`], here is how it usually looks.
668///
669/// This example also shows how to use `move`, in order to give ownership
670/// of values to a thread.
671///
672/// ```
673/// use std::thread;
674/// use std::sync::mpsc::channel;
675///
676/// let (tx, rx) = channel();
677///
678/// let sender = thread::spawn(move || {
679/// tx.send("Hello, thread".to_owned())
680/// .expect("Unable to send on channel");
681/// });
682///
683/// let receiver = thread::spawn(move || {
684/// let value = rx.recv().expect("Unable to receive from channel");
685/// println!("{value}");
686/// });
687///
688/// sender.join().expect("The sender thread has panicked");
689/// receiver.join().expect("The receiver thread has panicked");
690/// ```
691///
692/// A thread can also return a value through its [`JoinHandle`], you can use
693/// this to make asynchronous computations (futures might be more appropriate
694/// though).
695///
696/// ```
697/// use std::thread;
698///
699/// let computation = thread::spawn(|| {
700/// // Some expensive computation.
701/// 42
702/// });
703///
704/// let result = computation.join().unwrap();
705/// println!("{result}");
706/// ```
707///
708/// # Notes
709///
710/// This function has the same minimal guarantee regarding "foreign" unwinding operations (e.g.
711/// an exception thrown from C++ code, or a `panic!` in Rust code compiled or linked with a
712/// different runtime) as [`catch_unwind`]; namely, if the thread created with `thread::spawn`
713/// unwinds all the way to the root with such an exception, one of two behaviors are possible,
714/// and it is unspecified which will occur:
715///
716/// * The process aborts.
717/// * The process does not abort, and [`join`] will return a `Result::Err`
718/// containing an opaque type.
719///
720/// [`catch_unwind`]: ../../std/panic/fn.catch_unwind.html
721/// [`channels`]: crate::sync::mpsc
722/// [`join`]: JoinHandle::join
723/// [`Err`]: crate::result::Result::Err
724#[stable(feature = "rust1", since = "1.0.0")]
725#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
726pub fn spawn<F, T>(f: F) -> JoinHandle<T>
727where
728 F: FnOnce() -> T,
729 F: Send + 'static,
730 T: Send + 'static,
731{
732 Builder::new().spawn(f).expect("failed to spawn thread")
733}
734
735/// Cooperatively gives up a timeslice to the OS scheduler.
736///
737/// This calls the underlying OS scheduler's yield primitive, signaling
738/// that the calling thread is willing to give up its remaining timeslice
739/// so that the OS may schedule other threads on the CPU.
740///
741/// A drawback of yielding in a loop is that if the OS does not have any
742/// other ready threads to run on the current CPU, the thread will effectively
743/// busy-wait, which wastes CPU time and energy.
744///
745/// Therefore, when waiting for events of interest, a programmer's first
746/// choice should be to use synchronization devices such as [`channel`]s,
747/// [`Condvar`]s, [`Mutex`]es or [`join`] since these primitives are
748/// implemented in a blocking manner, giving up the CPU until the event
749/// of interest has occurred which avoids repeated yielding.
750///
751/// `yield_now` should thus be used only rarely, mostly in situations where
752/// repeated polling is required because there is no other suitable way to
753/// learn when an event of interest has occurred.
754///
755/// # Examples
756///
757/// ```
758/// use std::thread;
759///
760/// thread::yield_now();
761/// ```
762///
763/// [`channel`]: crate::sync::mpsc
764/// [`join`]: JoinHandle::join
765/// [`Condvar`]: crate::sync::Condvar
766/// [`Mutex`]: crate::sync::Mutex
767#[stable(feature = "rust1", since = "1.0.0")]
768pub fn yield_now() {
769 imp::yield_now()
770}
771
772/// Determines whether the current thread is unwinding because of panic.
773///
774/// A common use of this feature is to poison shared resources when writing
775/// unsafe code, by checking `panicking` when the `drop` is called.
776///
777/// This is usually not needed when writing safe code, as [`Mutex`es][Mutex]
778/// already poison themselves when a thread panics while holding the lock.
779///
780/// This can also be used in multithreaded applications, in order to send a
781/// message to other threads warning that a thread has panicked (e.g., for
782/// monitoring purposes).
783///
784/// # Examples
785///
786/// ```should_panic
787/// use std::thread;
788///
789/// struct SomeStruct;
790///
791/// impl Drop for SomeStruct {
792/// fn drop(&mut self) {
793/// if thread::panicking() {
794/// println!("dropped while unwinding");
795/// } else {
796/// println!("dropped while not unwinding");
797/// }
798/// }
799/// }
800///
801/// {
802/// print!("a: ");
803/// let a = SomeStruct;
804/// }
805///
806/// {
807/// print!("b: ");
808/// let b = SomeStruct;
809/// panic!()
810/// }
811/// ```
812///
813/// [Mutex]: crate::sync::Mutex
814#[inline]
815#[must_use]
816#[stable(feature = "rust1", since = "1.0.0")]
817pub fn panicking() -> bool {
818 panicking::panicking()
819}
820
821/// Uses [`sleep`].
822///
823/// Puts the current thread to sleep for at least the specified amount of time.
824///
825/// The thread may sleep longer than the duration specified due to scheduling
826/// specifics or platform-dependent functionality. It will never sleep less.
827///
828/// This function is blocking, and should not be used in `async` functions.
829///
830/// # Platform-specific behavior
831///
832/// On Unix platforms, the underlying syscall may be interrupted by a
833/// spurious wakeup or signal handler. To ensure the sleep occurs for at least
834/// the specified duration, this function may invoke that system call multiple
835/// times.
836///
837/// # Examples
838///
839/// ```no_run
840/// use std::thread;
841///
842/// // Let's sleep for 2 seconds:
843/// thread::sleep_ms(2000);
844/// ```
845#[stable(feature = "rust1", since = "1.0.0")]
846#[deprecated(since = "1.6.0", note = "replaced by `std::thread::sleep`")]
847pub fn sleep_ms(ms: u32) {
848 sleep(Duration::from_millis(ms as u64))
849}
850
851/// Puts the current thread to sleep for at least the specified amount of time.
852///
853/// The thread may sleep longer than the duration specified due to scheduling
854/// specifics or platform-dependent functionality. It will never sleep less.
855///
856/// This function is blocking, and should not be used in `async` functions.
857///
858/// # Platform-specific behavior
859///
860/// On Unix platforms, the underlying syscall may be interrupted by a
861/// spurious wakeup or signal handler. To ensure the sleep occurs for at least
862/// the specified duration, this function may invoke that system call multiple
863/// times.
864/// Platforms which do not support nanosecond precision for sleeping will
865/// have `dur` rounded up to the nearest granularity of time they can sleep for.
866///
867/// Currently, specifying a zero duration on Unix platforms returns immediately
868/// without invoking the underlying [`nanosleep`] syscall, whereas on Windows
869/// platforms the underlying [`Sleep`] syscall is always invoked.
870/// If the intention is to yield the current time-slice you may want to use
871/// [`yield_now`] instead.
872///
873/// [`nanosleep`]: https://linux.die.net/man/2/nanosleep
874/// [`Sleep`]: https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-sleep
875///
876/// # Examples
877///
878/// ```no_run
879/// use std::{thread, time};
880///
881/// let ten_millis = time::Duration::from_millis(10);
882/// let now = time::Instant::now();
883///
884/// thread::sleep(ten_millis);
885///
886/// assert!(now.elapsed() >= ten_millis);
887/// ```
888#[stable(feature = "thread_sleep", since = "1.4.0")]
889pub fn sleep(dur: Duration) {
890 imp::sleep(dur)
891}
892
893/// Puts the current thread to sleep until the specified deadline has passed.
894///
895/// The thread may still be asleep after the deadline specified due to
896/// scheduling specifics or platform-dependent functionality. It will never
897/// wake before.
898///
899/// This function is blocking, and should not be used in `async` functions.
900///
901/// # Platform-specific behavior
902///
903/// In most cases this function will call an OS specific function. Where that
904/// is not supported [`sleep`] is used. Those platforms are referred to as other
905/// in the table below.
906///
907/// # Underlying System calls
908///
909/// The following system calls are [currently] being used:
910///
911/// | Platform | System call |
912/// |-----------|----------------------------------------------------------------------|
913/// | Linux | [clock_nanosleep] (Monotonic clock) |
914/// | BSD except OpenBSD | [clock_nanosleep] (Monotonic Clock)] |
915/// | Android | [clock_nanosleep] (Monotonic Clock)] |
916/// | Solaris | [clock_nanosleep] (Monotonic Clock)] |
917/// | Illumos | [clock_nanosleep] (Monotonic Clock)] |
918/// | Dragonfly | [clock_nanosleep] (Monotonic Clock)] |
919/// | Hurd | [clock_nanosleep] (Monotonic Clock)] |
920/// | Fuchsia | [clock_nanosleep] (Monotonic Clock)] |
921/// | Vxworks | [clock_nanosleep] (Monotonic Clock)] |
922/// | Other | `sleep_until` uses [`sleep`] and does not issue a syscall itself |
923///
924/// [currently]: crate::io#platform-specific-behavior
925/// [clock_nanosleep]: https://linux.die.net/man/3/clock_nanosleep
926///
927/// **Disclaimer:** These system calls might change over time.
928///
929/// # Examples
930///
931/// A simple game loop that limits the game to 60 frames per second.
932///
933/// ```no_run
934/// #![feature(thread_sleep_until)]
935/// # use std::time::{Duration, Instant};
936/// # use std::thread;
937/// #
938/// # fn update() {}
939/// # fn render() {}
940/// #
941/// let max_fps = 60.0;
942/// let frame_time = Duration::from_secs_f32(1.0/max_fps);
943/// let mut next_frame = Instant::now();
944/// loop {
945/// thread::sleep_until(next_frame);
946/// next_frame += frame_time;
947/// update();
948/// render();
949/// }
950/// ```
951///
952/// A slow API we must not call too fast and which takes a few
953/// tries before succeeding. By using `sleep_until` the time the
954/// API call takes does not influence when we retry or when we give up
955///
956/// ```no_run
957/// #![feature(thread_sleep_until)]
958/// # use std::time::{Duration, Instant};
959/// # use std::thread;
960/// #
961/// # enum Status {
962/// # Ready(usize),
963/// # Waiting,
964/// # }
965/// # fn slow_web_api_call() -> Status { Status::Ready(42) }
966/// #
967/// # const MAX_DURATION: Duration = Duration::from_secs(10);
968/// #
969/// # fn try_api_call() -> Result<usize, ()> {
970/// let deadline = Instant::now() + MAX_DURATION;
971/// let delay = Duration::from_millis(250);
972/// let mut next_attempt = Instant::now();
973/// loop {
974/// if Instant::now() > deadline {
975/// break Err(());
976/// }
977/// if let Status::Ready(data) = slow_web_api_call() {
978/// break Ok(data);
979/// }
980///
981/// next_attempt = deadline.min(next_attempt + delay);
982/// thread::sleep_until(next_attempt);
983/// }
984/// # }
985/// # let _data = try_api_call();
986/// ```
987#[unstable(feature = "thread_sleep_until", issue = "113752")]
988pub fn sleep_until(deadline: Instant) {
989 imp::sleep_until(deadline)
990}
991
992/// Used to ensure that `park` and `park_timeout` do not unwind, as that can
993/// cause undefined behavior if not handled correctly (see #102398 for context).
994struct PanicGuard;
995
996impl Drop for PanicGuard {
997 fn drop(&mut self) {
998 rtabort!("an irrecoverable error occurred while synchronizing threads")
999 }
1000}
1001
1002/// Blocks unless or until the current thread's token is made available.
1003///
1004/// A call to `park` does not guarantee that the thread will remain parked
1005/// forever, and callers should be prepared for this possibility. However,
1006/// it is guaranteed that this function will not panic (it may abort the
1007/// process if the implementation encounters some rare errors).
1008///
1009/// # `park` and `unpark`
1010///
1011/// Every thread is equipped with some basic low-level blocking support, via the
1012/// [`thread::park`][`park`] function and [`thread::Thread::unpark`][`unpark`]
1013/// method. [`park`] blocks the current thread, which can then be resumed from
1014/// another thread by calling the [`unpark`] method on the blocked thread's
1015/// handle.
1016///
1017/// Conceptually, each [`Thread`] handle has an associated token, which is
1018/// initially not present:
1019///
1020/// * The [`thread::park`][`park`] function blocks the current thread unless or
1021/// until the token is available for its thread handle, at which point it
1022/// atomically consumes the token. It may also return *spuriously*, without
1023/// consuming the token. [`thread::park_timeout`] does the same, but allows
1024/// specifying a maximum time to block the thread for.
1025///
1026/// * The [`unpark`] method on a [`Thread`] atomically makes the token available
1027/// if it wasn't already. Because the token can be held by a thread even if it is currently not
1028/// parked, [`unpark`] followed by [`park`] will result in the second call returning immediately.
1029/// However, note that to rely on this guarantee, you need to make sure that your `unpark` happens
1030/// after all `park` that may be done by other data structures!
1031///
1032/// The API is typically used by acquiring a handle to the current thread, placing that handle in a
1033/// shared data structure so that other threads can find it, and then `park`ing in a loop. When some
1034/// desired condition is met, another thread calls [`unpark`] on the handle. The last bullet point
1035/// above guarantees that even if the `unpark` occurs before the thread is finished `park`ing, it
1036/// will be woken up properly.
1037///
1038/// Note that the coordination via the shared data structure is crucial: If you `unpark` a thread
1039/// without first establishing that it is about to be `park`ing within your code, that `unpark` may
1040/// get consumed by a *different* `park` in the same thread, leading to a deadlock. This also means
1041/// you must not call unknown code between setting up for parking and calling `park`; for instance,
1042/// if you invoke `println!`, that may itself call `park` and thus consume your `unpark` and cause a
1043/// deadlock.
1044///
1045/// The motivation for this design is twofold:
1046///
1047/// * It avoids the need to allocate mutexes and condvars when building new
1048/// synchronization primitives; the threads already provide basic
1049/// blocking/signaling.
1050///
1051/// * It can be implemented very efficiently on many platforms.
1052///
1053/// # Memory Ordering
1054///
1055/// Calls to `unpark` _synchronize-with_ calls to `park`, meaning that memory
1056/// operations performed before a call to `unpark` are made visible to the thread that
1057/// consumes the token and returns from `park`. Note that all `park` and `unpark`
1058/// operations for a given thread form a total order and _all_ prior `unpark` operations
1059/// synchronize-with `park`.
1060///
1061/// In atomic ordering terms, `unpark` performs a `Release` operation and `park`
1062/// performs the corresponding `Acquire` operation. Calls to `unpark` for the same
1063/// thread form a [release sequence].
1064///
1065/// Note that being unblocked does not imply a call was made to `unpark`, because
1066/// wakeups can also be spurious. For example, a valid, but inefficient,
1067/// implementation could have `park` and `unpark` return immediately without doing anything,
1068/// making *all* wakeups spurious.
1069///
1070/// # Examples
1071///
1072/// ```
1073/// use std::thread;
1074/// use std::sync::atomic::{Ordering, AtomicBool};
1075/// use std::time::Duration;
1076///
1077/// static QUEUED: AtomicBool = AtomicBool::new(false);
1078/// static FLAG: AtomicBool = AtomicBool::new(false);
1079///
1080/// let parked_thread = thread::spawn(move || {
1081/// println!("Thread spawned");
1082/// // Signal that we are going to `park`. Between this store and our `park`, there may
1083/// // be no other `park`, or else that `park` could consume our `unpark` token!
1084/// QUEUED.store(true, Ordering::Release);
1085/// // We want to wait until the flag is set. We *could* just spin, but using
1086/// // park/unpark is more efficient.
1087/// while !FLAG.load(Ordering::Acquire) {
1088/// // We can *not* use `println!` here since that could use thread parking internally.
1089/// thread::park();
1090/// // We *could* get here spuriously, i.e., way before the 10ms below are over!
1091/// // But that is no problem, we are in a loop until the flag is set anyway.
1092/// }
1093/// println!("Flag received");
1094/// });
1095///
1096/// // Let some time pass for the thread to be spawned.
1097/// thread::sleep(Duration::from_millis(10));
1098///
1099/// // Ensure the thread is about to park.
1100/// // This is crucial! It guarantees that the `unpark` below is not consumed
1101/// // by some other code in the parked thread (e.g. inside `println!`).
1102/// while !QUEUED.load(Ordering::Acquire) {
1103/// // Spinning is of course inefficient; in practice, this would more likely be
1104/// // a dequeue where we have no work to do if there's nobody queued.
1105/// std::hint::spin_loop();
1106/// }
1107///
1108/// // Set the flag, and let the thread wake up.
1109/// // There is no race condition here: if `unpark`
1110/// // happens first, `park` will return immediately.
1111/// // There is also no other `park` that could consume this token,
1112/// // since we waited until the other thread got queued.
1113/// // Hence there is no risk of a deadlock.
1114/// FLAG.store(true, Ordering::Release);
1115/// println!("Unpark the thread");
1116/// parked_thread.thread().unpark();
1117///
1118/// parked_thread.join().unwrap();
1119/// ```
1120///
1121/// [`unpark`]: Thread::unpark
1122/// [`thread::park_timeout`]: park_timeout
1123/// [release sequence]: https://en.cppreference.com/w/cpp/atomic/memory_order#Release_sequence
1124#[stable(feature = "rust1", since = "1.0.0")]
1125pub fn park() {
1126 let guard = PanicGuard;
1127 // SAFETY: park_timeout is called on the parker owned by this thread.
1128 unsafe {
1129 current().park();
1130 }
1131 // No panic occurred, do not abort.
1132 forget(guard);
1133}
1134
1135/// Uses [`park_timeout`].
1136///
1137/// Blocks unless or until the current thread's token is made available or
1138/// the specified duration has been reached (may wake spuriously).
1139///
1140/// The semantics of this function are equivalent to [`park`] except
1141/// that the thread will be blocked for roughly no longer than `dur`. This
1142/// method should not be used for precise timing due to anomalies such as
1143/// preemption or platform differences that might not cause the maximum
1144/// amount of time waited to be precisely `ms` long.
1145///
1146/// See the [park documentation][`park`] for more detail.
1147#[stable(feature = "rust1", since = "1.0.0")]
1148#[deprecated(since = "1.6.0", note = "replaced by `std::thread::park_timeout`")]
1149pub fn park_timeout_ms(ms: u32) {
1150 park_timeout(Duration::from_millis(ms as u64))
1151}
1152
1153/// Blocks unless or until the current thread's token is made available or
1154/// the specified duration has been reached (may wake spuriously).
1155///
1156/// The semantics of this function are equivalent to [`park`][park] except
1157/// that the thread will be blocked for roughly no longer than `dur`. This
1158/// method should not be used for precise timing due to anomalies such as
1159/// preemption or platform differences that might not cause the maximum
1160/// amount of time waited to be precisely `dur` long.
1161///
1162/// See the [park documentation][park] for more details.
1163///
1164/// # Platform-specific behavior
1165///
1166/// Platforms which do not support nanosecond precision for sleeping will have
1167/// `dur` rounded up to the nearest granularity of time they can sleep for.
1168///
1169/// # Examples
1170///
1171/// Waiting for the complete expiration of the timeout:
1172///
1173/// ```rust,no_run
1174/// use std::thread::park_timeout;
1175/// use std::time::{Instant, Duration};
1176///
1177/// let timeout = Duration::from_secs(2);
1178/// let beginning_park = Instant::now();
1179///
1180/// let mut timeout_remaining = timeout;
1181/// loop {
1182/// park_timeout(timeout_remaining);
1183/// let elapsed = beginning_park.elapsed();
1184/// if elapsed >= timeout {
1185/// break;
1186/// }
1187/// println!("restarting park_timeout after {elapsed:?}");
1188/// timeout_remaining = timeout - elapsed;
1189/// }
1190/// ```
1191#[stable(feature = "park_timeout", since = "1.4.0")]
1192pub fn park_timeout(dur: Duration) {
1193 let guard = PanicGuard;
1194 // SAFETY: park_timeout is called on a handle owned by this thread.
1195 unsafe {
1196 current().park_timeout(dur);
1197 }
1198 // No panic occurred, do not abort.
1199 forget(guard);
1200}
1201
1202////////////////////////////////////////////////////////////////////////////////
1203// ThreadId
1204////////////////////////////////////////////////////////////////////////////////
1205
1206/// A unique identifier for a running thread.
1207///
1208/// A `ThreadId` is an opaque object that uniquely identifies each thread
1209/// created during the lifetime of a process. `ThreadId`s are guaranteed not to
1210/// be reused, even when a thread terminates. `ThreadId`s are under the control
1211/// of Rust's standard library and there may not be any relationship between
1212/// `ThreadId` and the underlying platform's notion of a thread identifier --
1213/// the two concepts cannot, therefore, be used interchangeably. A `ThreadId`
1214/// can be retrieved from the [`id`] method on a [`Thread`].
1215///
1216/// # Examples
1217///
1218/// ```
1219/// use std::thread;
1220///
1221/// let other_thread = thread::spawn(|| {
1222/// thread::current().id()
1223/// });
1224///
1225/// let other_thread_id = other_thread.join().unwrap();
1226/// assert!(thread::current().id() != other_thread_id);
1227/// ```
1228///
1229/// [`id`]: Thread::id
1230#[stable(feature = "thread_id", since = "1.19.0")]
1231#[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
1232pub struct ThreadId(NonZero<u64>);
1233
1234impl ThreadId {
1235 // Generate a new unique thread ID.
1236 pub(crate) fn new() -> ThreadId {
1237 #[cold]
1238 fn exhausted() -> ! {
1239 panic!("failed to generate unique thread ID: bitspace exhausted")
1240 }
1241
1242 cfg_select! {
1243 target_has_atomic = "64" => {
1244 use crate::sync::atomic::{Atomic, AtomicU64};
1245
1246 static COUNTER: Atomic<u64> = AtomicU64::new(0);
1247
1248 let mut last = COUNTER.load(Ordering::Relaxed);
1249 loop {
1250 let Some(id) = last.checked_add(1) else {
1251 exhausted();
1252 };
1253
1254 match COUNTER.compare_exchange_weak(last, id, Ordering::Relaxed, Ordering::Relaxed) {
1255 Ok(_) => return ThreadId(NonZero::new(id).unwrap()),
1256 Err(id) => last = id,
1257 }
1258 }
1259 }
1260 _ => {
1261 use crate::sync::{Mutex, PoisonError};
1262
1263 static COUNTER: Mutex<u64> = Mutex::new(0);
1264
1265 let mut counter = COUNTER.lock().unwrap_or_else(PoisonError::into_inner);
1266 let Some(id) = counter.checked_add(1) else {
1267 // in case the panic handler ends up calling `ThreadId::new()`,
1268 // avoid reentrant lock acquire.
1269 drop(counter);
1270 exhausted();
1271 };
1272
1273 *counter = id;
1274 drop(counter);
1275 ThreadId(NonZero::new(id).unwrap())
1276 }
1277 }
1278 }
1279
1280 #[cfg(any(not(target_thread_local), target_has_atomic = "64"))]
1281 fn from_u64(v: u64) -> Option<ThreadId> {
1282 NonZero::new(v).map(ThreadId)
1283 }
1284
1285 /// This returns a numeric identifier for the thread identified by this
1286 /// `ThreadId`.
1287 ///
1288 /// As noted in the documentation for the type itself, it is essentially an
1289 /// opaque ID, but is guaranteed to be unique for each thread. The returned
1290 /// value is entirely opaque -- only equality testing is stable. Note that
1291 /// it is not guaranteed which values new threads will return, and this may
1292 /// change across Rust versions.
1293 #[must_use]
1294 #[unstable(feature = "thread_id_value", issue = "67939")]
1295 pub fn as_u64(&self) -> NonZero<u64> {
1296 self.0
1297 }
1298}
1299
1300////////////////////////////////////////////////////////////////////////////////
1301// Thread
1302////////////////////////////////////////////////////////////////////////////////
1303
1304// This module ensures private fields are kept private, which is necessary to enforce the safety requirements.
1305mod thread_name_string {
1306 use crate::ffi::{CStr, CString};
1307 use crate::str;
1308
1309 /// Like a `String` it's guaranteed UTF-8 and like a `CString` it's null terminated.
1310 pub(crate) struct ThreadNameString {
1311 inner: CString,
1312 }
1313
1314 impl From<String> for ThreadNameString {
1315 fn from(s: String) -> Self {
1316 Self {
1317 inner: CString::new(s).expect("thread name may not contain interior null bytes"),
1318 }
1319 }
1320 }
1321
1322 impl ThreadNameString {
1323 pub fn as_cstr(&self) -> &CStr {
1324 &self.inner
1325 }
1326
1327 pub fn as_str(&self) -> &str {
1328 // SAFETY: `ThreadNameString` is guaranteed to be UTF-8.
1329 unsafe { str::from_utf8_unchecked(self.inner.to_bytes()) }
1330 }
1331 }
1332}
1333
1334use thread_name_string::ThreadNameString;
1335
1336/// Store the ID of the main thread.
1337///
1338/// The thread handle for the main thread is created lazily, and this might even
1339/// happen pre-main. Since not every platform has a way to identify the main
1340/// thread when that happens – macOS's `pthread_main_np` function being a notable
1341/// exception – we cannot assign it the right name right then. Instead, in our
1342/// runtime startup code, we remember the thread ID of the main thread (through
1343/// this modules `set` function) and use it to identify the main thread from then
1344/// on. This works reliably and has the additional advantage that we can report
1345/// the right thread name on main even after the thread handle has been destroyed.
1346/// Note however that this also means that the name reported in pre-main functions
1347/// will be incorrect, but that's just something we have to live with.
1348pub(crate) mod main_thread {
1349 cfg_select! {
1350 target_has_atomic = "64" => {
1351 use super::ThreadId;
1352 use crate::sync::atomic::{Atomic, AtomicU64};
1353 use crate::sync::atomic::Ordering::Relaxed;
1354
1355 static MAIN: Atomic<u64> = AtomicU64::new(0);
1356
1357 pub(super) fn get() -> Option<ThreadId> {
1358 ThreadId::from_u64(MAIN.load(Relaxed))
1359 }
1360
1361 /// # Safety
1362 /// May only be called once.
1363 pub(crate) unsafe fn set(id: ThreadId) {
1364 MAIN.store(id.as_u64().get(), Relaxed)
1365 }
1366 }
1367 _ => {
1368 use super::ThreadId;
1369 use crate::mem::MaybeUninit;
1370 use crate::sync::atomic::{Atomic, AtomicBool};
1371 use crate::sync::atomic::Ordering::{Acquire, Release};
1372
1373 static INIT: Atomic<bool> = AtomicBool::new(false);
1374 static mut MAIN: MaybeUninit<ThreadId> = MaybeUninit::uninit();
1375
1376 pub(super) fn get() -> Option<ThreadId> {
1377 if INIT.load(Acquire) {
1378 Some(unsafe { MAIN.assume_init() })
1379 } else {
1380 None
1381 }
1382 }
1383
1384 /// # Safety
1385 /// May only be called once.
1386 pub(crate) unsafe fn set(id: ThreadId) {
1387 unsafe { MAIN = MaybeUninit::new(id) };
1388 INIT.store(true, Release);
1389 }
1390 }
1391 }
1392}
1393
1394/// Run a function with the current thread's name.
1395///
1396/// Modulo thread local accesses, this function is safe to call from signal
1397/// handlers and in similar circumstances where allocations are not possible.
1398pub(crate) fn with_current_name<F, R>(f: F) -> R
1399where
1400 F: FnOnce(Option<&str>) -> R,
1401{
1402 try_with_current(|thread| {
1403 if let Some(thread) = thread {
1404 // If there is a current thread handle, try to use the name stored
1405 // there.
1406 if let Some(name) = &thread.inner.name {
1407 return f(Some(name.as_str()));
1408 } else if Some(thread.inner.id) == main_thread::get() {
1409 // The main thread doesn't store its name in the handle, we must
1410 // identify it through its ID. Since we already have the `Thread`,
1411 // we can retrieve the ID from it instead of going through another
1412 // thread local.
1413 return f(Some("main"));
1414 }
1415 } else if let Some(main) = main_thread::get()
1416 && let Some(id) = current::id::get()
1417 && id == main
1418 {
1419 // The main thread doesn't always have a thread handle, we must
1420 // identify it through its ID instead. The checks are ordered so
1421 // that the current ID is only loaded if it is actually needed,
1422 // since loading it from TLS might need multiple expensive accesses.
1423 return f(Some("main"));
1424 }
1425
1426 f(None)
1427 })
1428}
1429
1430/// The internal representation of a `Thread` handle
1431///
1432/// We explicitly set the alignment for our guarantee in Thread::into_raw. This
1433/// allows applications to stuff extra metadata bits into the alignment, which
1434/// can be rather useful when working with atomics.
1435#[repr(align(8))]
1436struct Inner {
1437 name: Option<ThreadNameString>,
1438 id: ThreadId,
1439 parker: Parker,
1440}
1441
1442impl Inner {
1443 fn parker(self: Pin<&Self>) -> Pin<&Parker> {
1444 unsafe { Pin::map_unchecked(self, |inner| &inner.parker) }
1445 }
1446}
1447
1448#[derive(Clone)]
1449#[stable(feature = "rust1", since = "1.0.0")]
1450/// A handle to a thread.
1451///
1452/// Threads are represented via the `Thread` type, which you can get in one of
1453/// two ways:
1454///
1455/// * By spawning a new thread, e.g., using the [`thread::spawn`][`spawn`]
1456/// function, and calling [`thread`][`JoinHandle::thread`] on the
1457/// [`JoinHandle`].
1458/// * By requesting the current thread, using the [`thread::current`] function.
1459///
1460/// The [`thread::current`] function is available even for threads not spawned
1461/// by the APIs of this module.
1462///
1463/// There is usually no need to create a `Thread` struct yourself, one
1464/// should instead use a function like `spawn` to create new threads, see the
1465/// docs of [`Builder`] and [`spawn`] for more details.
1466///
1467/// [`thread::current`]: current::current
1468pub struct Thread {
1469 inner: Pin<Arc<Inner>>,
1470}
1471
1472impl Thread {
1473 pub(crate) fn new(id: ThreadId, name: Option<String>) -> Thread {
1474 let name = name.map(ThreadNameString::from);
1475
1476 // We have to use `unsafe` here to construct the `Parker` in-place,
1477 // which is required for the UNIX implementation.
1478 //
1479 // SAFETY: We pin the Arc immediately after creation, so its address never
1480 // changes.
1481 let inner = unsafe {
1482 let mut arc = Arc::<Inner>::new_uninit();
1483 let ptr = Arc::get_mut_unchecked(&mut arc).as_mut_ptr();
1484 (&raw mut (*ptr).name).write(name);
1485 (&raw mut (*ptr).id).write(id);
1486 Parker::new_in_place(&raw mut (*ptr).parker);
1487 Pin::new_unchecked(arc.assume_init())
1488 };
1489
1490 Thread { inner }
1491 }
1492
1493 /// Like the public [`park`], but callable on any handle. This is used to
1494 /// allow parking in TLS destructors.
1495 ///
1496 /// # Safety
1497 /// May only be called from the thread to which this handle belongs.
1498 pub(crate) unsafe fn park(&self) {
1499 unsafe { self.inner.as_ref().parker().park() }
1500 }
1501
1502 /// Like the public [`park_timeout`], but callable on any handle. This is
1503 /// used to allow parking in TLS destructors.
1504 ///
1505 /// # Safety
1506 /// May only be called from the thread to which this handle belongs.
1507 pub(crate) unsafe fn park_timeout(&self, dur: Duration) {
1508 unsafe { self.inner.as_ref().parker().park_timeout(dur) }
1509 }
1510
1511 /// Atomically makes the handle's token available if it is not already.
1512 ///
1513 /// Every thread is equipped with some basic low-level blocking support, via
1514 /// the [`park`][park] function and the `unpark()` method. These can be
1515 /// used as a more CPU-efficient implementation of a spinlock.
1516 ///
1517 /// See the [park documentation][park] for more details.
1518 ///
1519 /// # Examples
1520 ///
1521 /// ```
1522 /// use std::thread;
1523 /// use std::time::Duration;
1524 /// use std::sync::atomic::{AtomicBool, Ordering};
1525 ///
1526 /// static QUEUED: AtomicBool = AtomicBool::new(false);
1527 ///
1528 /// let parked_thread = thread::Builder::new()
1529 /// .spawn(|| {
1530 /// println!("Parking thread");
1531 /// QUEUED.store(true, Ordering::Release);
1532 /// thread::park();
1533 /// println!("Thread unparked");
1534 /// })
1535 /// .unwrap();
1536 ///
1537 /// // Let some time pass for the thread to be spawned.
1538 /// thread::sleep(Duration::from_millis(10));
1539 ///
1540 /// // Wait until the other thread is queued.
1541 /// // This is crucial! It guarantees that the `unpark` below is not consumed
1542 /// // by some other code in the parked thread (e.g. inside `println!`).
1543 /// while !QUEUED.load(Ordering::Acquire) {
1544 /// // Spinning is of course inefficient; in practice, this would more likely be
1545 /// // a dequeue where we have no work to do if there's nobody queued.
1546 /// std::hint::spin_loop();
1547 /// }
1548 ///
1549 /// println!("Unpark the thread");
1550 /// parked_thread.thread().unpark();
1551 ///
1552 /// parked_thread.join().unwrap();
1553 /// ```
1554 #[stable(feature = "rust1", since = "1.0.0")]
1555 #[inline]
1556 pub fn unpark(&self) {
1557 self.inner.as_ref().parker().unpark();
1558 }
1559
1560 /// Gets the thread's unique identifier.
1561 ///
1562 /// # Examples
1563 ///
1564 /// ```
1565 /// use std::thread;
1566 ///
1567 /// let other_thread = thread::spawn(|| {
1568 /// thread::current().id()
1569 /// });
1570 ///
1571 /// let other_thread_id = other_thread.join().unwrap();
1572 /// assert!(thread::current().id() != other_thread_id);
1573 /// ```
1574 #[stable(feature = "thread_id", since = "1.19.0")]
1575 #[must_use]
1576 pub fn id(&self) -> ThreadId {
1577 self.inner.id
1578 }
1579
1580 /// Gets the thread's name.
1581 ///
1582 /// For more information about named threads, see
1583 /// [this module-level documentation][naming-threads].
1584 ///
1585 /// # Examples
1586 ///
1587 /// Threads by default have no name specified:
1588 ///
1589 /// ```
1590 /// use std::thread;
1591 ///
1592 /// let builder = thread::Builder::new();
1593 ///
1594 /// let handler = builder.spawn(|| {
1595 /// assert!(thread::current().name().is_none());
1596 /// }).unwrap();
1597 ///
1598 /// handler.join().unwrap();
1599 /// ```
1600 ///
1601 /// Thread with a specified name:
1602 ///
1603 /// ```
1604 /// use std::thread;
1605 ///
1606 /// let builder = thread::Builder::new()
1607 /// .name("foo".into());
1608 ///
1609 /// let handler = builder.spawn(|| {
1610 /// assert_eq!(thread::current().name(), Some("foo"))
1611 /// }).unwrap();
1612 ///
1613 /// handler.join().unwrap();
1614 /// ```
1615 ///
1616 /// [naming-threads]: ./index.html#naming-threads
1617 #[stable(feature = "rust1", since = "1.0.0")]
1618 #[must_use]
1619 pub fn name(&self) -> Option<&str> {
1620 if let Some(name) = &self.inner.name {
1621 Some(name.as_str())
1622 } else if main_thread::get() == Some(self.inner.id) {
1623 Some("main")
1624 } else {
1625 None
1626 }
1627 }
1628
1629 /// Consumes the `Thread`, returning a raw pointer.
1630 ///
1631 /// To avoid a memory leak the pointer must be converted
1632 /// back into a `Thread` using [`Thread::from_raw`]. The pointer is
1633 /// guaranteed to be aligned to at least 8 bytes.
1634 ///
1635 /// # Examples
1636 ///
1637 /// ```
1638 /// #![feature(thread_raw)]
1639 ///
1640 /// use std::thread::{self, Thread};
1641 ///
1642 /// let thread = thread::current();
1643 /// let id = thread.id();
1644 /// let ptr = Thread::into_raw(thread);
1645 /// unsafe {
1646 /// assert_eq!(Thread::from_raw(ptr).id(), id);
1647 /// }
1648 /// ```
1649 #[unstable(feature = "thread_raw", issue = "97523")]
1650 pub fn into_raw(self) -> *const () {
1651 // Safety: We only expose an opaque pointer, which maintains the `Pin` invariant.
1652 let inner = unsafe { Pin::into_inner_unchecked(self.inner) };
1653 Arc::into_raw(inner) as *const ()
1654 }
1655
1656 /// Constructs a `Thread` from a raw pointer.
1657 ///
1658 /// The raw pointer must have been previously returned
1659 /// by a call to [`Thread::into_raw`].
1660 ///
1661 /// # Safety
1662 ///
1663 /// This function is unsafe because improper use may lead
1664 /// to memory unsafety, even if the returned `Thread` is never
1665 /// accessed.
1666 ///
1667 /// Creating a `Thread` from a pointer other than one returned
1668 /// from [`Thread::into_raw`] is **undefined behavior**.
1669 ///
1670 /// Calling this function twice on the same raw pointer can lead
1671 /// to a double-free if both `Thread` instances are dropped.
1672 #[unstable(feature = "thread_raw", issue = "97523")]
1673 pub unsafe fn from_raw(ptr: *const ()) -> Thread {
1674 // Safety: Upheld by caller.
1675 unsafe { Thread { inner: Pin::new_unchecked(Arc::from_raw(ptr as *const Inner)) } }
1676 }
1677
1678 fn cname(&self) -> Option<&CStr> {
1679 if let Some(name) = &self.inner.name {
1680 Some(name.as_cstr())
1681 } else if main_thread::get() == Some(self.inner.id) {
1682 Some(c"main")
1683 } else {
1684 None
1685 }
1686 }
1687}
1688
1689#[stable(feature = "rust1", since = "1.0.0")]
1690impl fmt::Debug for Thread {
1691 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1692 f.debug_struct("Thread")
1693 .field("id", &self.id())
1694 .field("name", &self.name())
1695 .finish_non_exhaustive()
1696 }
1697}
1698
1699////////////////////////////////////////////////////////////////////////////////
1700// JoinHandle
1701////////////////////////////////////////////////////////////////////////////////
1702
1703/// A specialized [`Result`] type for threads.
1704///
1705/// Indicates the manner in which a thread exited.
1706///
1707/// The value contained in the `Result::Err` variant
1708/// is the value the thread panicked with;
1709/// that is, the argument the `panic!` macro was called with.
1710/// Unlike with normal errors, this value doesn't implement
1711/// the [`Error`](crate::error::Error) trait.
1712///
1713/// Thus, a sensible way to handle a thread panic is to either:
1714///
1715/// 1. propagate the panic with [`std::panic::resume_unwind`]
1716/// 2. or in case the thread is intended to be a subsystem boundary
1717/// that is supposed to isolate system-level failures,
1718/// match on the `Err` variant and handle the panic in an appropriate way
1719///
1720/// A thread that completes without panicking is considered to exit successfully.
1721///
1722/// # Examples
1723///
1724/// Matching on the result of a joined thread:
1725///
1726/// ```no_run
1727/// use std::{fs, thread, panic};
1728///
1729/// fn copy_in_thread() -> thread::Result<()> {
1730/// thread::spawn(|| {
1731/// fs::copy("foo.txt", "bar.txt").unwrap();
1732/// }).join()
1733/// }
1734///
1735/// fn main() {
1736/// match copy_in_thread() {
1737/// Ok(_) => println!("copy succeeded"),
1738/// Err(e) => panic::resume_unwind(e),
1739/// }
1740/// }
1741/// ```
1742///
1743/// [`Result`]: crate::result::Result
1744/// [`std::panic::resume_unwind`]: crate::panic::resume_unwind
1745#[stable(feature = "rust1", since = "1.0.0")]
1746#[doc(search_unbox)]
1747pub type Result<T> = crate::result::Result<T, Box<dyn Any + Send + 'static>>;
1748
1749// This packet is used to communicate the return value between the spawned
1750// thread and the rest of the program. It is shared through an `Arc` and
1751// there's no need for a mutex here because synchronization happens with `join()`
1752// (the caller will never read this packet until the thread has exited).
1753//
1754// An Arc to the packet is stored into a `JoinInner` which in turns is placed
1755// in `JoinHandle`.
1756struct Packet<'scope, T> {
1757 scope: Option<Arc<scoped::ScopeData>>,
1758 result: UnsafeCell<Option<Result<T>>>,
1759 _marker: PhantomData<Option<&'scope scoped::ScopeData>>,
1760}
1761
1762// Due to the usage of `UnsafeCell` we need to manually implement Sync.
1763// The type `T` should already always be Send (otherwise the thread could not
1764// have been created) and the Packet is Sync because all access to the
1765// `UnsafeCell` synchronized (by the `join()` boundary), and `ScopeData` is Sync.
1766unsafe impl<'scope, T: Send> Sync for Packet<'scope, T> {}
1767
1768impl<'scope, T> Drop for Packet<'scope, T> {
1769 fn drop(&mut self) {
1770 // If this packet was for a thread that ran in a scope, the thread
1771 // panicked, and nobody consumed the panic payload, we make sure
1772 // the scope function will panic.
1773 let unhandled_panic = matches!(self.result.get_mut(), Some(Err(_)));
1774 // Drop the result without causing unwinding.
1775 // This is only relevant for threads that aren't join()ed, as
1776 // join() will take the `result` and set it to None, such that
1777 // there is nothing left to drop here.
1778 // If this panics, we should handle that, because we're outside the
1779 // outermost `catch_unwind` of our thread.
1780 // We just abort in that case, since there's nothing else we can do.
1781 // (And even if we tried to handle it somehow, we'd also need to handle
1782 // the case where the panic payload we get out of it also panics on
1783 // drop, and so on. See issue #86027.)
1784 if let Err(_) = panic::catch_unwind(panic::AssertUnwindSafe(|| {
1785 *self.result.get_mut() = None;
1786 })) {
1787 rtabort!("thread result panicked on drop");
1788 }
1789 // Book-keeping so the scope knows when it's done.
1790 if let Some(scope) = &self.scope {
1791 // Now that there will be no more user code running on this thread
1792 // that can use 'scope, mark the thread as 'finished'.
1793 // It's important we only do this after the `result` has been dropped,
1794 // since dropping it might still use things it borrowed from 'scope.
1795 scope.decrement_num_running_threads(unhandled_panic);
1796 }
1797 }
1798}
1799
1800/// Inner representation for JoinHandle
1801struct JoinInner<'scope, T> {
1802 native: imp::Thread,
1803 thread: Thread,
1804 packet: Arc<Packet<'scope, T>>,
1805}
1806
1807impl<'scope, T> JoinInner<'scope, T> {
1808 fn join(mut self) -> Result<T> {
1809 self.native.join();
1810 Arc::get_mut(&mut self.packet)
1811 // FIXME(fuzzypixelz): returning an error instead of panicking here
1812 // would require updating the documentation of
1813 // `std::thread::Result`; currently we can return `Err` if and only
1814 // if the thread had panicked.
1815 .expect("threads should not terminate unexpectedly")
1816 .result
1817 .get_mut()
1818 .take()
1819 .unwrap()
1820 }
1821}
1822
1823/// An owned permission to join on a thread (block on its termination).
1824///
1825/// A `JoinHandle` *detaches* the associated thread when it is dropped, which
1826/// means that there is no longer any handle to the thread and no way to `join`
1827/// on it.
1828///
1829/// Due to platform restrictions, it is not possible to [`Clone`] this
1830/// handle: the ability to join a thread is a uniquely-owned permission.
1831///
1832/// This `struct` is created by the [`thread::spawn`] function and the
1833/// [`thread::Builder::spawn`] method.
1834///
1835/// # Examples
1836///
1837/// Creation from [`thread::spawn`]:
1838///
1839/// ```
1840/// use std::thread;
1841///
1842/// let join_handle: thread::JoinHandle<_> = thread::spawn(|| {
1843/// // some work here
1844/// });
1845/// ```
1846///
1847/// Creation from [`thread::Builder::spawn`]:
1848///
1849/// ```
1850/// use std::thread;
1851///
1852/// let builder = thread::Builder::new();
1853///
1854/// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1855/// // some work here
1856/// }).unwrap();
1857/// ```
1858///
1859/// A thread being detached and outliving the thread that spawned it:
1860///
1861/// ```no_run
1862/// use std::thread;
1863/// use std::time::Duration;
1864///
1865/// let original_thread = thread::spawn(|| {
1866/// let _detached_thread = thread::spawn(|| {
1867/// // Here we sleep to make sure that the first thread returns before.
1868/// thread::sleep(Duration::from_millis(10));
1869/// // This will be called, even though the JoinHandle is dropped.
1870/// println!("♫ Still alive ♫");
1871/// });
1872/// });
1873///
1874/// original_thread.join().expect("The thread being joined has panicked");
1875/// println!("Original thread is joined.");
1876///
1877/// // We make sure that the new thread has time to run, before the main
1878/// // thread returns.
1879///
1880/// thread::sleep(Duration::from_millis(1000));
1881/// ```
1882///
1883/// [`thread::Builder::spawn`]: Builder::spawn
1884/// [`thread::spawn`]: spawn
1885#[stable(feature = "rust1", since = "1.0.0")]
1886#[cfg_attr(target_os = "teeos", must_use)]
1887pub struct JoinHandle<T>(JoinInner<'static, T>);
1888
1889#[stable(feature = "joinhandle_impl_send_sync", since = "1.29.0")]
1890unsafe impl<T> Send for JoinHandle<T> {}
1891#[stable(feature = "joinhandle_impl_send_sync", since = "1.29.0")]
1892unsafe impl<T> Sync for JoinHandle<T> {}
1893
1894impl<T> JoinHandle<T> {
1895 /// Extracts a handle to the underlying thread.
1896 ///
1897 /// # Examples
1898 ///
1899 /// ```
1900 /// use std::thread;
1901 ///
1902 /// let builder = thread::Builder::new();
1903 ///
1904 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1905 /// // some work here
1906 /// }).unwrap();
1907 ///
1908 /// let thread = join_handle.thread();
1909 /// println!("thread id: {:?}", thread.id());
1910 /// ```
1911 #[stable(feature = "rust1", since = "1.0.0")]
1912 #[must_use]
1913 pub fn thread(&self) -> &Thread {
1914 &self.0.thread
1915 }
1916
1917 /// Waits for the associated thread to finish.
1918 ///
1919 /// This function will return immediately if the associated thread has already finished.
1920 ///
1921 /// In terms of [atomic memory orderings], the completion of the associated
1922 /// thread synchronizes with this function returning. In other words, all
1923 /// operations performed by that thread [happen
1924 /// before](https://doc.rust-lang.org/nomicon/atomics.html#data-accesses) all
1925 /// operations that happen after `join` returns.
1926 ///
1927 /// If the associated thread panics, [`Err`] is returned with the parameter given
1928 /// to [`panic!`] (though see the Notes below).
1929 ///
1930 /// [`Err`]: crate::result::Result::Err
1931 /// [atomic memory orderings]: crate::sync::atomic
1932 ///
1933 /// # Panics
1934 ///
1935 /// This function may panic on some platforms if a thread attempts to join
1936 /// itself or otherwise may create a deadlock with joining threads.
1937 ///
1938 /// # Examples
1939 ///
1940 /// ```
1941 /// use std::thread;
1942 ///
1943 /// let builder = thread::Builder::new();
1944 ///
1945 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1946 /// // some work here
1947 /// }).unwrap();
1948 /// join_handle.join().expect("Couldn't join on the associated thread");
1949 /// ```
1950 ///
1951 /// # Notes
1952 ///
1953 /// If a "foreign" unwinding operation (e.g. an exception thrown from C++
1954 /// code, or a `panic!` in Rust code compiled or linked with a different
1955 /// runtime) unwinds all the way to the thread root, the process may be
1956 /// aborted; see the Notes on [`thread::spawn`]. If the process is not
1957 /// aborted, this function will return a `Result::Err` containing an opaque
1958 /// type.
1959 ///
1960 /// [`catch_unwind`]: ../../std/panic/fn.catch_unwind.html
1961 /// [`thread::spawn`]: spawn
1962 #[stable(feature = "rust1", since = "1.0.0")]
1963 pub fn join(self) -> Result<T> {
1964 self.0.join()
1965 }
1966
1967 /// Checks if the associated thread has finished running its main function.
1968 ///
1969 /// `is_finished` supports implementing a non-blocking join operation, by checking
1970 /// `is_finished`, and calling `join` if it returns `true`. This function does not block. To
1971 /// block while waiting on the thread to finish, use [`join`][Self::join].
1972 ///
1973 /// This might return `true` for a brief moment after the thread's main
1974 /// function has returned, but before the thread itself has stopped running.
1975 /// However, once this returns `true`, [`join`][Self::join] can be expected
1976 /// to return quickly, without blocking for any significant amount of time.
1977 #[stable(feature = "thread_is_running", since = "1.61.0")]
1978 pub fn is_finished(&self) -> bool {
1979 Arc::strong_count(&self.0.packet) == 1
1980 }
1981}
1982
1983impl<T> AsInner<imp::Thread> for JoinHandle<T> {
1984 fn as_inner(&self) -> &imp::Thread {
1985 &self.0.native
1986 }
1987}
1988
1989impl<T> IntoInner<imp::Thread> for JoinHandle<T> {
1990 fn into_inner(self) -> imp::Thread {
1991 self.0.native
1992 }
1993}
1994
1995#[stable(feature = "std_debug", since = "1.16.0")]
1996impl<T> fmt::Debug for JoinHandle<T> {
1997 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1998 f.debug_struct("JoinHandle").finish_non_exhaustive()
1999 }
2000}
2001
2002fn _assert_sync_and_send() {
2003 fn _assert_both<T: Send + Sync>() {}
2004 _assert_both::<JoinHandle<()>>();
2005 _assert_both::<Thread>();
2006}
2007
2008/// Returns an estimate of the default amount of parallelism a program should use.
2009///
2010/// Parallelism is a resource. A given machine provides a certain capacity for
2011/// parallelism, i.e., a bound on the number of computations it can perform
2012/// simultaneously. This number often corresponds to the amount of CPUs a
2013/// computer has, but it may diverge in various cases.
2014///
2015/// Host environments such as VMs or container orchestrators may want to
2016/// restrict the amount of parallelism made available to programs in them. This
2017/// is often done to limit the potential impact of (unintentionally)
2018/// resource-intensive programs on other programs running on the same machine.
2019///
2020/// # Limitations
2021///
2022/// The purpose of this API is to provide an easy and portable way to query
2023/// the default amount of parallelism the program should use. Among other things it
2024/// does not expose information on NUMA regions, does not account for
2025/// differences in (co)processor capabilities or current system load,
2026/// and will not modify the program's global state in order to more accurately
2027/// query the amount of available parallelism.
2028///
2029/// Where both fixed steady-state and burst limits are available the steady-state
2030/// capacity will be used to ensure more predictable latencies.
2031///
2032/// Resource limits can be changed during the runtime of a program, therefore the value is
2033/// not cached and instead recomputed every time this function is called. It should not be
2034/// called from hot code.
2035///
2036/// The value returned by this function should be considered a simplified
2037/// approximation of the actual amount of parallelism available at any given
2038/// time. To get a more detailed or precise overview of the amount of
2039/// parallelism available to the program, you may wish to use
2040/// platform-specific APIs as well. The following platform limitations currently
2041/// apply to `available_parallelism`:
2042///
2043/// On Windows:
2044/// - It may undercount the amount of parallelism available on systems with more
2045/// than 64 logical CPUs. However, programs typically need specific support to
2046/// take advantage of more than 64 logical CPUs, and in the absence of such
2047/// support, the number returned by this function accurately reflects the
2048/// number of logical CPUs the program can use by default.
2049/// - It may overcount the amount of parallelism available on systems limited by
2050/// process-wide affinity masks, or job object limitations.
2051///
2052/// On Linux:
2053/// - It may overcount the amount of parallelism available when limited by a
2054/// process-wide affinity mask or cgroup quotas and `sched_getaffinity()` or cgroup fs can't be
2055/// queried, e.g. due to sandboxing.
2056/// - It may undercount the amount of parallelism if the current thread's affinity mask
2057/// does not reflect the process' cpuset, e.g. due to pinned threads.
2058/// - If the process is in a cgroup v1 cpu controller, this may need to
2059/// scan mountpoints to find the corresponding cgroup v1 controller,
2060/// which may take time on systems with large numbers of mountpoints.
2061/// (This does not apply to cgroup v2, or to processes not in a
2062/// cgroup.)
2063/// - It does not attempt to take `ulimit` into account. If there is a limit set on the number of
2064/// threads, `available_parallelism` cannot know how much of that limit a Rust program should
2065/// take, or know in a reliable and race-free way how much of that limit is already taken.
2066///
2067/// On all targets:
2068/// - It may overcount the amount of parallelism available when running in a VM
2069/// with CPU usage limits (e.g. an overcommitted host).
2070///
2071/// # Errors
2072///
2073/// This function will, but is not limited to, return errors in the following
2074/// cases:
2075///
2076/// - If the amount of parallelism is not known for the target platform.
2077/// - If the program lacks permission to query the amount of parallelism made
2078/// available to it.
2079///
2080/// # Examples
2081///
2082/// ```
2083/// # #![allow(dead_code)]
2084/// use std::{io, thread};
2085///
2086/// fn main() -> io::Result<()> {
2087/// let count = thread::available_parallelism()?.get();
2088/// assert!(count >= 1_usize);
2089/// Ok(())
2090/// }
2091/// ```
2092#[doc(alias = "available_concurrency")] // Alias for a previous name we gave this API on unstable.
2093#[doc(alias = "hardware_concurrency")] // Alias for C++ `std::thread::hardware_concurrency`.
2094#[doc(alias = "num_cpus")] // Alias for a popular ecosystem crate which provides similar functionality.
2095#[stable(feature = "available_parallelism", since = "1.59.0")]
2096pub fn available_parallelism() -> io::Result<NonZero<usize>> {
2097 imp::available_parallelism()
2098}