]> git.lizzy.rs Git - rust.git/blob - library/std/src/thread/mod.rs
Auto merge of #70743 - oli-obk:eager_const_to_pat_conversion, r=eddyb
[rust.git] / library / std / src / thread / mod.rs
1 //! Native threads.
2 //!
3 //! ## The threading model
4 //!
5 //! An executing Rust program consists of a collection of native OS threads,
6 //! each with their own stack and local state. Threads can be named, and
7 //! provide some built-in support for low-level synchronization.
8 //!
9 //! Communication between threads can be done through
10 //! [channels], Rust's message-passing types, along with [other forms of thread
11 //! synchronization](../../std/sync/index.html) and shared-memory data
12 //! structures. In particular, types that are guaranteed to be
13 //! threadsafe are easily shared between threads using the
14 //! atomically-reference-counted container, [`Arc`].
15 //!
16 //! Fatal logic errors in Rust cause *thread panic*, during which
17 //! a thread will unwind the stack, running destructors and freeing
18 //! owned resources. While not meant as a 'try/catch' mechanism, panics
19 //! in Rust can nonetheless be caught (unless compiling with `panic=abort`) with
20 //! [`catch_unwind`](../../std/panic/fn.catch_unwind.html) and recovered
21 //! from, or alternatively be resumed with
22 //! [`resume_unwind`](../../std/panic/fn.resume_unwind.html). If the panic
23 //! is not caught the thread will exit, but the panic may optionally be
24 //! detected from a different thread with [`join`]. If the main thread panics
25 //! without the panic being caught, the application will exit with a
26 //! non-zero exit code.
27 //!
28 //! When the main thread of a Rust program terminates, the entire program shuts
29 //! down, even if other threads are still running. However, this module provides
30 //! convenient facilities for automatically waiting for the termination of a
31 //! child 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" 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.
48 //!
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:
52 //!
53 //! ```rust
54 //! use std::thread;
55 //!
56 //! let child = thread::spawn(move || {
57 //!     // some work here
58 //! });
59 //! // some work here
60 //! let res = child.join();
61 //! ```
62 //!
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.
66 //!
67 //! ## Configuring threads
68 //!
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:
71 //!
72 //! ```rust
73 //! # #![allow(unused_must_use)]
74 //! use std::thread;
75 //!
76 //! thread::Builder::new().name("child1".to_string()).spawn(move || {
77 //!     println!("Hello, world!");
78 //! });
79 //! ```
80 //!
81 //! ## The `Thread` type
82 //!
83 //! Threads are represented via the [`Thread`] type, which you can get in one of
84 //! two ways:
85 //!
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.
89 //!
90 //! The [`thread::current`] function is available even for threads not spawned
91 //! by the APIs of this module.
92 //!
93 //! ## Thread-local storage
94 //!
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.
99 //!
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.
108 //!
109 //! ## Naming threads
110 //!
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:
115 //!
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).
119 //!
120 //! ## Stack size
121 //!
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
124 //! spawned threads:
125 //!
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.
129 //!
130 //! Note that the stack size of the main thread is *not* determined by Rust.
131 //!
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
145
146 #![stable(feature = "rust1", since = "1.0.0")]
147 #![deny(unsafe_op_in_unsafe_fn)]
148
149 #[cfg(all(test, not(target_os = "emscripten")))]
150 mod tests;
151
152 use crate::any::Any;
153 use crate::cell::UnsafeCell;
154 use crate::ffi::{CStr, CString};
155 use crate::fmt;
156 use crate::io;
157 use crate::mem;
158 use crate::num::NonZeroU64;
159 use crate::panic;
160 use crate::panicking;
161 use crate::str;
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;
171
172 ////////////////////////////////////////////////////////////////////////////////
173 // Thread-local storage
174 ////////////////////////////////////////////////////////////////////////////////
175
176 #[macro_use]
177 mod local;
178
179 #[stable(feature = "rust1", since = "1.0.0")]
180 pub use self::local::{AccessError, LocalKey};
181
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.
190
191 #[unstable(feature = "libstd_thread_internals", issue = "none")]
192 #[cfg(target_thread_local)]
193 #[doc(hidden)]
194 pub use self::local::fast::Key as __FastLocalKeyInner;
195 #[unstable(feature = "libstd_thread_internals", issue = "none")]
196 #[doc(hidden)]
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")))]
200 #[doc(hidden)]
201 pub use self::local::statik::Key as __StaticLocalKeyInner;
202
203 ////////////////////////////////////////////////////////////////////////////////
204 // Builder
205 ////////////////////////////////////////////////////////////////////////////////
206
207 /// Thread factory, which can be used in order to configure the properties of
208 /// a new thread.
209 ///
210 /// Methods can be chained on it in order to configure it.
211 ///
212 /// The two configurations available are:
213 ///
214 /// - [`name`]: specifies an [associated name for the thread][naming-threads]
215 /// - [`stack_size`]: specifies the [desired stack size for the thread][stack-size]
216 ///
217 /// The [`spawn`] method will take ownership of the builder and create an
218 /// [`io::Result`] to the thread handle with the given configuration.
219 ///
220 /// The [`thread::spawn`] free function uses a `Builder` with default
221 /// configuration and [`unwrap`]s its return value.
222 ///
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`].
226 ///
227 /// # Examples
228 ///
229 /// ```
230 /// use std::thread;
231 ///
232 /// let builder = thread::Builder::new();
233 ///
234 /// let handler = builder.spawn(|| {
235 ///     // thread code
236 /// }).unwrap();
237 ///
238 /// handler.join().unwrap();
239 /// ```
240 ///
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")]
250 #[derive(Debug)]
251 pub struct Builder {
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>,
256 }
257
258 impl Builder {
259     /// Generates the base configuration for spawning a thread, from which
260     /// configuration methods can be chained.
261     ///
262     /// # Examples
263     ///
264     /// ```
265     /// use std::thread;
266     ///
267     /// let builder = thread::Builder::new()
268     ///                               .name("foo".into())
269     ///                               .stack_size(32 * 1024);
270     ///
271     /// let handler = builder.spawn(|| {
272     ///     // thread code
273     /// }).unwrap();
274     ///
275     /// handler.join().unwrap();
276     /// ```
277     #[stable(feature = "rust1", since = "1.0.0")]
278     pub fn new() -> Builder {
279         Builder { name: None, stack_size: None }
280     }
281
282     /// Names the thread-to-be. Currently the name is used for identification
283     /// only in panic messages.
284     ///
285     /// The name must not contain null bytes (`\0`).
286     ///
287     /// For more information about named threads, see
288     /// [this module-level documentation][naming-threads].
289     ///
290     /// # Examples
291     ///
292     /// ```
293     /// use std::thread;
294     ///
295     /// let builder = thread::Builder::new()
296     ///     .name("foo".into());
297     ///
298     /// let handler = builder.spawn(|| {
299     ///     assert_eq!(thread::current().name(), Some("foo"))
300     /// }).unwrap();
301     ///
302     /// handler.join().unwrap();
303     /// ```
304     ///
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);
309         self
310     }
311
312     /// Sets the size of the stack (in bytes) for the new thread.
313     ///
314     /// The actual stack size may be greater than this value if
315     /// the platform specifies a minimal stack size.
316     ///
317     /// For more information about the stack size for threads, see
318     /// [this module-level documentation][stack-size].
319     ///
320     /// # Examples
321     ///
322     /// ```
323     /// use std::thread;
324     ///
325     /// let builder = thread::Builder::new().stack_size(32 * 1024);
326     /// ```
327     ///
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);
332         self
333     }
334
335     /// Spawns a new thread by taking ownership of the `Builder`, and returns an
336     /// [`io::Result`] to its [`JoinHandle`].
337     ///
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.
342     ///
343     /// For a more complete documentation see [`thread::spawn`][`spawn`].
344     ///
345     /// # Errors
346     ///
347     /// Unlike the [`spawn`] free function, this method yields an
348     /// [`io::Result`] to capture any failure to create the thread at
349     /// the OS level.
350     ///
351     /// [`io::Result`]: crate::io::Result
352     ///
353     /// # Panics
354     ///
355     /// Panics if a thread name was set and it contained null bytes.
356     ///
357     /// # Examples
358     ///
359     /// ```
360     /// use std::thread;
361     ///
362     /// let builder = thread::Builder::new();
363     ///
364     /// let handler = builder.spawn(|| {
365     ///     // thread code
366     /// }).unwrap();
367     ///
368     /// handler.join().unwrap();
369     /// ```
370     #[stable(feature = "rust1", since = "1.0.0")]
371     pub fn spawn<F, T>(self, f: F) -> io::Result<JoinHandle<T>>
372     where
373         F: FnOnce() -> T,
374         F: Send + 'static,
375         T: Send + 'static,
376     {
377         unsafe { self.spawn_unchecked(f) }
378     }
379
380     /// Spawns a new thread without any lifetime restrictions by taking ownership
381     /// of the `Builder`, and returns an [`io::Result`] to its [`JoinHandle`].
382     ///
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.
387     ///
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`].
391     ///
392     /// # Errors
393     ///
394     /// Unlike the [`spawn`] free function, this method yields an
395     /// [`io::Result`] to capture any failure to create the thread at
396     /// the OS level.
397     ///
398     /// # Panics
399     ///
400     /// Panics if a thread name was set and it contained null bytes.
401     ///
402     /// # Safety
403     ///
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:
407     ///
408     /// - ensure that [`join`][`JoinHandle::join`] is called before any referenced
409     /// data is dropped
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)
413     ///
414     /// # Examples
415     ///
416     /// ```
417     /// #![feature(thread_spawn_unchecked)]
418     /// use std::thread;
419     ///
420     /// let builder = thread::Builder::new();
421     ///
422     /// let x = 1;
423     /// let thread_x = &x;
424     ///
425     /// let handler = unsafe {
426     ///     builder.spawn_unchecked(move || {
427     ///         println!("x = {}", *thread_x);
428     ///     }).unwrap()
429     /// };
430     ///
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();
435     /// ```
436     ///
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>>
440     where
441         F: FnOnce() -> T,
442         F: Send + 'a,
443         T: Send + 'a,
444     {
445         let Builder { name, stack_size } = self;
446
447         let stack_size = stack_size.unwrap_or_else(thread::min_stack);
448
449         let my_thread = Thread::new(name);
450         let their_thread = my_thread.clone();
451
452         let my_packet: Arc<UnsafeCell<Option<Result<T>>>> = Arc::new(UnsafeCell::new(None));
453         let their_packet = my_packet.clone();
454
455         let main = move || {
456             if let Some(name) = their_thread.cname() {
457                 imp::Thread::set_name(name);
458             }
459
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)
466             }));
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) };
472         };
473
474         Ok(JoinHandle(JoinInner {
475             // SAFETY:
476             //
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.
480             //
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.
484             //
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`
487             // returning.
488             native: unsafe {
489                 Some(imp::Thread::new(
490                     stack_size,
491                     mem::transmute::<Box<dyn FnOnce() + 'a>, Box<dyn FnOnce() + 'static>>(
492                         Box::new(main),
493                     ),
494                 )?)
495             },
496             thread: my_thread,
497             packet: Packet(my_packet),
498         }))
499     }
500 }
501
502 ////////////////////////////////////////////////////////////////////////////////
503 // Free functions
504 ////////////////////////////////////////////////////////////////////////////////
505
506 /// Spawns a new thread, returning a [`JoinHandle`] for it.
507 ///
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
514 /// [`panic!`].
515 ///
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
518 /// instead.
519 ///
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:
522 ///
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
526 ///   created in.
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`
531 ///   lifetime.
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.
539 ///
540 /// # Panics
541 ///
542 /// Panics if the OS fails to create a thread; use [`Builder::spawn`]
543 /// to recover from such errors.
544 ///
545 /// # Examples
546 ///
547 /// Creating a thread.
548 ///
549 /// ```
550 /// use std::thread;
551 ///
552 /// let handler = thread::spawn(|| {
553 ///     // thread code
554 /// });
555 ///
556 /// handler.join().unwrap();
557 /// ```
558 ///
559 /// As mentioned in the module documentation, threads are usually made to
560 /// communicate using [`channels`], here is how it usually looks.
561 ///
562 /// This example also shows how to use `move`, in order to give ownership
563 /// of values to a thread.
564 ///
565 /// ```
566 /// use std::thread;
567 /// use std::sync::mpsc::channel;
568 ///
569 /// let (tx, rx) = channel();
570 ///
571 /// let sender = thread::spawn(move || {
572 ///     tx.send("Hello, thread".to_owned())
573 ///         .expect("Unable to send on channel");
574 /// });
575 ///
576 /// let receiver = thread::spawn(move || {
577 ///     let value = rx.recv().expect("Unable to receive from channel");
578 ///     println!("{}", value);
579 /// });
580 ///
581 /// sender.join().expect("The sender thread has panicked");
582 /// receiver.join().expect("The receiver thread has panicked");
583 /// ```
584 ///
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
587 /// though).
588 ///
589 /// ```
590 /// use std::thread;
591 ///
592 /// let computation = thread::spawn(|| {
593 ///     // Some expensive computation.
594 ///     42
595 /// });
596 ///
597 /// let result = computation.join().unwrap();
598 /// println!("{}", result);
599 /// ```
600 ///
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>
606 where
607     F: FnOnce() -> T,
608     F: Send + 'static,
609     T: Send + 'static,
610 {
611     Builder::new().spawn(f).expect("failed to spawn thread")
612 }
613
614 /// Gets a handle to the thread that invokes it.
615 ///
616 /// # Examples
617 ///
618 /// Getting a handle to the current thread with `thread::current()`:
619 ///
620 /// ```
621 /// use std::thread;
622 ///
623 /// let handler = thread::Builder::new()
624 ///     .name("named thread".into())
625 ///     .spawn(|| {
626 ///         let handle = thread::current();
627 ///         assert_eq!(handle.name(), Some("named thread"));
628 ///     })
629 ///     .unwrap();
630 ///
631 /// handler.join().unwrap();
632 /// ```
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",
638     )
639 }
640
641 /// Cooperatively gives up a timeslice to the OS scheduler.
642 ///
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.
645 ///
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.
648 ///
649 /// Thus the pattern of `yield`ing after a failed poll is rather common when
650 /// implementing low-level shared resources or synchronization primitives.
651 ///
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.
655 ///
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.
659 ///
660 /// # Examples
661 ///
662 /// ```
663 /// use std::thread;
664 ///
665 /// thread::yield_now();
666 /// ```
667 ///
668 /// [`channel`]: crate::sync::mpsc
669 /// [`join`]: JoinHandle::join
670 #[stable(feature = "rust1", since = "1.0.0")]
671 pub fn yield_now() {
672     imp::Thread::yield_now()
673 }
674
675 /// Determines whether the current thread is unwinding because of panic.
676 ///
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.
679 ///
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.
682 ///
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).
686 ///
687 /// # Examples
688 ///
689 /// ```should_panic
690 /// use std::thread;
691 ///
692 /// struct SomeStruct;
693 ///
694 /// impl Drop for SomeStruct {
695 ///     fn drop(&mut self) {
696 ///         if thread::panicking() {
697 ///             println!("dropped while unwinding");
698 ///         } else {
699 ///             println!("dropped while not unwinding");
700 ///         }
701 ///     }
702 /// }
703 ///
704 /// {
705 ///     print!("a: ");
706 ///     let a = SomeStruct;
707 /// }
708 ///
709 /// {
710 ///     print!("b: ");
711 ///     let b = SomeStruct;
712 ///     panic!()
713 /// }
714 /// ```
715 #[inline]
716 #[stable(feature = "rust1", since = "1.0.0")]
717 pub fn panicking() -> bool {
718     panicking::panicking()
719 }
720
721 /// Puts the current thread to sleep for at least the specified amount of time.
722 ///
723 /// The thread may sleep longer than the duration specified due to scheduling
724 /// specifics or platform-dependent functionality. It will never sleep less.
725 ///
726 /// This function is blocking, and should not be used in `async` functions.
727 ///
728 /// # Platform-specific behavior
729 ///
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
733 /// times.
734 ///
735 /// # Examples
736 ///
737 /// ```no_run
738 /// use std::thread;
739 ///
740 /// // Let's sleep for 2 seconds:
741 /// thread::sleep_ms(2000);
742 /// ```
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))
747 }
748
749 /// Puts the current thread to sleep for at least the specified amount of time.
750 ///
751 /// The thread may sleep longer than the duration specified due to scheduling
752 /// specifics or platform-dependent functionality. It will never sleep less.
753 ///
754 /// This function is blocking, and should not be used in `async` functions.
755 ///
756 /// # Platform-specific behavior
757 ///
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
761 /// times.
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.
764 ///
765 /// # Examples
766 ///
767 /// ```no_run
768 /// use std::{thread, time};
769 ///
770 /// let ten_millis = time::Duration::from_millis(10);
771 /// let now = time::Instant::now();
772 ///
773 /// thread::sleep(ten_millis);
774 ///
775 /// assert!(now.elapsed() >= ten_millis);
776 /// ```
777 #[stable(feature = "thread_sleep", since = "1.4.0")]
778 pub fn sleep(dur: Duration) {
779     imp::Thread::sleep(dur)
780 }
781
782 // constants for park/unpark
783 const EMPTY: usize = 0;
784 const PARKED: usize = 1;
785 const NOTIFIED: usize = 2;
786
787 /// Blocks unless or until the current thread's token is made available.
788 ///
789 /// A call to `park` does not guarantee that the thread will remain parked
790 /// forever, and callers should be prepared for this possibility.
791 ///
792 /// # park and unpark
793 ///
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
798 /// handle.
799 ///
800 /// Conceptually, each [`Thread`] handle has an associated token, which is
801 /// initially not present:
802 ///
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.
808 ///
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.
812 ///
813 /// In other words, each [`Thread`] acts a bit like a spinlock that can be
814 /// locked and unlocked using `park` and `unpark`.
815 ///
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.
820 ///
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.
825 ///
826 /// The motivation for this design is twofold:
827 ///
828 /// * It avoids the need to allocate mutexes and condvars when building new
829 ///   synchronization primitives; the threads already provide basic
830 ///   blocking/signaling.
831 ///
832 /// * It can be implemented very efficiently on many platforms.
833 ///
834 /// # Examples
835 ///
836 /// ```
837 /// use std::thread;
838 /// use std::sync::{Arc, atomic::{Ordering, AtomicBool}};
839 /// use std::time::Duration;
840 ///
841 /// let flag = Arc::new(AtomicBool::new(false));
842 /// let flag2 = Arc::clone(&flag);
843 ///
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");
849 ///         thread::park();
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");
853 ///     }
854 ///     println!("Flag received");
855 /// });
856 ///
857 /// // Let some time pass for the thread to be spawned.
858 /// thread::sleep(Duration::from_millis(10));
859 ///
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();
867 ///
868 /// parked_thread.join().unwrap();
869 /// ```
870 ///
871 /// [`unpark`]: Thread::unpark
872 /// [`thread::park_timeout`]: park_timeout
873 //
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")]
880 pub fn park() {
881     let thread = current();
882
883     // If we were previously notified then we consume this notification and
884     // return quickly.
885     if thread.inner.state.compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst).is_ok() {
886         return;
887     }
888
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) {
892         Ok(_) => {}
893         Err(NOTIFIED) => {
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");
902             return;
903         } // should consume this notification, so prohibit spurious wakeups in next park.
904         Err(_) => panic!("inconsistent park state"),
905     }
906     loop {
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
911         }
912     }
913 }
914
915 /// Use [`park_timeout`].
916 ///
917 /// Blocks unless or until the current thread's token is made available or
918 /// the specified duration has been reached (may wake spuriously).
919 ///
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.
925 ///
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))
931 }
932
933 /// Blocks unless or until the current thread's token is made available or
934 /// the specified duration has been reached (may wake spuriously).
935 ///
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.
941 ///
942 /// See the [park documentation][park] for more details.
943 ///
944 /// # Platform-specific behavior
945 ///
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.
948 ///
949 /// # Examples
950 ///
951 /// Waiting for the complete expiration of the timeout:
952 ///
953 /// ```rust,no_run
954 /// use std::thread::park_timeout;
955 /// use std::time::{Instant, Duration};
956 ///
957 /// let timeout = Duration::from_secs(2);
958 /// let beginning_park = Instant::now();
959 ///
960 /// let mut timeout_remaining = timeout;
961 /// loop {
962 ///     park_timeout(timeout_remaining);
963 ///     let elapsed = beginning_park.elapsed();
964 ///     if elapsed >= timeout {
965 ///         break;
966 ///     }
967 ///     println!("restarting park_timeout after {:?}", elapsed);
968 ///     timeout_remaining = timeout - elapsed;
969 /// }
970 /// ```
971 #[stable(feature = "park_timeout", since = "1.4.0")]
972 pub fn park_timeout(dur: Duration) {
973     let thread = current();
974
975     // Like `park` above we have a fast path for an already-notified thread, and
976     // afterwards we start coordinating for a sleep.
977     // return quickly.
978     if thread.inner.state.compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst).is_ok() {
979         return;
980     }
981     let m = thread.inner.lock.lock().unwrap();
982     match thread.inner.state.compare_exchange(EMPTY, PARKED, SeqCst, SeqCst) {
983         Ok(_) => {}
984         Err(NOTIFIED) => {
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");
988             return;
989         } // should consume this notification, so prohibit spurious wakeups in next park.
990         Err(_) => panic!("inconsistent park_timeout state"),
991     }
992
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
996     // parked.
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),
1002     }
1003 }
1004
1005 ////////////////////////////////////////////////////////////////////////////////
1006 // ThreadId
1007 ////////////////////////////////////////////////////////////////////////////////
1008
1009 /// A unique identifier for a running thread.
1010 ///
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`].
1015 ///
1016 /// # Examples
1017 ///
1018 /// ```
1019 /// use std::thread;
1020 ///
1021 /// let other_thread = thread::spawn(|| {
1022 ///     thread::current().id()
1023 /// });
1024 ///
1025 /// let other_thread_id = other_thread.join().unwrap();
1026 /// assert!(thread::current().id() != other_thread_id);
1027 /// ```
1028 ///
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);
1033
1034 impl ThreadId {
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;
1041
1042         unsafe {
1043             let _guard = GUARD.lock();
1044
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");
1049             }
1050
1051             let id = COUNTER;
1052             COUNTER += 1;
1053
1054             ThreadId(NonZeroU64::new(id).unwrap())
1055         }
1056     }
1057
1058     /// This returns a numeric identifier for the thread identified by this
1059     /// `ThreadId`.
1060     ///
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 {
1068         self.0
1069     }
1070 }
1071
1072 ////////////////////////////////////////////////////////////////////////////////
1073 // Thread
1074 ////////////////////////////////////////////////////////////////////////////////
1075
1076 /// The internal representation of a `Thread` handle
1077 struct Inner {
1078     name: Option<CString>, // Guaranteed to be UTF-8
1079     id: ThreadId,
1080
1081     // state for thread park/unpark
1082     state: AtomicUsize,
1083     lock: Mutex<()>,
1084     cvar: Condvar,
1085 }
1086
1087 #[derive(Clone)]
1088 #[stable(feature = "rust1", since = "1.0.0")]
1089 /// A handle to a thread.
1090 ///
1091 /// Threads are represented via the `Thread` type, which you can get in one of
1092 /// two ways:
1093 ///
1094 /// * By spawning a new thread, e.g., using the [`thread::spawn`][`spawn`]
1095 ///   function, and calling [`thread`][`JoinHandle::thread`] on the
1096 ///   [`JoinHandle`].
1097 /// * By requesting the current thread, using the [`thread::current`] function.
1098 ///
1099 /// The [`thread::current`] function is available even for threads not spawned
1100 /// by the APIs of this module.
1101 ///
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.
1105 ///
1106 /// [`thread::current`]: current
1107 pub struct Thread {
1108     inner: Arc<Inner>,
1109 }
1110
1111 impl Thread {
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 {
1115         let cname =
1116             name.map(|n| CString::new(n).expect("thread name may not contain interior null bytes"));
1117         Thread {
1118             inner: Arc::new(Inner {
1119                 name: cname,
1120                 id: ThreadId::new(),
1121                 state: AtomicUsize::new(EMPTY),
1122                 lock: Mutex::new(()),
1123                 cvar: Condvar::new(),
1124             }),
1125         }
1126     }
1127
1128     /// Atomically makes the handle's token available if it is not already.
1129     ///
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.
1133     ///
1134     /// See the [park documentation][park] for more details.
1135     ///
1136     /// # Examples
1137     ///
1138     /// ```
1139     /// use std::thread;
1140     /// use std::time::Duration;
1141     ///
1142     /// let parked_thread = thread::Builder::new()
1143     ///     .spawn(|| {
1144     ///         println!("Parking thread");
1145     ///         thread::park();
1146     ///         println!("Thread unparked");
1147     ///     })
1148     ///     .unwrap();
1149     ///
1150     /// // Let some time pass for the thread to be spawned.
1151     /// thread::sleep(Duration::from_millis(10));
1152     ///
1153     /// println!("Unpark the thread");
1154     /// parked_thread.thread().unpark();
1155     ///
1156     /// parked_thread.join().unwrap();
1157     /// ```
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`
1165         // on failure.
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"),
1171         }
1172
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.
1180         //
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()
1186     }
1187
1188     /// Gets the thread's unique identifier.
1189     ///
1190     /// # Examples
1191     ///
1192     /// ```
1193     /// use std::thread;
1194     ///
1195     /// let other_thread = thread::spawn(|| {
1196     ///     thread::current().id()
1197     /// });
1198     ///
1199     /// let other_thread_id = other_thread.join().unwrap();
1200     /// assert!(thread::current().id() != other_thread_id);
1201     /// ```
1202     #[stable(feature = "thread_id", since = "1.19.0")]
1203     pub fn id(&self) -> ThreadId {
1204         self.inner.id
1205     }
1206
1207     /// Gets the thread's name.
1208     ///
1209     /// For more information about named threads, see
1210     /// [this module-level documentation][naming-threads].
1211     ///
1212     /// # Examples
1213     ///
1214     /// Threads by default have no name specified:
1215     ///
1216     /// ```
1217     /// use std::thread;
1218     ///
1219     /// let builder = thread::Builder::new();
1220     ///
1221     /// let handler = builder.spawn(|| {
1222     ///     assert!(thread::current().name().is_none());
1223     /// }).unwrap();
1224     ///
1225     /// handler.join().unwrap();
1226     /// ```
1227     ///
1228     /// Thread with a specified name:
1229     ///
1230     /// ```
1231     /// use std::thread;
1232     ///
1233     /// let builder = thread::Builder::new()
1234     ///     .name("foo".into());
1235     ///
1236     /// let handler = builder.spawn(|| {
1237     ///     assert_eq!(thread::current().name(), Some("foo"))
1238     /// }).unwrap();
1239     ///
1240     /// handler.join().unwrap();
1241     /// ```
1242     ///
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()) })
1247     }
1248
1249     fn cname(&self) -> Option<&CStr> {
1250         self.inner.name.as_deref()
1251     }
1252 }
1253
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()
1258     }
1259 }
1260
1261 ////////////////////////////////////////////////////////////////////////////////
1262 // JoinHandle
1263 ////////////////////////////////////////////////////////////////////////////////
1264
1265 /// A specialized [`Result`] type for threads.
1266 ///
1267 /// Indicates the manner in which a thread exited.
1268 ///
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.
1274 ///
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.
1280 ///
1281 /// A thread that completes without panicking is considered to exit successfully.
1282 ///
1283 /// # Examples
1284 ///
1285 /// ```no_run
1286 /// use std::thread;
1287 /// use std::fs;
1288 ///
1289 /// fn copy_in_thread() -> thread::Result<()> {
1290 ///     thread::spawn(move || { fs::copy("foo.txt", "bar.txt").unwrap(); }).join()
1291 /// }
1292 ///
1293 /// fn main() {
1294 ///     match copy_in_thread() {
1295 ///         Ok(_) => println!("this is fine"),
1296 ///         Err(_) => println!("thread panicked"),
1297 ///     }
1298 /// }
1299 /// ```
1300 ///
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>>;
1304
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).
1309 //
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>>>>);
1318
1319 unsafe impl<T: Send> Send for Packet<T> {}
1320 unsafe impl<T: Sync> Sync for Packet<T> {}
1321
1322 /// Inner representation for JoinHandle
1323 struct JoinInner<T> {
1324     native: Option<imp::Thread>,
1325     thread: Thread,
1326     packet: Packet<T>,
1327 }
1328
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() }
1333     }
1334 }
1335
1336 /// An owned permission to join on a thread (block on its termination).
1337 ///
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`
1340 /// on it.
1341 ///
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.
1344 ///
1345 /// This `struct` is created by the [`thread::spawn`] function and the
1346 /// [`thread::Builder::spawn`] method.
1347 ///
1348 /// # Examples
1349 ///
1350 /// Creation from [`thread::spawn`]:
1351 ///
1352 /// ```
1353 /// use std::thread;
1354 ///
1355 /// let join_handle: thread::JoinHandle<_> = thread::spawn(|| {
1356 ///     // some work here
1357 /// });
1358 /// ```
1359 ///
1360 /// Creation from [`thread::Builder::spawn`]:
1361 ///
1362 /// ```
1363 /// use std::thread;
1364 ///
1365 /// let builder = thread::Builder::new();
1366 ///
1367 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1368 ///     // some work here
1369 /// }).unwrap();
1370 /// ```
1371 ///
1372 /// Child being detached and outliving its parent:
1373 ///
1374 /// ```no_run
1375 /// use std::thread;
1376 /// use std::time::Duration;
1377 ///
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 ♫");
1384 ///     });
1385 /// });
1386 ///
1387 /// original_thread.join().expect("The thread being joined has panicked");
1388 /// println!("Original thread is joined.");
1389 ///
1390 /// // We make sure that the new thread has time to run, before the main
1391 /// // thread returns.
1392 ///
1393 /// thread::sleep(Duration::from_millis(1000));
1394 /// ```
1395 ///
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>);
1400
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> {}
1405
1406 impl<T> JoinHandle<T> {
1407     /// Extracts a handle to the underlying thread.
1408     ///
1409     /// # Examples
1410     ///
1411     /// ```
1412     /// use std::thread;
1413     ///
1414     /// let builder = thread::Builder::new();
1415     ///
1416     /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1417     ///     // some work here
1418     /// }).unwrap();
1419     ///
1420     /// let thread = join_handle.thread();
1421     /// println!("thread id: {:?}", thread.id());
1422     /// ```
1423     #[stable(feature = "rust1", since = "1.0.0")]
1424     pub fn thread(&self) -> &Thread {
1425         &self.0.thread
1426     }
1427
1428     /// Waits for the associated thread to finish.
1429     ///
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.
1434     ///
1435     /// If the child thread panics, [`Err`] is returned with the parameter given
1436     /// to [`panic!`].
1437     ///
1438     /// [`Err`]: crate::result::Result::Err
1439     /// [atomic memory orderings]: crate::sync::atomic
1440     ///
1441     /// # Panics
1442     ///
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.
1445     ///
1446     /// # Examples
1447     ///
1448     /// ```
1449     /// use std::thread;
1450     ///
1451     /// let builder = thread::Builder::new();
1452     ///
1453     /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1454     ///     // some work here
1455     /// }).unwrap();
1456     /// join_handle.join().expect("Couldn't join on the associated thread");
1457     /// ```
1458     #[stable(feature = "rust1", since = "1.0.0")]
1459     pub fn join(mut self) -> Result<T> {
1460         self.0.join()
1461     }
1462 }
1463
1464 impl<T> AsInner<imp::Thread> for JoinHandle<T> {
1465     fn as_inner(&self) -> &imp::Thread {
1466         self.0.native.as_ref().unwrap()
1467     }
1468 }
1469
1470 impl<T> IntoInner<imp::Thread> for JoinHandle<T> {
1471     fn into_inner(self) -> imp::Thread {
1472         self.0.native.unwrap()
1473     }
1474 }
1475
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 { .. }")
1480     }
1481 }
1482
1483 fn _assert_sync_and_send() {
1484     fn _assert_both<T: Send + Sync>() {}
1485     _assert_both::<JoinHandle<()>>();
1486     _assert_both::<Thread>();
1487 }