3 //! ## The threading model
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.
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`].
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.
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 //! child thread (i.e., join).
33 //! ## Spawning a thread
35 //! A new thread can be spawned using the [`thread::spawn`][`spawn`] function:
40 //! thread::spawn(move || {
45 //! In this example, the spawned thread is "detached" from the current
46 //! thread. This means that it can outlive its parent (the thread that spawned
47 //! it), unless this parent is the main thread.
49 //! The parent thread can also wait on the completion of the child
50 //! thread; a call to [`spawn`] produces a [`JoinHandle`], which provides
51 //! a `join` method for waiting:
56 //! let child = thread::spawn(move || {
60 //! let res = child.join();
63 //! The [`join`] method returns a [`thread::Result`] containing [`Ok`] of the final
64 //! value produced by the child thread, or [`Err`] of the value given to
65 //! a call to [`panic!`] if the child panicked.
67 //! ## Configuring threads
69 //! A new thread can be configured before it is spawned via the [`Builder`] type,
70 //! which currently allows you to set the name and stack size for the child thread:
73 //! # #![allow(unused_must_use)]
76 //! thread::Builder::new().name("child1".to_string()).spawn(move || {
77 //! println!("Hello, world!");
81 //! ## The `Thread` type
83 //! Threads are represented via the [`Thread`] type, which you can get in one of
86 //! * By spawning a new thread, e.g., using the [`thread::spawn`][`spawn`]
87 //! function, and calling [`thread`][`JoinHandle::thread`] on the [`JoinHandle`].
88 //! * By requesting the current thread, using the [`thread::current`] function.
90 //! The [`thread::current`] function is available even for threads not spawned
91 //! by the APIs of this module.
93 //! ## Thread-local storage
95 //! This module also provides an implementation of thread-local storage for Rust
96 //! programs. Thread-local storage is a method of storing data into a global
97 //! variable that each thread in the program will have its own copy of.
98 //! Threads do not share this data, so accesses do not need to be synchronized.
100 //! A thread-local key owns the value it contains and will destroy the value when the
101 //! thread exits. It is created with the [`thread_local!`] macro and can contain any
102 //! value that is `'static` (no borrowed pointers). It provides an accessor function,
103 //! [`with`], that yields a shared reference to the value to the specified
104 //! closure. Thread-local keys allow only shared access to values, as there would be no
105 //! way to guarantee uniqueness if mutable borrows were allowed. Most values
106 //! will want to make use of some form of **interior mutability** through the
107 //! [`Cell`] or [`RefCell`] types.
109 //! ## Naming threads
111 //! Threads are able to have associated names for identification purposes. By default, spawned
112 //! threads are unnamed. To specify a name for a thread, build the thread with [`Builder`] and pass
113 //! the desired thread name to [`Builder::name`]. To retrieve the thread name from within the
114 //! thread, use [`Thread::name`]. A couple examples of where the name of a thread gets used:
116 //! * If a panic occurs in a named thread, the thread name will be printed in the panic message.
117 //! * The thread name is provided to the OS where applicable (e.g., `pthread_setname_np` in
118 //! unix-like platforms).
122 //! The default stack size for spawned threads is 2 MiB, though this particular stack size is
123 //! subject to change in the future. There are two ways to manually specify the stack size for
126 //! * Build the thread with [`Builder`] and pass the desired stack size to [`Builder::stack_size`].
127 //! * Set the `RUST_MIN_STACK` environment variable to an integer representing the desired stack
128 //! size (in bytes). Note that setting [`Builder::stack_size`] will override this.
130 //! Note that the stack size of the main thread is *not* determined by Rust.
132 //! [channels]: crate::sync::mpsc
133 //! [`join`]: JoinHandle::join
134 //! [`Result`]: crate::result::Result
135 //! [`Ok`]: crate::result::Result::Ok
136 //! [`Err`]: crate::result::Result::Err
137 //! [`thread::current`]: current
138 //! [`thread::Result`]: Result
139 //! [`unpark`]: Thread::unpark
140 //! [`Thread::name`]: Thread::name
141 //! [`thread::park_timeout`]: park_timeout
142 //! [`Cell`]: crate::cell::Cell
143 //! [`RefCell`]: crate::cell::RefCell
144 //! [`with`]: LocalKey::with
146 #![stable(feature = "rust1", since = "1.0.0")]
147 #![deny(unsafe_op_in_unsafe_fn)]
149 #[cfg(all(test, not(target_os = "emscripten")))]
153 use crate::cell::UnsafeCell;
154 use crate::ffi::{CStr, CString};
158 use crate::num::NonZeroU64;
160 use crate::panicking;
162 use crate::sync::atomic::AtomicUsize;
163 use crate::sync::atomic::Ordering::SeqCst;
164 use crate::sync::{Arc, Condvar, Mutex};
165 use crate::sys::thread as imp;
166 use crate::sys_common::mutex;
167 use crate::sys_common::thread;
168 use crate::sys_common::thread_info;
169 use crate::sys_common::{AsInner, IntoInner};
170 use crate::time::Duration;
172 ////////////////////////////////////////////////////////////////////////////////
173 // Thread-local storage
174 ////////////////////////////////////////////////////////////////////////////////
179 #[stable(feature = "rust1", since = "1.0.0")]
180 pub use self::local::{AccessError, LocalKey};
182 // The types used by the thread_local! macro to access TLS keys. Note that there
183 // are two types, the "OS" type and the "fast" type. The OS thread local key
184 // type is accessed via platform-specific API calls and is slow, while the fast
185 // key type is accessed via code generated via LLVM, where TLS keys are set up
186 // by the elf linker. Note that the OS TLS type is always available: on macOS
187 // the standard library is compiled with support for older platform versions
188 // where fast TLS was not available; end-user code is compiled with fast TLS
189 // where available, but both are needed.
191 #[unstable(feature = "libstd_thread_internals", issue = "none")]
192 #[cfg(target_thread_local)]
194 pub use self::local::fast::Key as __FastLocalKeyInner;
195 #[unstable(feature = "libstd_thread_internals", issue = "none")]
197 pub use self::local::os::Key as __OsLocalKeyInner;
198 #[unstable(feature = "libstd_thread_internals", issue = "none")]
199 #[cfg(all(target_arch = "wasm32", not(target_feature = "atomics")))]
201 pub use self::local::statik::Key as __StaticLocalKeyInner;
203 ////////////////////////////////////////////////////////////////////////////////
205 ////////////////////////////////////////////////////////////////////////////////
207 /// Thread factory, which can be used in order to configure the properties of
210 /// Methods can be chained on it in order to configure it.
212 /// The two configurations available are:
214 /// - [`name`]: specifies an [associated name for the thread][naming-threads]
215 /// - [`stack_size`]: specifies the [desired stack size for the thread][stack-size]
217 /// The [`spawn`] method will take ownership of the builder and create an
218 /// [`io::Result`] to the thread handle with the given configuration.
220 /// The [`thread::spawn`] free function uses a `Builder` with default
221 /// configuration and [`unwrap`]s its return value.
223 /// You may want to use [`spawn`] instead of [`thread::spawn`], when you want
224 /// to recover from a failure to launch a thread, indeed the free function will
225 /// panic where the `Builder` method will return a [`io::Result`].
232 /// let builder = thread::Builder::new();
234 /// let handler = builder.spawn(|| {
238 /// handler.join().unwrap();
241 /// [`stack_size`]: Builder::stack_size
242 /// [`name`]: Builder::name
243 /// [`spawn`]: Builder::spawn
244 /// [`thread::spawn`]: spawn
245 /// [`io::Result`]: crate::io::Result
246 /// [`unwrap`]: crate::result::Result::unwrap
247 /// [naming-threads]: ./index.html#naming-threads
248 /// [stack-size]: ./index.html#stack-size
249 #[stable(feature = "rust1", since = "1.0.0")]
252 // A name for the thread-to-be, for identification in panic messages
253 name: Option<String>,
254 // The size of the stack for the spawned thread in bytes
255 stack_size: Option<usize>,
259 /// Generates the base configuration for spawning a thread, from which
260 /// configuration methods can be chained.
267 /// let builder = thread::Builder::new()
268 /// .name("foo".into())
269 /// .stack_size(32 * 1024);
271 /// let handler = builder.spawn(|| {
275 /// handler.join().unwrap();
277 #[stable(feature = "rust1", since = "1.0.0")]
278 pub fn new() -> Builder {
279 Builder { name: None, stack_size: None }
282 /// Names the thread-to-be. Currently the name is used for identification
283 /// only in panic messages.
285 /// The name must not contain null bytes (`\0`).
287 /// For more information about named threads, see
288 /// [this module-level documentation][naming-threads].
295 /// let builder = thread::Builder::new()
296 /// .name("foo".into());
298 /// let handler = builder.spawn(|| {
299 /// assert_eq!(thread::current().name(), Some("foo"))
302 /// handler.join().unwrap();
305 /// [naming-threads]: ./index.html#naming-threads
306 #[stable(feature = "rust1", since = "1.0.0")]
307 pub fn name(mut self, name: String) -> Builder {
308 self.name = Some(name);
312 /// Sets the size of the stack (in bytes) for the new thread.
314 /// The actual stack size may be greater than this value if
315 /// the platform specifies a minimal stack size.
317 /// For more information about the stack size for threads, see
318 /// [this module-level documentation][stack-size].
325 /// let builder = thread::Builder::new().stack_size(32 * 1024);
328 /// [stack-size]: ./index.html#stack-size
329 #[stable(feature = "rust1", since = "1.0.0")]
330 pub fn stack_size(mut self, size: usize) -> Builder {
331 self.stack_size = Some(size);
335 /// Spawns a new thread by taking ownership of the `Builder`, and returns an
336 /// [`io::Result`] to its [`JoinHandle`].
338 /// The spawned thread may outlive the caller (unless the caller thread
339 /// is the main thread; the whole process is terminated when the main
340 /// thread finishes). The join handle can be used to block on
341 /// termination of the child thread, including recovering its panics.
343 /// For a more complete documentation see [`thread::spawn`][`spawn`].
347 /// Unlike the [`spawn`] free function, this method yields an
348 /// [`io::Result`] to capture any failure to create the thread at
351 /// [`io::Result`]: crate::io::Result
355 /// Panics if a thread name was set and it contained null bytes.
362 /// let builder = thread::Builder::new();
364 /// let handler = builder.spawn(|| {
368 /// handler.join().unwrap();
370 #[stable(feature = "rust1", since = "1.0.0")]
371 pub fn spawn<F, T>(self, f: F) -> io::Result<JoinHandle<T>>
377 unsafe { self.spawn_unchecked(f) }
380 /// Spawns a new thread without any lifetime restrictions by taking ownership
381 /// of the `Builder`, and returns an [`io::Result`] to its [`JoinHandle`].
383 /// The spawned thread may outlive the caller (unless the caller thread
384 /// is the main thread; the whole process is terminated when the main
385 /// thread finishes). The join handle can be used to block on
386 /// termination of the child thread, including recovering its panics.
388 /// This method is identical to [`thread::Builder::spawn`][`Builder::spawn`],
389 /// except for the relaxed lifetime bounds, which render it unsafe.
390 /// For a more complete documentation see [`thread::spawn`][`spawn`].
394 /// Unlike the [`spawn`] free function, this method yields an
395 /// [`io::Result`] to capture any failure to create the thread at
400 /// Panics if a thread name was set and it contained null bytes.
404 /// The caller has to ensure that no references in the supplied thread closure
405 /// or its return type can outlive the spawned thread's lifetime. This can be
406 /// guaranteed in two ways:
408 /// - ensure that [`join`][`JoinHandle::join`] is called before any referenced
410 /// - use only types with `'static` lifetime bounds, i.e., those with no or only
411 /// `'static` references (both [`thread::Builder::spawn`][`Builder::spawn`]
412 /// and [`thread::spawn`][`spawn`] enforce this property statically)
417 /// #![feature(thread_spawn_unchecked)]
420 /// let builder = thread::Builder::new();
423 /// let thread_x = &x;
425 /// let handler = unsafe {
426 /// builder.spawn_unchecked(move || {
427 /// println!("x = {}", *thread_x);
431 /// // caller has to ensure `join()` is called, otherwise
432 /// // it is possible to access freed memory if `x` gets
433 /// // dropped before the thread closure is executed!
434 /// handler.join().unwrap();
437 /// [`io::Result`]: crate::io::Result
438 #[unstable(feature = "thread_spawn_unchecked", issue = "55132")]
439 pub unsafe fn spawn_unchecked<'a, F, T>(self, f: F) -> io::Result<JoinHandle<T>>
445 let Builder { name, stack_size } = self;
447 let stack_size = stack_size.unwrap_or_else(thread::min_stack);
449 let my_thread = Thread::new(name);
450 let their_thread = my_thread.clone();
452 let my_packet: Arc<UnsafeCell<Option<Result<T>>>> = Arc::new(UnsafeCell::new(None));
453 let their_packet = my_packet.clone();
456 if let Some(name) = their_thread.cname() {
457 imp::Thread::set_name(name);
460 // SAFETY: the stack guard passed is the one for the current thread.
461 // This means the current thread's stack and the new thread's stack
462 // are properly set and protected from each other.
463 thread_info::set(unsafe { imp::guard::current() }, their_thread);
464 let try_result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
465 crate::sys_common::backtrace::__rust_begin_short_backtrace(f)
467 // SAFETY: `their_packet` as been built just above and moved by the
468 // closure (it is an Arc<...>) and `my_packet` will be stored in the
469 // same `JoinInner` as this closure meaning the mutation will be
470 // safe (not modify it and affect a value far away).
471 unsafe { *their_packet.get() = Some(try_result) };
474 Ok(JoinHandle(JoinInner {
477 // `imp::Thread::new` takes a closure with a `'static` lifetime, since it's passed
478 // through FFI or otherwise used with low-level threading primitives that have no
479 // notion of or way to enforce lifetimes.
481 // As mentioned in the `Safety` section of this function's documentation, the caller of
482 // this function needs to guarantee that the passed-in lifetime is sufficiently long
483 // for the lifetime of the thread.
485 // Similarly, the `sys` implementation must guarantee that no references to the closure
486 // exist after the thread has terminated, which is signaled by `Thread::join`
489 Some(imp::Thread::new(
491 mem::transmute::<Box<dyn FnOnce() + 'a>, Box<dyn FnOnce() + 'static>>(
497 packet: Packet(my_packet),
502 ////////////////////////////////////////////////////////////////////////////////
504 ////////////////////////////////////////////////////////////////////////////////
506 /// Spawns a new thread, returning a [`JoinHandle`] for it.
508 /// The join handle will implicitly *detach* the child thread upon being
509 /// dropped. In this case, the child thread may outlive the parent (unless
510 /// the parent thread is the main thread; the whole process is terminated when
511 /// the main thread finishes). Additionally, the join handle provides a [`join`]
512 /// method that can be used to join the child thread. If the child thread
513 /// panics, [`join`] will return an [`Err`] containing the argument given to
516 /// This will create a thread using default parameters of [`Builder`], if you
517 /// want to specify the stack size or the name of the thread, use this API
520 /// As you can see in the signature of `spawn` there are two constraints on
521 /// both the closure given to `spawn` and its return value, let's explain them:
523 /// - The `'static` constraint means that the closure and its return value
524 /// must have a lifetime of the whole program execution. The reason for this
525 /// is that threads can `detach` and outlive the lifetime they have been
527 /// Indeed if the thread, and by extension its return value, can outlive their
528 /// caller, we need to make sure that they will be valid afterwards, and since
529 /// we *can't* know when it will return we need to have them valid as long as
530 /// possible, that is until the end of the program, hence the `'static`
532 /// - The [`Send`] constraint is because the closure will need to be passed
533 /// *by value* from the thread where it is spawned to the new thread. Its
534 /// return value will need to be passed from the new thread to the thread
535 /// where it is `join`ed.
536 /// As a reminder, the [`Send`] marker trait expresses that it is safe to be
537 /// passed from thread to thread. [`Sync`] expresses that it is safe to have a
538 /// reference be passed from thread to thread.
542 /// Panics if the OS fails to create a thread; use [`Builder::spawn`]
543 /// to recover from such errors.
547 /// Creating a thread.
552 /// let handler = thread::spawn(|| {
556 /// handler.join().unwrap();
559 /// As mentioned in the module documentation, threads are usually made to
560 /// communicate using [`channels`], here is how it usually looks.
562 /// This example also shows how to use `move`, in order to give ownership
563 /// of values to a thread.
567 /// use std::sync::mpsc::channel;
569 /// let (tx, rx) = channel();
571 /// let sender = thread::spawn(move || {
572 /// tx.send("Hello, thread".to_owned())
573 /// .expect("Unable to send on channel");
576 /// let receiver = thread::spawn(move || {
577 /// let value = rx.recv().expect("Unable to receive from channel");
578 /// println!("{}", value);
581 /// sender.join().expect("The sender thread has panicked");
582 /// receiver.join().expect("The receiver thread has panicked");
585 /// A thread can also return a value through its [`JoinHandle`], you can use
586 /// this to make asynchronous computations (futures might be more appropriate
592 /// let computation = thread::spawn(|| {
593 /// // Some expensive computation.
597 /// let result = computation.join().unwrap();
598 /// println!("{}", result);
601 /// [`channels`]: crate::sync::mpsc
602 /// [`join`]: JoinHandle::join
603 /// [`Err`]: crate::result::Result::Err
604 #[stable(feature = "rust1", since = "1.0.0")]
605 pub fn spawn<F, T>(f: F) -> JoinHandle<T>
611 Builder::new().spawn(f).expect("failed to spawn thread")
614 /// Gets a handle to the thread that invokes it.
618 /// Getting a handle to the current thread with `thread::current()`:
623 /// let handler = thread::Builder::new()
624 /// .name("named thread".into())
626 /// let handle = thread::current();
627 /// assert_eq!(handle.name(), Some("named thread"));
631 /// handler.join().unwrap();
633 #[stable(feature = "rust1", since = "1.0.0")]
634 pub fn current() -> Thread {
635 thread_info::current_thread().expect(
636 "use of std::thread::current() is not possible \
637 after the thread's local data has been destroyed",
641 /// Cooperatively gives up a timeslice to the OS scheduler.
643 /// This is used when the programmer knows that the thread will have nothing
644 /// to do for some time, and thus avoid wasting computing time.
646 /// For example when polling on a resource, it is common to check that it is
647 /// available, and if not to yield in order to avoid busy waiting.
649 /// Thus the pattern of `yield`ing after a failed poll is rather common when
650 /// implementing low-level shared resources or synchronization primitives.
652 /// However programmers will usually prefer to use [`channel`]s, [`Condvar`]s,
653 /// [`Mutex`]es or [`join`] for their synchronization routines, as they avoid
654 /// thinking about thread scheduling.
656 /// Note that [`channel`]s for example are implemented using this primitive.
657 /// Indeed when you call `send` or `recv`, which are blocking, they will yield
658 /// if the channel is not available.
665 /// thread::yield_now();
668 /// [`channel`]: crate::sync::mpsc
669 /// [`join`]: JoinHandle::join
670 #[stable(feature = "rust1", since = "1.0.0")]
672 imp::Thread::yield_now()
675 /// Determines whether the current thread is unwinding because of panic.
677 /// A common use of this feature is to poison shared resources when writing
678 /// unsafe code, by checking `panicking` when the `drop` is called.
680 /// This is usually not needed when writing safe code, as [`Mutex`es][Mutex]
681 /// already poison themselves when a thread panics while holding the lock.
683 /// This can also be used in multithreaded applications, in order to send a
684 /// message to other threads warning that a thread has panicked (e.g., for
685 /// monitoring purposes).
692 /// struct SomeStruct;
694 /// impl Drop for SomeStruct {
695 /// fn drop(&mut self) {
696 /// if thread::panicking() {
697 /// println!("dropped while unwinding");
699 /// println!("dropped while not unwinding");
706 /// let a = SomeStruct;
711 /// let b = SomeStruct;
716 #[stable(feature = "rust1", since = "1.0.0")]
717 pub fn panicking() -> bool {
718 panicking::panicking()
721 /// Puts the current thread to sleep for at least the specified amount of time.
723 /// The thread may sleep longer than the duration specified due to scheduling
724 /// specifics or platform-dependent functionality. It will never sleep less.
726 /// This function is blocking, and should not be used in `async` functions.
728 /// # Platform-specific behavior
730 /// On Unix platforms, the underlying syscall may be interrupted by a
731 /// spurious wakeup or signal handler. To ensure the sleep occurs for at least
732 /// the specified duration, this function may invoke that system call multiple
740 /// // Let's sleep for 2 seconds:
741 /// thread::sleep_ms(2000);
743 #[stable(feature = "rust1", since = "1.0.0")]
744 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::sleep`")]
745 pub fn sleep_ms(ms: u32) {
746 sleep(Duration::from_millis(ms as u64))
749 /// Puts the current thread to sleep for at least the specified amount of time.
751 /// The thread may sleep longer than the duration specified due to scheduling
752 /// specifics or platform-dependent functionality. It will never sleep less.
754 /// This function is blocking, and should not be used in `async` functions.
756 /// # Platform-specific behavior
758 /// On Unix platforms, the underlying syscall may be interrupted by a
759 /// spurious wakeup or signal handler. To ensure the sleep occurs for at least
760 /// the specified duration, this function may invoke that system call multiple
762 /// Platforms which do not support nanosecond precision for sleeping will
763 /// have `dur` rounded up to the nearest granularity of time they can sleep for.
768 /// use std::{thread, time};
770 /// let ten_millis = time::Duration::from_millis(10);
771 /// let now = time::Instant::now();
773 /// thread::sleep(ten_millis);
775 /// assert!(now.elapsed() >= ten_millis);
777 #[stable(feature = "thread_sleep", since = "1.4.0")]
778 pub fn sleep(dur: Duration) {
779 imp::Thread::sleep(dur)
782 // constants for park/unpark
783 const EMPTY: usize = 0;
784 const PARKED: usize = 1;
785 const NOTIFIED: usize = 2;
787 /// Blocks unless or until the current thread's token is made available.
789 /// A call to `park` does not guarantee that the thread will remain parked
790 /// forever, and callers should be prepared for this possibility.
792 /// # park and unpark
794 /// Every thread is equipped with some basic low-level blocking support, via the
795 /// [`thread::park`][`park`] function and [`thread::Thread::unpark`][`unpark`]
796 /// method. [`park`] blocks the current thread, which can then be resumed from
797 /// another thread by calling the [`unpark`] method on the blocked thread's
800 /// Conceptually, each [`Thread`] handle has an associated token, which is
801 /// initially not present:
803 /// * The [`thread::park`][`park`] function blocks the current thread unless or
804 /// until the token is available for its thread handle, at which point it
805 /// atomically consumes the token. It may also return *spuriously*, without
806 /// consuming the token. [`thread::park_timeout`] does the same, but allows
807 /// specifying a maximum time to block the thread for.
809 /// * The [`unpark`] method on a [`Thread`] atomically makes the token available
810 /// if it wasn't already. Because the token is initially absent, [`unpark`]
811 /// followed by [`park`] will result in the second call returning immediately.
813 /// In other words, each [`Thread`] acts a bit like a spinlock that can be
814 /// locked and unlocked using `park` and `unpark`.
816 /// Notice that being unblocked does not imply any synchronization with someone
817 /// that unparked this thread, it could also be spurious.
818 /// For example, it would be a valid, but inefficient, implementation to make both [`park`] and
819 /// [`unpark`] return immediately without doing anything.
821 /// The API is typically used by acquiring a handle to the current thread,
822 /// placing that handle in a shared data structure so that other threads can
823 /// find it, and then `park`ing in a loop. When some desired condition is met, another
824 /// thread calls [`unpark`] on the handle.
826 /// The motivation for this design is twofold:
828 /// * It avoids the need to allocate mutexes and condvars when building new
829 /// synchronization primitives; the threads already provide basic
830 /// blocking/signaling.
832 /// * It can be implemented very efficiently on many platforms.
838 /// use std::sync::{Arc, atomic::{Ordering, AtomicBool}};
839 /// use std::time::Duration;
841 /// let flag = Arc::new(AtomicBool::new(false));
842 /// let flag2 = Arc::clone(&flag);
844 /// let parked_thread = thread::spawn(move || {
845 /// // We want to wait until the flag is set. We *could* just spin, but using
846 /// // park/unpark is more efficient.
847 /// while !flag2.load(Ordering::Acquire) {
848 /// println!("Parking thread");
850 /// // We *could* get here spuriously, i.e., way before the 10ms below are over!
851 /// // But that is no problem, we are in a loop until the flag is set anyway.
852 /// println!("Thread unparked");
854 /// println!("Flag received");
857 /// // Let some time pass for the thread to be spawned.
858 /// thread::sleep(Duration::from_millis(10));
860 /// // Set the flag, and let the thread wake up.
861 /// // There is no race condition here, if `unpark`
862 /// // happens first, `park` will return immediately.
863 /// // Hence there is no risk of a deadlock.
864 /// flag.store(true, Ordering::Release);
865 /// println!("Unpark the thread");
866 /// parked_thread.thread().unpark();
868 /// parked_thread.join().unwrap();
871 /// [`unpark`]: Thread::unpark
872 /// [`thread::park_timeout`]: park_timeout
874 // The implementation currently uses the trivial strategy of a Mutex+Condvar
875 // with wakeup flag, which does not actually allow spurious wakeups. In the
876 // future, this will be implemented in a more efficient way, perhaps along the lines of
877 // http://cr.openjdk.java.net/~stefank/6989984.1/raw_files/new/src/os/linux/vm/os_linux.cpp
878 // or futuxes, and in either case may allow spurious wakeups.
879 #[stable(feature = "rust1", since = "1.0.0")]
881 let thread = current();
883 // If we were previously notified then we consume this notification and
885 if thread.inner.state.compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst).is_ok() {
889 // Otherwise we need to coordinate going to sleep
890 let mut m = thread.inner.lock.lock().unwrap();
891 match thread.inner.state.compare_exchange(EMPTY, PARKED, SeqCst, SeqCst) {
894 // We must read here, even though we know it will be `NOTIFIED`.
895 // This is because `unpark` may have been called again since we read
896 // `NOTIFIED` in the `compare_exchange` above. We must perform an
897 // acquire operation that synchronizes with that `unpark` to observe
898 // any writes it made before the call to unpark. To do that we must
899 // read from the write it made to `state`.
900 let old = thread.inner.state.swap(EMPTY, SeqCst);
901 assert_eq!(old, NOTIFIED, "park state changed unexpectedly");
903 } // should consume this notification, so prohibit spurious wakeups in next park.
904 Err(_) => panic!("inconsistent park state"),
907 m = thread.inner.cvar.wait(m).unwrap();
908 match thread.inner.state.compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst) {
909 Ok(_) => return, // got a notification
910 Err(_) => {} // spurious wakeup, go back to sleep
915 /// Use [`park_timeout`].
917 /// Blocks unless or until the current thread's token is made available or
918 /// the specified duration has been reached (may wake spuriously).
920 /// The semantics of this function are equivalent to [`park`] except
921 /// that the thread will be blocked for roughly no longer than `dur`. This
922 /// method should not be used for precise timing due to anomalies such as
923 /// preemption or platform differences that may not cause the maximum
924 /// amount of time waited to be precisely `ms` long.
926 /// See the [park documentation][`park`] for more detail.
927 #[stable(feature = "rust1", since = "1.0.0")]
928 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::park_timeout`")]
929 pub fn park_timeout_ms(ms: u32) {
930 park_timeout(Duration::from_millis(ms as u64))
933 /// Blocks unless or until the current thread's token is made available or
934 /// the specified duration has been reached (may wake spuriously).
936 /// The semantics of this function are equivalent to [`park`][park] except
937 /// that the thread will be blocked for roughly no longer than `dur`. This
938 /// method should not be used for precise timing due to anomalies such as
939 /// preemption or platform differences that may not cause the maximum
940 /// amount of time waited to be precisely `dur` long.
942 /// See the [park documentation][park] for more details.
944 /// # Platform-specific behavior
946 /// Platforms which do not support nanosecond precision for sleeping will have
947 /// `dur` rounded up to the nearest granularity of time they can sleep for.
951 /// Waiting for the complete expiration of the timeout:
954 /// use std::thread::park_timeout;
955 /// use std::time::{Instant, Duration};
957 /// let timeout = Duration::from_secs(2);
958 /// let beginning_park = Instant::now();
960 /// let mut timeout_remaining = timeout;
962 /// park_timeout(timeout_remaining);
963 /// let elapsed = beginning_park.elapsed();
964 /// if elapsed >= timeout {
967 /// println!("restarting park_timeout after {:?}", elapsed);
968 /// timeout_remaining = timeout - elapsed;
971 #[stable(feature = "park_timeout", since = "1.4.0")]
972 pub fn park_timeout(dur: Duration) {
973 let thread = current();
975 // Like `park` above we have a fast path for an already-notified thread, and
976 // afterwards we start coordinating for a sleep.
978 if thread.inner.state.compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst).is_ok() {
981 let m = thread.inner.lock.lock().unwrap();
982 match thread.inner.state.compare_exchange(EMPTY, PARKED, SeqCst, SeqCst) {
985 // We must read again here, see `park`.
986 let old = thread.inner.state.swap(EMPTY, SeqCst);
987 assert_eq!(old, NOTIFIED, "park state changed unexpectedly");
989 } // should consume this notification, so prohibit spurious wakeups in next park.
990 Err(_) => panic!("inconsistent park_timeout state"),
993 // Wait with a timeout, and if we spuriously wake up or otherwise wake up
994 // from a notification we just want to unconditionally set the state back to
995 // empty, either consuming a notification or un-flagging ourselves as
997 let (_m, _result) = thread.inner.cvar.wait_timeout(m, dur).unwrap();
998 match thread.inner.state.swap(EMPTY, SeqCst) {
999 NOTIFIED => {} // got a notification, hurray!
1000 PARKED => {} // no notification, alas
1001 n => panic!("inconsistent park_timeout state: {}", n),
1005 ////////////////////////////////////////////////////////////////////////////////
1007 ////////////////////////////////////////////////////////////////////////////////
1009 /// A unique identifier for a running thread.
1011 /// A `ThreadId` is an opaque object that has a unique value for each thread
1012 /// that creates one. `ThreadId`s are not guaranteed to correspond to a thread's
1013 /// system-designated identifier. A `ThreadId` can be retrieved from the [`id`]
1014 /// method on a [`Thread`].
1019 /// use std::thread;
1021 /// let other_thread = thread::spawn(|| {
1022 /// thread::current().id()
1025 /// let other_thread_id = other_thread.join().unwrap();
1026 /// assert!(thread::current().id() != other_thread_id);
1029 /// [`id`]: Thread::id
1030 #[stable(feature = "thread_id", since = "1.19.0")]
1031 #[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
1032 pub struct ThreadId(NonZeroU64);
1035 // Generate a new unique thread ID.
1036 fn new() -> ThreadId {
1037 // We never call `GUARD.init()`, so it is UB to attempt to
1038 // acquire this mutex reentrantly!
1039 static GUARD: mutex::Mutex = mutex::Mutex::new();
1040 static mut COUNTER: u64 = 1;
1043 let _guard = GUARD.lock();
1045 // If we somehow use up all our bits, panic so that we're not
1046 // covering up subtle bugs of IDs being reused.
1047 if COUNTER == u64::MAX {
1048 panic!("failed to generate unique thread ID: bitspace exhausted");
1054 ThreadId(NonZeroU64::new(id).unwrap())
1058 /// This returns a numeric identifier for the thread identified by this
1061 /// As noted in the documentation for the type itself, it is essentially an
1062 /// opaque ID, but is guaranteed to be unique for each thread. The returned
1063 /// value is entirely opaque -- only equality testing is stable. Note that
1064 /// it is not guaranteed which values new threads will return, and this may
1065 /// change across Rust versions.
1066 #[unstable(feature = "thread_id_value", issue = "67939")]
1067 pub fn as_u64(&self) -> NonZeroU64 {
1072 ////////////////////////////////////////////////////////////////////////////////
1074 ////////////////////////////////////////////////////////////////////////////////
1076 /// The internal representation of a `Thread` handle
1078 name: Option<CString>, // Guaranteed to be UTF-8
1081 // state for thread park/unpark
1088 #[stable(feature = "rust1", since = "1.0.0")]
1089 /// A handle to a thread.
1091 /// Threads are represented via the `Thread` type, which you can get in one of
1094 /// * By spawning a new thread, e.g., using the [`thread::spawn`][`spawn`]
1095 /// function, and calling [`thread`][`JoinHandle::thread`] on the
1097 /// * By requesting the current thread, using the [`thread::current`] function.
1099 /// The [`thread::current`] function is available even for threads not spawned
1100 /// by the APIs of this module.
1102 /// There is usually no need to create a `Thread` struct yourself, one
1103 /// should instead use a function like `spawn` to create new threads, see the
1104 /// docs of [`Builder`] and [`spawn`] for more details.
1106 /// [`thread::current`]: current
1112 // Used only internally to construct a thread object without spawning
1113 // Panics if the name contains nuls.
1114 pub(crate) fn new(name: Option<String>) -> Thread {
1116 name.map(|n| CString::new(n).expect("thread name may not contain interior null bytes"));
1118 inner: Arc::new(Inner {
1120 id: ThreadId::new(),
1121 state: AtomicUsize::new(EMPTY),
1122 lock: Mutex::new(()),
1123 cvar: Condvar::new(),
1128 /// Atomically makes the handle's token available if it is not already.
1130 /// Every thread is equipped with some basic low-level blocking support, via
1131 /// the [`park`][park] function and the `unpark()` method. These can be
1132 /// used as a more CPU-efficient implementation of a spinlock.
1134 /// See the [park documentation][park] for more details.
1139 /// use std::thread;
1140 /// use std::time::Duration;
1142 /// let parked_thread = thread::Builder::new()
1144 /// println!("Parking thread");
1146 /// println!("Thread unparked");
1150 /// // Let some time pass for the thread to be spawned.
1151 /// thread::sleep(Duration::from_millis(10));
1153 /// println!("Unpark the thread");
1154 /// parked_thread.thread().unpark();
1156 /// parked_thread.join().unwrap();
1158 #[stable(feature = "rust1", since = "1.0.0")]
1159 pub fn unpark(&self) {
1160 // To ensure the unparked thread will observe any writes we made
1161 // before this call, we must perform a release operation that `park`
1162 // can synchronize with. To do that we must write `NOTIFIED` even if
1163 // `state` is already `NOTIFIED`. That is why this must be a swap
1164 // rather than a compare-and-swap that returns if it reads `NOTIFIED`
1166 match self.inner.state.swap(NOTIFIED, SeqCst) {
1167 EMPTY => return, // no one was waiting
1168 NOTIFIED => return, // already unparked
1169 PARKED => {} // gotta go wake someone up
1170 _ => panic!("inconsistent state in unpark"),
1173 // There is a period between when the parked thread sets `state` to
1174 // `PARKED` (or last checked `state` in the case of a spurious wake
1175 // up) and when it actually waits on `cvar`. If we were to notify
1176 // during this period it would be ignored and then when the parked
1177 // thread went to sleep it would never wake up. Fortunately, it has
1178 // `lock` locked at this stage so we can acquire `lock` to wait until
1179 // it is ready to receive the notification.
1181 // Releasing `lock` before the call to `notify_one` means that when the
1182 // parked thread wakes it doesn't get woken only to have to wait for us
1183 // to release `lock`.
1184 drop(self.inner.lock.lock().unwrap());
1185 self.inner.cvar.notify_one()
1188 /// Gets the thread's unique identifier.
1193 /// use std::thread;
1195 /// let other_thread = thread::spawn(|| {
1196 /// thread::current().id()
1199 /// let other_thread_id = other_thread.join().unwrap();
1200 /// assert!(thread::current().id() != other_thread_id);
1202 #[stable(feature = "thread_id", since = "1.19.0")]
1203 pub fn id(&self) -> ThreadId {
1207 /// Gets the thread's name.
1209 /// For more information about named threads, see
1210 /// [this module-level documentation][naming-threads].
1214 /// Threads by default have no name specified:
1217 /// use std::thread;
1219 /// let builder = thread::Builder::new();
1221 /// let handler = builder.spawn(|| {
1222 /// assert!(thread::current().name().is_none());
1225 /// handler.join().unwrap();
1228 /// Thread with a specified name:
1231 /// use std::thread;
1233 /// let builder = thread::Builder::new()
1234 /// .name("foo".into());
1236 /// let handler = builder.spawn(|| {
1237 /// assert_eq!(thread::current().name(), Some("foo"))
1240 /// handler.join().unwrap();
1243 /// [naming-threads]: ./index.html#naming-threads
1244 #[stable(feature = "rust1", since = "1.0.0")]
1245 pub fn name(&self) -> Option<&str> {
1246 self.cname().map(|s| unsafe { str::from_utf8_unchecked(s.to_bytes()) })
1249 fn cname(&self) -> Option<&CStr> {
1250 self.inner.name.as_deref()
1254 #[stable(feature = "rust1", since = "1.0.0")]
1255 impl fmt::Debug for Thread {
1256 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1257 f.debug_struct("Thread").field("id", &self.id()).field("name", &self.name()).finish()
1261 ////////////////////////////////////////////////////////////////////////////////
1263 ////////////////////////////////////////////////////////////////////////////////
1265 /// A specialized [`Result`] type for threads.
1267 /// Indicates the manner in which a thread exited.
1269 /// The value contained in the `Result::Err` variant
1270 /// is the value the thread panicked with;
1271 /// that is, the argument the `panic!` macro was called with.
1272 /// Unlike with normal errors, this value doesn't implement
1273 /// the [`Error`](crate::error::Error) trait.
1275 /// Thus, a sensible way to handle a thread panic is to either:
1276 /// 1. `unwrap` the `Result<T>`, propagating the panic
1277 /// 2. or in case the thread is intended to be a subsystem boundary
1278 /// that is supposed to isolate system-level failures,
1279 /// match on the `Err` variant and handle the panic in an appropriate way.
1281 /// A thread that completes without panicking is considered to exit successfully.
1286 /// use std::thread;
1289 /// fn copy_in_thread() -> thread::Result<()> {
1290 /// thread::spawn(move || { fs::copy("foo.txt", "bar.txt").unwrap(); }).join()
1294 /// match copy_in_thread() {
1295 /// Ok(_) => println!("this is fine"),
1296 /// Err(_) => println!("thread panicked"),
1301 /// [`Result`]: crate::result::Result
1302 #[stable(feature = "rust1", since = "1.0.0")]
1303 pub type Result<T> = crate::result::Result<T, Box<dyn Any + Send + 'static>>;
1305 // This packet is used to communicate the return value between the child thread
1306 // and the parent thread. Memory is shared through the `Arc` within and there's
1307 // no need for a mutex here because synchronization happens with `join()` (the
1308 // parent thread never reads this packet until the child has exited).
1310 // This packet itself is then stored into a `JoinInner` which in turns is placed
1311 // in `JoinHandle` and `JoinGuard`. Due to the usage of `UnsafeCell` we need to
1312 // manually worry about impls like Send and Sync. The type `T` should
1313 // already always be Send (otherwise the thread could not have been created) and
1314 // this type is inherently Sync because no methods take &self. Regardless,
1315 // however, we add inheriting impls for Send/Sync to this type to ensure it's
1316 // Send/Sync and that future modifications will still appropriately classify it.
1317 struct Packet<T>(Arc<UnsafeCell<Option<Result<T>>>>);
1319 unsafe impl<T: Send> Send for Packet<T> {}
1320 unsafe impl<T: Sync> Sync for Packet<T> {}
1322 /// Inner representation for JoinHandle
1323 struct JoinInner<T> {
1324 native: Option<imp::Thread>,
1329 impl<T> JoinInner<T> {
1330 fn join(&mut self) -> Result<T> {
1331 self.native.take().unwrap().join();
1332 unsafe { (*self.packet.0.get()).take().unwrap() }
1336 /// An owned permission to join on a thread (block on its termination).
1338 /// A `JoinHandle` *detaches* the associated thread when it is dropped, which
1339 /// means that there is no longer any handle to thread and no way to `join`
1342 /// Due to platform restrictions, it is not possible to [`Clone`] this
1343 /// handle: the ability to join a thread is a uniquely-owned permission.
1345 /// This `struct` is created by the [`thread::spawn`] function and the
1346 /// [`thread::Builder::spawn`] method.
1350 /// Creation from [`thread::spawn`]:
1353 /// use std::thread;
1355 /// let join_handle: thread::JoinHandle<_> = thread::spawn(|| {
1356 /// // some work here
1360 /// Creation from [`thread::Builder::spawn`]:
1363 /// use std::thread;
1365 /// let builder = thread::Builder::new();
1367 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1368 /// // some work here
1372 /// Child being detached and outliving its parent:
1375 /// use std::thread;
1376 /// use std::time::Duration;
1378 /// let original_thread = thread::spawn(|| {
1379 /// let _detached_thread = thread::spawn(|| {
1380 /// // Here we sleep to make sure that the first thread returns before.
1381 /// thread::sleep(Duration::from_millis(10));
1382 /// // This will be called, even though the JoinHandle is dropped.
1383 /// println!("♫ Still alive ♫");
1387 /// original_thread.join().expect("The thread being joined has panicked");
1388 /// println!("Original thread is joined.");
1390 /// // We make sure that the new thread has time to run, before the main
1391 /// // thread returns.
1393 /// thread::sleep(Duration::from_millis(1000));
1396 /// [`thread::Builder::spawn`]: Builder::spawn
1397 /// [`thread::spawn`]: spawn
1398 #[stable(feature = "rust1", since = "1.0.0")]
1399 pub struct JoinHandle<T>(JoinInner<T>);
1401 #[stable(feature = "joinhandle_impl_send_sync", since = "1.29.0")]
1402 unsafe impl<T> Send for JoinHandle<T> {}
1403 #[stable(feature = "joinhandle_impl_send_sync", since = "1.29.0")]
1404 unsafe impl<T> Sync for JoinHandle<T> {}
1406 impl<T> JoinHandle<T> {
1407 /// Extracts a handle to the underlying thread.
1412 /// use std::thread;
1414 /// let builder = thread::Builder::new();
1416 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1417 /// // some work here
1420 /// let thread = join_handle.thread();
1421 /// println!("thread id: {:?}", thread.id());
1423 #[stable(feature = "rust1", since = "1.0.0")]
1424 pub fn thread(&self) -> &Thread {
1428 /// Waits for the associated thread to finish.
1430 /// In terms of [atomic memory orderings], the completion of the associated
1431 /// thread synchronizes with this function returning. In other words, all
1432 /// operations performed by that thread are ordered before all
1433 /// operations that happen after `join` returns.
1435 /// If the child thread panics, [`Err`] is returned with the parameter given
1438 /// [`Err`]: crate::result::Result::Err
1439 /// [atomic memory orderings]: crate::sync::atomic
1443 /// This function may panic on some platforms if a thread attempts to join
1444 /// itself or otherwise may create a deadlock with joining threads.
1449 /// use std::thread;
1451 /// let builder = thread::Builder::new();
1453 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1454 /// // some work here
1456 /// join_handle.join().expect("Couldn't join on the associated thread");
1458 #[stable(feature = "rust1", since = "1.0.0")]
1459 pub fn join(mut self) -> Result<T> {
1464 impl<T> AsInner<imp::Thread> for JoinHandle<T> {
1465 fn as_inner(&self) -> &imp::Thread {
1466 self.0.native.as_ref().unwrap()
1470 impl<T> IntoInner<imp::Thread> for JoinHandle<T> {
1471 fn into_inner(self) -> imp::Thread {
1472 self.0.native.unwrap()
1476 #[stable(feature = "std_debug", since = "1.16.0")]
1477 impl<T> fmt::Debug for JoinHandle<T> {
1478 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1479 f.pad("JoinHandle { .. }")
1483 fn _assert_sync_and_send() {
1484 fn _assert_both<T: Send + Sync>() {}
1485 _assert_both::<JoinHandle<()>>();
1486 _assert_both::<Thread>();