]> git.lizzy.rs Git - rust.git/blob - library/std/src/thread/mod.rs
Fix font color for help button in ayu and dark themes
[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]: ../../std/sync/mpsc/index.html
133 //! [`Arc`]: ../../std/sync/struct.Arc.html
134 //! [`spawn`]: ../../std/thread/fn.spawn.html
135 //! [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
136 //! [`JoinHandle::thread`]: ../../std/thread/struct.JoinHandle.html#method.thread
137 //! [`join`]: ../../std/thread/struct.JoinHandle.html#method.join
138 //! [`Result`]: ../../std/result/enum.Result.html
139 //! [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
140 //! [`Err`]: ../../std/result/enum.Result.html#variant.Err
141 //! [`panic!`]: ../../std/macro.panic.html
142 //! [`Builder`]: ../../std/thread/struct.Builder.html
143 //! [`Builder::stack_size`]: ../../std/thread/struct.Builder.html#method.stack_size
144 //! [`Builder::name`]: ../../std/thread/struct.Builder.html#method.name
145 //! [`thread::current`]: ../../std/thread/fn.current.html
146 //! [`thread::Result`]: ../../std/thread/type.Result.html
147 //! [`Thread`]: ../../std/thread/struct.Thread.html
148 //! [`park`]: ../../std/thread/fn.park.html
149 //! [`unpark`]: ../../std/thread/struct.Thread.html#method.unpark
150 //! [`Thread::name`]: ../../std/thread/struct.Thread.html#method.name
151 //! [`thread::park_timeout`]: ../../std/thread/fn.park_timeout.html
152 //! [`Cell`]: ../cell/struct.Cell.html
153 //! [`RefCell`]: ../cell/struct.RefCell.html
154 //! [`thread_local!`]: ../macro.thread_local.html
155 //! [`with`]: struct.LocalKey.html#method.with
156
157 #![stable(feature = "rust1", since = "1.0.0")]
158
159 use crate::any::Any;
160 use crate::cell::UnsafeCell;
161 use crate::ffi::{CStr, CString};
162 use crate::fmt;
163 use crate::io;
164 use crate::mem;
165 use crate::num::NonZeroU64;
166 use crate::panic;
167 use crate::panicking;
168 use crate::str;
169 use crate::sync::atomic::AtomicUsize;
170 use crate::sync::atomic::Ordering::SeqCst;
171 use crate::sync::{Arc, Condvar, Mutex};
172 use crate::sys::thread as imp;
173 use crate::sys_common::mutex;
174 use crate::sys_common::thread;
175 use crate::sys_common::thread_info;
176 use crate::sys_common::{AsInner, IntoInner};
177 use crate::time::Duration;
178
179 ////////////////////////////////////////////////////////////////////////////////
180 // Thread-local storage
181 ////////////////////////////////////////////////////////////////////////////////
182
183 #[macro_use]
184 mod local;
185
186 #[stable(feature = "rust1", since = "1.0.0")]
187 pub use self::local::{AccessError, LocalKey};
188
189 // The types used by the thread_local! macro to access TLS keys. Note that there
190 // are two types, the "OS" type and the "fast" type. The OS thread local key
191 // type is accessed via platform-specific API calls and is slow, while the fast
192 // key type is accessed via code generated via LLVM, where TLS keys are set up
193 // by the elf linker. Note that the OS TLS type is always available: on macOS
194 // the standard library is compiled with support for older platform versions
195 // where fast TLS was not available; end-user code is compiled with fast TLS
196 // where available, but both are needed.
197
198 #[unstable(feature = "libstd_thread_internals", issue = "none")]
199 #[cfg(target_thread_local)]
200 #[doc(hidden)]
201 pub use self::local::fast::Key as __FastLocalKeyInner;
202 #[unstable(feature = "libstd_thread_internals", issue = "none")]
203 #[doc(hidden)]
204 pub use self::local::os::Key as __OsLocalKeyInner;
205 #[unstable(feature = "libstd_thread_internals", issue = "none")]
206 #[cfg(all(target_arch = "wasm32", not(target_feature = "atomics")))]
207 #[doc(hidden)]
208 pub use self::local::statik::Key as __StaticLocalKeyInner;
209
210 ////////////////////////////////////////////////////////////////////////////////
211 // Builder
212 ////////////////////////////////////////////////////////////////////////////////
213
214 /// Thread factory, which can be used in order to configure the properties of
215 /// a new thread.
216 ///
217 /// Methods can be chained on it in order to configure it.
218 ///
219 /// The two configurations available are:
220 ///
221 /// - [`name`]: specifies an [associated name for the thread][naming-threads]
222 /// - [`stack_size`]: specifies the [desired stack size for the thread][stack-size]
223 ///
224 /// The [`spawn`] method will take ownership of the builder and create an
225 /// [`io::Result`] to the thread handle with the given configuration.
226 ///
227 /// The [`thread::spawn`] free function uses a `Builder` with default
228 /// configuration and [`unwrap`]s its return value.
229 ///
230 /// You may want to use [`spawn`] instead of [`thread::spawn`], when you want
231 /// to recover from a failure to launch a thread, indeed the free function will
232 /// panic where the `Builder` method will return a [`io::Result`].
233 ///
234 /// # Examples
235 ///
236 /// ```
237 /// use std::thread;
238 ///
239 /// let builder = thread::Builder::new();
240 ///
241 /// let handler = builder.spawn(|| {
242 ///     // thread code
243 /// }).unwrap();
244 ///
245 /// handler.join().unwrap();
246 /// ```
247 ///
248 /// [`thread::spawn`]: ../../std/thread/fn.spawn.html
249 /// [`stack_size`]: ../../std/thread/struct.Builder.html#method.stack_size
250 /// [`name`]: ../../std/thread/struct.Builder.html#method.name
251 /// [`spawn`]: ../../std/thread/struct.Builder.html#method.spawn
252 /// [`io::Result`]: ../../std/io/type.Result.html
253 /// [`unwrap`]: ../../std/result/enum.Result.html#method.unwrap
254 /// [naming-threads]: ./index.html#naming-threads
255 /// [stack-size]: ./index.html#stack-size
256 #[stable(feature = "rust1", since = "1.0.0")]
257 #[derive(Debug)]
258 pub struct Builder {
259     // A name for the thread-to-be, for identification in panic messages
260     name: Option<String>,
261     // The size of the stack for the spawned thread in bytes
262     stack_size: Option<usize>,
263 }
264
265 impl Builder {
266     /// Generates the base configuration for spawning a thread, from which
267     /// configuration methods can be chained.
268     ///
269     /// # Examples
270     ///
271     /// ```
272     /// use std::thread;
273     ///
274     /// let builder = thread::Builder::new()
275     ///                               .name("foo".into())
276     ///                               .stack_size(32 * 1024);
277     ///
278     /// let handler = builder.spawn(|| {
279     ///     // thread code
280     /// }).unwrap();
281     ///
282     /// handler.join().unwrap();
283     /// ```
284     #[stable(feature = "rust1", since = "1.0.0")]
285     pub fn new() -> Builder {
286         Builder { name: None, stack_size: None }
287     }
288
289     /// Names the thread-to-be. Currently the name is used for identification
290     /// only in panic messages.
291     ///
292     /// The name must not contain null bytes (`\0`).
293     ///
294     /// For more information about named threads, see
295     /// [this module-level documentation][naming-threads].
296     ///
297     /// # Examples
298     ///
299     /// ```
300     /// use std::thread;
301     ///
302     /// let builder = thread::Builder::new()
303     ///     .name("foo".into());
304     ///
305     /// let handler = builder.spawn(|| {
306     ///     assert_eq!(thread::current().name(), Some("foo"))
307     /// }).unwrap();
308     ///
309     /// handler.join().unwrap();
310     /// ```
311     ///
312     /// [naming-threads]: ./index.html#naming-threads
313     #[stable(feature = "rust1", since = "1.0.0")]
314     pub fn name(mut self, name: String) -> Builder {
315         self.name = Some(name);
316         self
317     }
318
319     /// Sets the size of the stack (in bytes) for the new thread.
320     ///
321     /// The actual stack size may be greater than this value if
322     /// the platform specifies a minimal stack size.
323     ///
324     /// For more information about the stack size for threads, see
325     /// [this module-level documentation][stack-size].
326     ///
327     /// # Examples
328     ///
329     /// ```
330     /// use std::thread;
331     ///
332     /// let builder = thread::Builder::new().stack_size(32 * 1024);
333     /// ```
334     ///
335     /// [stack-size]: ./index.html#stack-size
336     #[stable(feature = "rust1", since = "1.0.0")]
337     pub fn stack_size(mut self, size: usize) -> Builder {
338         self.stack_size = Some(size);
339         self
340     }
341
342     /// Spawns a new thread by taking ownership of the `Builder`, and returns an
343     /// [`io::Result`] to its [`JoinHandle`].
344     ///
345     /// The spawned thread may outlive the caller (unless the caller thread
346     /// is the main thread; the whole process is terminated when the main
347     /// thread finishes). The join handle can be used to block on
348     /// termination of the child thread, including recovering its panics.
349     ///
350     /// For a more complete documentation see [`thread::spawn`][`spawn`].
351     ///
352     /// # Errors
353     ///
354     /// Unlike the [`spawn`] free function, this method yields an
355     /// [`io::Result`] to capture any failure to create the thread at
356     /// the OS level.
357     ///
358     /// [`spawn`]: ../../std/thread/fn.spawn.html
359     /// [`io::Result`]: ../../std/io/type.Result.html
360     /// [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
361     ///
362     /// # Panics
363     ///
364     /// Panics if a thread name was set and it contained null bytes.
365     ///
366     /// # Examples
367     ///
368     /// ```
369     /// use std::thread;
370     ///
371     /// let builder = thread::Builder::new();
372     ///
373     /// let handler = builder.spawn(|| {
374     ///     // thread code
375     /// }).unwrap();
376     ///
377     /// handler.join().unwrap();
378     /// ```
379     #[stable(feature = "rust1", since = "1.0.0")]
380     pub fn spawn<F, T>(self, f: F) -> io::Result<JoinHandle<T>>
381     where
382         F: FnOnce() -> T,
383         F: Send + 'static,
384         T: Send + 'static,
385     {
386         unsafe { self.spawn_unchecked(f) }
387     }
388
389     /// Spawns a new thread without any lifetime restrictions by taking ownership
390     /// of the `Builder`, and returns an [`io::Result`] to its [`JoinHandle`].
391     ///
392     /// The spawned thread may outlive the caller (unless the caller thread
393     /// is the main thread; the whole process is terminated when the main
394     /// thread finishes). The join handle can be used to block on
395     /// termination of the child thread, including recovering its panics.
396     ///
397     /// This method is identical to [`thread::Builder::spawn`][`Builder::spawn`],
398     /// except for the relaxed lifetime bounds, which render it unsafe.
399     /// For a more complete documentation see [`thread::spawn`][`spawn`].
400     ///
401     /// # Errors
402     ///
403     /// Unlike the [`spawn`] free function, this method yields an
404     /// [`io::Result`] to capture any failure to create the thread at
405     /// the OS level.
406     ///
407     /// # Panics
408     ///
409     /// Panics if a thread name was set and it contained null bytes.
410     ///
411     /// # Safety
412     ///
413     /// The caller has to ensure that no references in the supplied thread closure
414     /// or its return type can outlive the spawned thread's lifetime. This can be
415     /// guaranteed in two ways:
416     ///
417     /// - ensure that [`join`][`JoinHandle::join`] is called before any referenced
418     /// data is dropped
419     /// - use only types with `'static` lifetime bounds, i.e., those with no or only
420     /// `'static` references (both [`thread::Builder::spawn`][`Builder::spawn`]
421     /// and [`thread::spawn`][`spawn`] enforce this property statically)
422     ///
423     /// # Examples
424     ///
425     /// ```
426     /// #![feature(thread_spawn_unchecked)]
427     /// use std::thread;
428     ///
429     /// let builder = thread::Builder::new();
430     ///
431     /// let x = 1;
432     /// let thread_x = &x;
433     ///
434     /// let handler = unsafe {
435     ///     builder.spawn_unchecked(move || {
436     ///         println!("x = {}", *thread_x);
437     ///     }).unwrap()
438     /// };
439     ///
440     /// // caller has to ensure `join()` is called, otherwise
441     /// // it is possible to access freed memory if `x` gets
442     /// // dropped before the thread closure is executed!
443     /// handler.join().unwrap();
444     /// ```
445     ///
446     /// [`spawn`]: ../../std/thread/fn.spawn.html
447     /// [`Builder::spawn`]: ../../std/thread/struct.Builder.html#method.spawn
448     /// [`io::Result`]: ../../std/io/type.Result.html
449     /// [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
450     /// [`JoinHandle::join`]: ../../std/thread/struct.JoinHandle.html#method.join
451     #[unstable(feature = "thread_spawn_unchecked", issue = "55132")]
452     pub unsafe fn spawn_unchecked<'a, F, T>(self, f: F) -> io::Result<JoinHandle<T>>
453     where
454         F: FnOnce() -> T,
455         F: Send + 'a,
456         T: Send + 'a,
457     {
458         let Builder { name, stack_size } = self;
459
460         let stack_size = stack_size.unwrap_or_else(thread::min_stack);
461
462         let my_thread = Thread::new(name);
463         let their_thread = my_thread.clone();
464
465         let my_packet: Arc<UnsafeCell<Option<Result<T>>>> = Arc::new(UnsafeCell::new(None));
466         let their_packet = my_packet.clone();
467
468         let main = move || {
469             if let Some(name) = their_thread.cname() {
470                 imp::Thread::set_name(name);
471             }
472
473             thread_info::set(imp::guard::current(), their_thread);
474             let try_result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
475                 crate::sys_common::backtrace::__rust_begin_short_backtrace(f)
476             }));
477             *their_packet.get() = Some(try_result);
478         };
479
480         Ok(JoinHandle(JoinInner {
481             // `imp::Thread::new` takes a closure with a `'static` lifetime, since it's passed
482             // through FFI or otherwise used with low-level threading primitives that have no
483             // notion of or way to enforce lifetimes.
484             //
485             // As mentioned in the `Safety` section of this function's documentation, the caller of
486             // this function needs to guarantee that the passed-in lifetime is sufficiently long
487             // for the lifetime of the thread.
488             //
489             // Similarly, the `sys` implementation must guarantee that no references to the closure
490             // exist after the thread has terminated, which is signaled by `Thread::join`
491             // returning.
492             native: Some(imp::Thread::new(
493                 stack_size,
494                 mem::transmute::<Box<dyn FnOnce() + 'a>, Box<dyn FnOnce() + 'static>>(Box::new(
495                     main,
496                 )),
497             )?),
498             thread: my_thread,
499             packet: Packet(my_packet),
500         }))
501     }
502 }
503
504 ////////////////////////////////////////////////////////////////////////////////
505 // Free functions
506 ////////////////////////////////////////////////////////////////////////////////
507
508 /// Spawns a new thread, returning a [`JoinHandle`] for it.
509 ///
510 /// The join handle will implicitly *detach* the child thread upon being
511 /// dropped. In this case, the child thread may outlive the parent (unless
512 /// the parent thread is the main thread; the whole process is terminated when
513 /// the main thread finishes). Additionally, the join handle provides a [`join`]
514 /// method that can be used to join the child thread. If the child thread
515 /// panics, [`join`] will return an [`Err`] containing the argument given to
516 /// [`panic`].
517 ///
518 /// This will create a thread using default parameters of [`Builder`], if you
519 /// want to specify the stack size or the name of the thread, use this API
520 /// instead.
521 ///
522 /// As you can see in the signature of `spawn` there are two constraints on
523 /// both the closure given to `spawn` and its return value, let's explain them:
524 ///
525 /// - The `'static` constraint means that the closure and its return value
526 ///   must have a lifetime of the whole program execution. The reason for this
527 ///   is that threads can `detach` and outlive the lifetime they have been
528 ///   created in.
529 ///   Indeed if the thread, and by extension its return value, can outlive their
530 ///   caller, we need to make sure that they will be valid afterwards, and since
531 ///   we *can't* know when it will return we need to have them valid as long as
532 ///   possible, that is until the end of the program, hence the `'static`
533 ///   lifetime.
534 /// - The [`Send`] constraint is because the closure will need to be passed
535 ///   *by value* from the thread where it is spawned to the new thread. Its
536 ///   return value will need to be passed from the new thread to the thread
537 ///   where it is `join`ed.
538 ///   As a reminder, the [`Send`] marker trait expresses that it is safe to be
539 ///   passed from thread to thread. [`Sync`] expresses that it is safe to have a
540 ///   reference be passed from thread to thread.
541 ///
542 /// # Panics
543 ///
544 /// Panics if the OS fails to create a thread; use [`Builder::spawn`]
545 /// to recover from such errors.
546 ///
547 /// # Examples
548 ///
549 /// Creating a thread.
550 ///
551 /// ```
552 /// use std::thread;
553 ///
554 /// let handler = thread::spawn(|| {
555 ///     // thread code
556 /// });
557 ///
558 /// handler.join().unwrap();
559 /// ```
560 ///
561 /// As mentioned in the module documentation, threads are usually made to
562 /// communicate using [`channels`], here is how it usually looks.
563 ///
564 /// This example also shows how to use `move`, in order to give ownership
565 /// of values to a thread.
566 ///
567 /// ```
568 /// use std::thread;
569 /// use std::sync::mpsc::channel;
570 ///
571 /// let (tx, rx) = channel();
572 ///
573 /// let sender = thread::spawn(move || {
574 ///     tx.send("Hello, thread".to_owned())
575 ///         .expect("Unable to send on channel");
576 /// });
577 ///
578 /// let receiver = thread::spawn(move || {
579 ///     let value = rx.recv().expect("Unable to receive from channel");
580 ///     println!("{}", value);
581 /// });
582 ///
583 /// sender.join().expect("The sender thread has panicked");
584 /// receiver.join().expect("The receiver thread has panicked");
585 /// ```
586 ///
587 /// A thread can also return a value through its [`JoinHandle`], you can use
588 /// this to make asynchronous computations (futures might be more appropriate
589 /// though).
590 ///
591 /// ```
592 /// use std::thread;
593 ///
594 /// let computation = thread::spawn(|| {
595 ///     // Some expensive computation.
596 ///     42
597 /// });
598 ///
599 /// let result = computation.join().unwrap();
600 /// println!("{}", result);
601 /// ```
602 ///
603 /// [`channels`]: ../../std/sync/mpsc/index.html
604 /// [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
605 /// [`join`]: ../../std/thread/struct.JoinHandle.html#method.join
606 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
607 /// [`panic`]: ../../std/macro.panic.html
608 /// [`Builder::spawn`]: ../../std/thread/struct.Builder.html#method.spawn
609 /// [`Builder`]: ../../std/thread/struct.Builder.html
610 /// [`Send`]: ../../std/marker/trait.Send.html
611 /// [`Sync`]: ../../std/marker/trait.Sync.html
612 #[stable(feature = "rust1", since = "1.0.0")]
613 pub fn spawn<F, T>(f: F) -> JoinHandle<T>
614 where
615     F: FnOnce() -> T,
616     F: Send + 'static,
617     T: Send + 'static,
618 {
619     Builder::new().spawn(f).expect("failed to spawn thread")
620 }
621
622 /// Gets a handle to the thread that invokes it.
623 ///
624 /// # Examples
625 ///
626 /// Getting a handle to the current thread with `thread::current()`:
627 ///
628 /// ```
629 /// use std::thread;
630 ///
631 /// let handler = thread::Builder::new()
632 ///     .name("named thread".into())
633 ///     .spawn(|| {
634 ///         let handle = thread::current();
635 ///         assert_eq!(handle.name(), Some("named thread"));
636 ///     })
637 ///     .unwrap();
638 ///
639 /// handler.join().unwrap();
640 /// ```
641 #[stable(feature = "rust1", since = "1.0.0")]
642 pub fn current() -> Thread {
643     thread_info::current_thread().expect(
644         "use of std::thread::current() is not possible \
645          after the thread's local data has been destroyed",
646     )
647 }
648
649 /// Cooperatively gives up a timeslice to the OS scheduler.
650 ///
651 /// This is used when the programmer knows that the thread will have nothing
652 /// to do for some time, and thus avoid wasting computing time.
653 ///
654 /// For example when polling on a resource, it is common to check that it is
655 /// available, and if not to yield in order to avoid busy waiting.
656 ///
657 /// Thus the pattern of `yield`ing after a failed poll is rather common when
658 /// implementing low-level shared resources or synchronization primitives.
659 ///
660 /// However programmers will usually prefer to use [`channel`]s, [`Condvar`]s,
661 /// [`Mutex`]es or [`join`] for their synchronization routines, as they avoid
662 /// thinking about thread scheduling.
663 ///
664 /// Note that [`channel`]s for example are implemented using this primitive.
665 /// Indeed when you call `send` or `recv`, which are blocking, they will yield
666 /// if the channel is not available.
667 ///
668 /// # Examples
669 ///
670 /// ```
671 /// use std::thread;
672 ///
673 /// thread::yield_now();
674 /// ```
675 ///
676 /// [`channel`]: ../../std/sync/mpsc/index.html
677 /// [`spawn`]: ../../std/thread/fn.spawn.html
678 /// [`join`]: ../../std/thread/struct.JoinHandle.html#method.join
679 /// [`Mutex`]: ../../std/sync/struct.Mutex.html
680 /// [`Condvar`]: ../../std/sync/struct.Condvar.html
681 #[stable(feature = "rust1", since = "1.0.0")]
682 pub fn yield_now() {
683     imp::Thread::yield_now()
684 }
685
686 /// Determines whether the current thread is unwinding because of panic.
687 ///
688 /// A common use of this feature is to poison shared resources when writing
689 /// unsafe code, by checking `panicking` when the `drop` is called.
690 ///
691 /// This is usually not needed when writing safe code, as [`Mutex`es][Mutex]
692 /// already poison themselves when a thread panics while holding the lock.
693 ///
694 /// This can also be used in multithreaded applications, in order to send a
695 /// message to other threads warning that a thread has panicked (e.g., for
696 /// monitoring purposes).
697 ///
698 /// # Examples
699 ///
700 /// ```should_panic
701 /// use std::thread;
702 ///
703 /// struct SomeStruct;
704 ///
705 /// impl Drop for SomeStruct {
706 ///     fn drop(&mut self) {
707 ///         if thread::panicking() {
708 ///             println!("dropped while unwinding");
709 ///         } else {
710 ///             println!("dropped while not unwinding");
711 ///         }
712 ///     }
713 /// }
714 ///
715 /// {
716 ///     print!("a: ");
717 ///     let a = SomeStruct;
718 /// }
719 ///
720 /// {
721 ///     print!("b: ");
722 ///     let b = SomeStruct;
723 ///     panic!()
724 /// }
725 /// ```
726 ///
727 /// [Mutex]: ../../std/sync/struct.Mutex.html
728 #[inline]
729 #[stable(feature = "rust1", since = "1.0.0")]
730 pub fn panicking() -> bool {
731     panicking::panicking()
732 }
733
734 /// Puts the current thread to sleep for at least the specified amount of time.
735 ///
736 /// The thread may sleep longer than the duration specified due to scheduling
737 /// specifics or platform-dependent functionality. It will never sleep less.
738 ///
739 /// This function is blocking, and should not be used in `async` functions.
740 ///
741 /// # Platform-specific behavior
742 ///
743 /// On Unix platforms, the underlying syscall may be interrupted by a
744 /// spurious wakeup or signal handler. To ensure the sleep occurs for at least
745 /// the specified duration, this function may invoke that system call multiple
746 /// times.
747 ///
748 /// # Examples
749 ///
750 /// ```no_run
751 /// use std::thread;
752 ///
753 /// // Let's sleep for 2 seconds:
754 /// thread::sleep_ms(2000);
755 /// ```
756 #[stable(feature = "rust1", since = "1.0.0")]
757 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::sleep`")]
758 pub fn sleep_ms(ms: u32) {
759     sleep(Duration::from_millis(ms as u64))
760 }
761
762 /// Puts the current thread to sleep for at least the specified amount of time.
763 ///
764 /// The thread may sleep longer than the duration specified due to scheduling
765 /// specifics or platform-dependent functionality. It will never sleep less.
766 ///
767 /// This function is blocking, and should not be used in `async` functions.
768 ///
769 /// # Platform-specific behavior
770 ///
771 /// On Unix platforms, the underlying syscall may be interrupted by a
772 /// spurious wakeup or signal handler. To ensure the sleep occurs for at least
773 /// the specified duration, this function may invoke that system call multiple
774 /// times.
775 /// Platforms which do not support nanosecond precision for sleeping will
776 /// have `dur` rounded up to the nearest granularity of time they can sleep for.
777 ///
778 /// # Examples
779 ///
780 /// ```no_run
781 /// use std::{thread, time};
782 ///
783 /// let ten_millis = time::Duration::from_millis(10);
784 /// let now = time::Instant::now();
785 ///
786 /// thread::sleep(ten_millis);
787 ///
788 /// assert!(now.elapsed() >= ten_millis);
789 /// ```
790 #[stable(feature = "thread_sleep", since = "1.4.0")]
791 pub fn sleep(dur: Duration) {
792     imp::Thread::sleep(dur)
793 }
794
795 // constants for park/unpark
796 const EMPTY: usize = 0;
797 const PARKED: usize = 1;
798 const NOTIFIED: usize = 2;
799
800 /// Blocks unless or until the current thread's token is made available.
801 ///
802 /// A call to `park` does not guarantee that the thread will remain parked
803 /// forever, and callers should be prepared for this possibility.
804 ///
805 /// # park and unpark
806 ///
807 /// Every thread is equipped with some basic low-level blocking support, via the
808 /// [`thread::park`][`park`] function and [`thread::Thread::unpark`][`unpark`]
809 /// method. [`park`] blocks the current thread, which can then be resumed from
810 /// another thread by calling the [`unpark`] method on the blocked thread's
811 /// handle.
812 ///
813 /// Conceptually, each [`Thread`] handle has an associated token, which is
814 /// initially not present:
815 ///
816 /// * The [`thread::park`][`park`] function blocks the current thread unless or
817 ///   until the token is available for its thread handle, at which point it
818 ///   atomically consumes the token. It may also return *spuriously*, without
819 ///   consuming the token. [`thread::park_timeout`] does the same, but allows
820 ///   specifying a maximum time to block the thread for.
821 ///
822 /// * The [`unpark`] method on a [`Thread`] atomically makes the token available
823 ///   if it wasn't already. Because the token is initially absent, [`unpark`]
824 ///   followed by [`park`] will result in the second call returning immediately.
825 ///
826 /// In other words, each [`Thread`] acts a bit like a spinlock that can be
827 /// locked and unlocked using `park` and `unpark`.
828 ///
829 /// Notice that being unblocked does not imply any synchronization with someone
830 /// that unparked this thread, it could also be spurious.
831 /// For example, it would be a valid, but inefficient, implementation to make both [`park`] and
832 /// [`unpark`] return immediately without doing anything.
833 ///
834 /// The API is typically used by acquiring a handle to the current thread,
835 /// placing that handle in a shared data structure so that other threads can
836 /// find it, and then `park`ing in a loop. When some desired condition is met, another
837 /// thread calls [`unpark`] on the handle.
838 ///
839 /// The motivation for this design is twofold:
840 ///
841 /// * It avoids the need to allocate mutexes and condvars when building new
842 ///   synchronization primitives; the threads already provide basic
843 ///   blocking/signaling.
844 ///
845 /// * It can be implemented very efficiently on many platforms.
846 ///
847 /// # Examples
848 ///
849 /// ```
850 /// use std::thread;
851 /// use std::sync::{Arc, atomic::{Ordering, AtomicBool}};
852 /// use std::time::Duration;
853 ///
854 /// let flag = Arc::new(AtomicBool::new(false));
855 /// let flag2 = Arc::clone(&flag);
856 ///
857 /// let parked_thread = thread::spawn(move || {
858 ///     // We want to wait until the flag is set. We *could* just spin, but using
859 ///     // park/unpark is more efficient.
860 ///     while !flag2.load(Ordering::Acquire) {
861 ///         println!("Parking thread");
862 ///         thread::park();
863 ///         // We *could* get here spuriously, i.e., way before the 10ms below are over!
864 ///         // But that is no problem, we are in a loop until the flag is set anyway.
865 ///         println!("Thread unparked");
866 ///     }
867 ///     println!("Flag received");
868 /// });
869 ///
870 /// // Let some time pass for the thread to be spawned.
871 /// thread::sleep(Duration::from_millis(10));
872 ///
873 /// // Set the flag, and let the thread wake up.
874 /// // There is no race condition here, if `unpark`
875 /// // happens first, `park` will return immediately.
876 /// // Hence there is no risk of a deadlock.
877 /// flag.store(true, Ordering::Release);
878 /// println!("Unpark the thread");
879 /// parked_thread.thread().unpark();
880 ///
881 /// parked_thread.join().unwrap();
882 /// ```
883 ///
884 /// [`Thread`]: ../../std/thread/struct.Thread.html
885 /// [`park`]: ../../std/thread/fn.park.html
886 /// [`unpark`]: ../../std/thread/struct.Thread.html#method.unpark
887 /// [`thread::park_timeout`]: ../../std/thread/fn.park_timeout.html
888 //
889 // The implementation currently uses the trivial strategy of a Mutex+Condvar
890 // with wakeup flag, which does not actually allow spurious wakeups. In the
891 // future, this will be implemented in a more efficient way, perhaps along the lines of
892 //   http://cr.openjdk.java.net/~stefank/6989984.1/raw_files/new/src/os/linux/vm/os_linux.cpp
893 // or futuxes, and in either case may allow spurious wakeups.
894 #[stable(feature = "rust1", since = "1.0.0")]
895 pub fn park() {
896     let thread = current();
897
898     // If we were previously notified then we consume this notification and
899     // return quickly.
900     if thread.inner.state.compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst).is_ok() {
901         return;
902     }
903
904     // Otherwise we need to coordinate going to sleep
905     let mut m = thread.inner.lock.lock().unwrap();
906     match thread.inner.state.compare_exchange(EMPTY, PARKED, SeqCst, SeqCst) {
907         Ok(_) => {}
908         Err(NOTIFIED) => {
909             // We must read here, even though we know it will be `NOTIFIED`.
910             // This is because `unpark` may have been called again since we read
911             // `NOTIFIED` in the `compare_exchange` above. We must perform an
912             // acquire operation that synchronizes with that `unpark` to observe
913             // any writes it made before the call to unpark. To do that we must
914             // read from the write it made to `state`.
915             let old = thread.inner.state.swap(EMPTY, SeqCst);
916             assert_eq!(old, NOTIFIED, "park state changed unexpectedly");
917             return;
918         } // should consume this notification, so prohibit spurious wakeups in next park.
919         Err(_) => panic!("inconsistent park state"),
920     }
921     loop {
922         m = thread.inner.cvar.wait(m).unwrap();
923         match thread.inner.state.compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst) {
924             Ok(_) => return, // got a notification
925             Err(_) => {}     // spurious wakeup, go back to sleep
926         }
927     }
928 }
929
930 /// Use [`park_timeout`].
931 ///
932 /// Blocks unless or until the current thread's token is made available or
933 /// the specified duration has been reached (may wake spuriously).
934 ///
935 /// The semantics of this function are equivalent to [`park`] except
936 /// that the thread will be blocked for roughly no longer than `dur`. This
937 /// method should not be used for precise timing due to anomalies such as
938 /// preemption or platform differences that may not cause the maximum
939 /// amount of time waited to be precisely `ms` long.
940 ///
941 /// See the [park documentation][`park`] for more detail.
942 ///
943 /// [`park_timeout`]: fn.park_timeout.html
944 /// [`park`]: ../../std/thread/fn.park.html
945 #[stable(feature = "rust1", since = "1.0.0")]
946 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::park_timeout`")]
947 pub fn park_timeout_ms(ms: u32) {
948     park_timeout(Duration::from_millis(ms as u64))
949 }
950
951 /// Blocks unless or until the current thread's token is made available or
952 /// the specified duration has been reached (may wake spuriously).
953 ///
954 /// The semantics of this function are equivalent to [`park`][park] except
955 /// that the thread will be blocked for roughly no longer than `dur`. This
956 /// method should not be used for precise timing due to anomalies such as
957 /// preemption or platform differences that may not cause the maximum
958 /// amount of time waited to be precisely `dur` long.
959 ///
960 /// See the [park documentation][park] for more details.
961 ///
962 /// # Platform-specific behavior
963 ///
964 /// Platforms which do not support nanosecond precision for sleeping will have
965 /// `dur` rounded up to the nearest granularity of time they can sleep for.
966 ///
967 /// # Examples
968 ///
969 /// Waiting for the complete expiration of the timeout:
970 ///
971 /// ```rust,no_run
972 /// use std::thread::park_timeout;
973 /// use std::time::{Instant, Duration};
974 ///
975 /// let timeout = Duration::from_secs(2);
976 /// let beginning_park = Instant::now();
977 ///
978 /// let mut timeout_remaining = timeout;
979 /// loop {
980 ///     park_timeout(timeout_remaining);
981 ///     let elapsed = beginning_park.elapsed();
982 ///     if elapsed >= timeout {
983 ///         break;
984 ///     }
985 ///     println!("restarting park_timeout after {:?}", elapsed);
986 ///     timeout_remaining = timeout - elapsed;
987 /// }
988 /// ```
989 ///
990 /// [park]: fn.park.html
991 #[stable(feature = "park_timeout", since = "1.4.0")]
992 pub fn park_timeout(dur: Duration) {
993     let thread = current();
994
995     // Like `park` above we have a fast path for an already-notified thread, and
996     // afterwards we start coordinating for a sleep.
997     // return quickly.
998     if thread.inner.state.compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst).is_ok() {
999         return;
1000     }
1001     let m = thread.inner.lock.lock().unwrap();
1002     match thread.inner.state.compare_exchange(EMPTY, PARKED, SeqCst, SeqCst) {
1003         Ok(_) => {}
1004         Err(NOTIFIED) => {
1005             // We must read again here, see `park`.
1006             let old = thread.inner.state.swap(EMPTY, SeqCst);
1007             assert_eq!(old, NOTIFIED, "park state changed unexpectedly");
1008             return;
1009         } // should consume this notification, so prohibit spurious wakeups in next park.
1010         Err(_) => panic!("inconsistent park_timeout state"),
1011     }
1012
1013     // Wait with a timeout, and if we spuriously wake up or otherwise wake up
1014     // from a notification we just want to unconditionally set the state back to
1015     // empty, either consuming a notification or un-flagging ourselves as
1016     // parked.
1017     let (_m, _result) = thread.inner.cvar.wait_timeout(m, dur).unwrap();
1018     match thread.inner.state.swap(EMPTY, SeqCst) {
1019         NOTIFIED => {} // got a notification, hurray!
1020         PARKED => {}   // no notification, alas
1021         n => panic!("inconsistent park_timeout state: {}", n),
1022     }
1023 }
1024
1025 ////////////////////////////////////////////////////////////////////////////////
1026 // ThreadId
1027 ////////////////////////////////////////////////////////////////////////////////
1028
1029 /// A unique identifier for a running thread.
1030 ///
1031 /// A `ThreadId` is an opaque object that has a unique value for each thread
1032 /// that creates one. `ThreadId`s are not guaranteed to correspond to a thread's
1033 /// system-designated identifier. A `ThreadId` can be retrieved from the [`id`]
1034 /// method on a [`Thread`].
1035 ///
1036 /// # Examples
1037 ///
1038 /// ```
1039 /// use std::thread;
1040 ///
1041 /// let other_thread = thread::spawn(|| {
1042 ///     thread::current().id()
1043 /// });
1044 ///
1045 /// let other_thread_id = other_thread.join().unwrap();
1046 /// assert!(thread::current().id() != other_thread_id);
1047 /// ```
1048 ///
1049 /// [`id`]: ../../std/thread/struct.Thread.html#method.id
1050 /// [`Thread`]: ../../std/thread/struct.Thread.html
1051 #[stable(feature = "thread_id", since = "1.19.0")]
1052 #[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
1053 pub struct ThreadId(NonZeroU64);
1054
1055 impl ThreadId {
1056     // Generate a new unique thread ID.
1057     fn new() -> ThreadId {
1058         // We never call `GUARD.init()`, so it is UB to attempt to
1059         // acquire this mutex reentrantly!
1060         static GUARD: mutex::Mutex = mutex::Mutex::new();
1061         static mut COUNTER: u64 = 1;
1062
1063         unsafe {
1064             let _guard = GUARD.lock();
1065
1066             // If we somehow use up all our bits, panic so that we're not
1067             // covering up subtle bugs of IDs being reused.
1068             if COUNTER == u64::MAX {
1069                 panic!("failed to generate unique thread ID: bitspace exhausted");
1070             }
1071
1072             let id = COUNTER;
1073             COUNTER += 1;
1074
1075             ThreadId(NonZeroU64::new(id).unwrap())
1076         }
1077     }
1078
1079     /// This returns a numeric identifier for the thread identified by this
1080     /// `ThreadId`.
1081     ///
1082     /// As noted in the documentation for the type itself, it is essentially an
1083     /// opaque ID, but is guaranteed to be unique for each thread. The returned
1084     /// value is entirely opaque -- only equality testing is stable. Note that
1085     /// it is not guaranteed which values new threads will return, and this may
1086     /// change across Rust versions.
1087     #[unstable(feature = "thread_id_value", issue = "67939")]
1088     pub fn as_u64(&self) -> NonZeroU64 {
1089         self.0
1090     }
1091 }
1092
1093 ////////////////////////////////////////////////////////////////////////////////
1094 // Thread
1095 ////////////////////////////////////////////////////////////////////////////////
1096
1097 /// The internal representation of a `Thread` handle
1098 struct Inner {
1099     name: Option<CString>, // Guaranteed to be UTF-8
1100     id: ThreadId,
1101
1102     // state for thread park/unpark
1103     state: AtomicUsize,
1104     lock: Mutex<()>,
1105     cvar: Condvar,
1106 }
1107
1108 #[derive(Clone)]
1109 #[stable(feature = "rust1", since = "1.0.0")]
1110 /// A handle to a thread.
1111 ///
1112 /// Threads are represented via the `Thread` type, which you can get in one of
1113 /// two ways:
1114 ///
1115 /// * By spawning a new thread, e.g., using the [`thread::spawn`][`spawn`]
1116 ///   function, and calling [`thread`][`JoinHandle::thread`] on the
1117 ///   [`JoinHandle`].
1118 /// * By requesting the current thread, using the [`thread::current`] function.
1119 ///
1120 /// The [`thread::current`] function is available even for threads not spawned
1121 /// by the APIs of this module.
1122 ///
1123 /// There is usually no need to create a `Thread` struct yourself, one
1124 /// should instead use a function like `spawn` to create new threads, see the
1125 /// docs of [`Builder`] and [`spawn`] for more details.
1126 ///
1127 /// [`Builder`]: ../../std/thread/struct.Builder.html
1128 /// [`JoinHandle::thread`]: ../../std/thread/struct.JoinHandle.html#method.thread
1129 /// [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
1130 /// [`thread::current`]: ../../std/thread/fn.current.html
1131 /// [`spawn`]: ../../std/thread/fn.spawn.html
1132
1133 pub struct Thread {
1134     inner: Arc<Inner>,
1135 }
1136
1137 impl Thread {
1138     // Used only internally to construct a thread object without spawning
1139     // Panics if the name contains nuls.
1140     pub(crate) fn new(name: Option<String>) -> Thread {
1141         let cname =
1142             name.map(|n| CString::new(n).expect("thread name may not contain interior null bytes"));
1143         Thread {
1144             inner: Arc::new(Inner {
1145                 name: cname,
1146                 id: ThreadId::new(),
1147                 state: AtomicUsize::new(EMPTY),
1148                 lock: Mutex::new(()),
1149                 cvar: Condvar::new(),
1150             }),
1151         }
1152     }
1153
1154     /// Atomically makes the handle's token available if it is not already.
1155     ///
1156     /// Every thread is equipped with some basic low-level blocking support, via
1157     /// the [`park`][park] function and the `unpark()` method. These can be
1158     /// used as a more CPU-efficient implementation of a spinlock.
1159     ///
1160     /// See the [park documentation][park] for more details.
1161     ///
1162     /// # Examples
1163     ///
1164     /// ```
1165     /// use std::thread;
1166     /// use std::time::Duration;
1167     ///
1168     /// let parked_thread = thread::Builder::new()
1169     ///     .spawn(|| {
1170     ///         println!("Parking thread");
1171     ///         thread::park();
1172     ///         println!("Thread unparked");
1173     ///     })
1174     ///     .unwrap();
1175     ///
1176     /// // Let some time pass for the thread to be spawned.
1177     /// thread::sleep(Duration::from_millis(10));
1178     ///
1179     /// println!("Unpark the thread");
1180     /// parked_thread.thread().unpark();
1181     ///
1182     /// parked_thread.join().unwrap();
1183     /// ```
1184     ///
1185     /// [park]: fn.park.html
1186     #[stable(feature = "rust1", since = "1.0.0")]
1187     pub fn unpark(&self) {
1188         // To ensure the unparked thread will observe any writes we made
1189         // before this call, we must perform a release operation that `park`
1190         // can synchronize with. To do that we must write `NOTIFIED` even if
1191         // `state` is already `NOTIFIED`. That is why this must be a swap
1192         // rather than a compare-and-swap that returns if it reads `NOTIFIED`
1193         // on failure.
1194         match self.inner.state.swap(NOTIFIED, SeqCst) {
1195             EMPTY => return,    // no one was waiting
1196             NOTIFIED => return, // already unparked
1197             PARKED => {}        // gotta go wake someone up
1198             _ => panic!("inconsistent state in unpark"),
1199         }
1200
1201         // There is a period between when the parked thread sets `state` to
1202         // `PARKED` (or last checked `state` in the case of a spurious wake
1203         // up) and when it actually waits on `cvar`. If we were to notify
1204         // during this period it would be ignored and then when the parked
1205         // thread went to sleep it would never wake up. Fortunately, it has
1206         // `lock` locked at this stage so we can acquire `lock` to wait until
1207         // it is ready to receive the notification.
1208         //
1209         // Releasing `lock` before the call to `notify_one` means that when the
1210         // parked thread wakes it doesn't get woken only to have to wait for us
1211         // to release `lock`.
1212         drop(self.inner.lock.lock().unwrap());
1213         self.inner.cvar.notify_one()
1214     }
1215
1216     /// Gets the thread's unique identifier.
1217     ///
1218     /// # Examples
1219     ///
1220     /// ```
1221     /// use std::thread;
1222     ///
1223     /// let other_thread = thread::spawn(|| {
1224     ///     thread::current().id()
1225     /// });
1226     ///
1227     /// let other_thread_id = other_thread.join().unwrap();
1228     /// assert!(thread::current().id() != other_thread_id);
1229     /// ```
1230     #[stable(feature = "thread_id", since = "1.19.0")]
1231     pub fn id(&self) -> ThreadId {
1232         self.inner.id
1233     }
1234
1235     /// Gets the thread's name.
1236     ///
1237     /// For more information about named threads, see
1238     /// [this module-level documentation][naming-threads].
1239     ///
1240     /// # Examples
1241     ///
1242     /// Threads by default have no name specified:
1243     ///
1244     /// ```
1245     /// use std::thread;
1246     ///
1247     /// let builder = thread::Builder::new();
1248     ///
1249     /// let handler = builder.spawn(|| {
1250     ///     assert!(thread::current().name().is_none());
1251     /// }).unwrap();
1252     ///
1253     /// handler.join().unwrap();
1254     /// ```
1255     ///
1256     /// Thread with a specified name:
1257     ///
1258     /// ```
1259     /// use std::thread;
1260     ///
1261     /// let builder = thread::Builder::new()
1262     ///     .name("foo".into());
1263     ///
1264     /// let handler = builder.spawn(|| {
1265     ///     assert_eq!(thread::current().name(), Some("foo"))
1266     /// }).unwrap();
1267     ///
1268     /// handler.join().unwrap();
1269     /// ```
1270     ///
1271     /// [naming-threads]: ./index.html#naming-threads
1272     #[stable(feature = "rust1", since = "1.0.0")]
1273     pub fn name(&self) -> Option<&str> {
1274         self.cname().map(|s| unsafe { str::from_utf8_unchecked(s.to_bytes()) })
1275     }
1276
1277     fn cname(&self) -> Option<&CStr> {
1278         self.inner.name.as_deref()
1279     }
1280 }
1281
1282 #[stable(feature = "rust1", since = "1.0.0")]
1283 impl fmt::Debug for Thread {
1284     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1285         f.debug_struct("Thread").field("id", &self.id()).field("name", &self.name()).finish()
1286     }
1287 }
1288
1289 ////////////////////////////////////////////////////////////////////////////////
1290 // JoinHandle
1291 ////////////////////////////////////////////////////////////////////////////////
1292
1293 /// A specialized [`Result`] type for threads.
1294 ///
1295 /// Indicates the manner in which a thread exited.
1296 ///
1297 /// The value contained in the `Result::Err` variant
1298 /// is the value the thread panicked with;
1299 /// that is, the argument the `panic!` macro was called with.
1300 /// Unlike with normal errors, this value doesn't implement
1301 /// the [`Error`](crate::error::Error) trait.
1302 ///
1303 /// Thus, a sensible way to handle a thread panic is to either:
1304 /// 1. `unwrap` the `Result<T>`, propagating the panic
1305 /// 2. or in case the thread is intended to be a subsystem boundary
1306 /// that is supposed to isolate system-level failures,
1307 /// match on the `Err` variant and handle the panic in an appropriate way.
1308 ///
1309 /// A thread that completes without panicking is considered to exit successfully.
1310 ///
1311 /// # Examples
1312 ///
1313 /// ```no_run
1314 /// use std::thread;
1315 /// use std::fs;
1316 ///
1317 /// fn copy_in_thread() -> thread::Result<()> {
1318 ///     thread::spawn(move || { fs::copy("foo.txt", "bar.txt").unwrap(); }).join()
1319 /// }
1320 ///
1321 /// fn main() {
1322 ///     match copy_in_thread() {
1323 ///         Ok(_) => println!("this is fine"),
1324 ///         Err(_) => println!("thread panicked"),
1325 ///     }
1326 /// }
1327 /// ```
1328 ///
1329 /// [`Result`]: ../../std/result/enum.Result.html
1330 #[stable(feature = "rust1", since = "1.0.0")]
1331 pub type Result<T> = crate::result::Result<T, Box<dyn Any + Send + 'static>>;
1332
1333 // This packet is used to communicate the return value between the child thread
1334 // and the parent thread. Memory is shared through the `Arc` within and there's
1335 // no need for a mutex here because synchronization happens with `join()` (the
1336 // parent thread never reads this packet until the child has exited).
1337 //
1338 // This packet itself is then stored into a `JoinInner` which in turns is placed
1339 // in `JoinHandle` and `JoinGuard`. Due to the usage of `UnsafeCell` we need to
1340 // manually worry about impls like Send and Sync. The type `T` should
1341 // already always be Send (otherwise the thread could not have been created) and
1342 // this type is inherently Sync because no methods take &self. Regardless,
1343 // however, we add inheriting impls for Send/Sync to this type to ensure it's
1344 // Send/Sync and that future modifications will still appropriately classify it.
1345 struct Packet<T>(Arc<UnsafeCell<Option<Result<T>>>>);
1346
1347 unsafe impl<T: Send> Send for Packet<T> {}
1348 unsafe impl<T: Sync> Sync for Packet<T> {}
1349
1350 /// Inner representation for JoinHandle
1351 struct JoinInner<T> {
1352     native: Option<imp::Thread>,
1353     thread: Thread,
1354     packet: Packet<T>,
1355 }
1356
1357 impl<T> JoinInner<T> {
1358     fn join(&mut self) -> Result<T> {
1359         self.native.take().unwrap().join();
1360         unsafe { (*self.packet.0.get()).take().unwrap() }
1361     }
1362 }
1363
1364 /// An owned permission to join on a thread (block on its termination).
1365 ///
1366 /// A `JoinHandle` *detaches* the associated thread when it is dropped, which
1367 /// means that there is no longer any handle to thread and no way to `join`
1368 /// on it.
1369 ///
1370 /// Due to platform restrictions, it is not possible to [`Clone`] this
1371 /// handle: the ability to join a thread is a uniquely-owned permission.
1372 ///
1373 /// This `struct` is created by the [`thread::spawn`] function and the
1374 /// [`thread::Builder::spawn`] method.
1375 ///
1376 /// # Examples
1377 ///
1378 /// Creation from [`thread::spawn`]:
1379 ///
1380 /// ```
1381 /// use std::thread;
1382 ///
1383 /// let join_handle: thread::JoinHandle<_> = thread::spawn(|| {
1384 ///     // some work here
1385 /// });
1386 /// ```
1387 ///
1388 /// Creation from [`thread::Builder::spawn`]:
1389 ///
1390 /// ```
1391 /// use std::thread;
1392 ///
1393 /// let builder = thread::Builder::new();
1394 ///
1395 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1396 ///     // some work here
1397 /// }).unwrap();
1398 /// ```
1399 ///
1400 /// Child being detached and outliving its parent:
1401 ///
1402 /// ```no_run
1403 /// use std::thread;
1404 /// use std::time::Duration;
1405 ///
1406 /// let original_thread = thread::spawn(|| {
1407 ///     let _detached_thread = thread::spawn(|| {
1408 ///         // Here we sleep to make sure that the first thread returns before.
1409 ///         thread::sleep(Duration::from_millis(10));
1410 ///         // This will be called, even though the JoinHandle is dropped.
1411 ///         println!("♫ Still alive â™«");
1412 ///     });
1413 /// });
1414 ///
1415 /// original_thread.join().expect("The thread being joined has panicked");
1416 /// println!("Original thread is joined.");
1417 ///
1418 /// // We make sure that the new thread has time to run, before the main
1419 /// // thread returns.
1420 ///
1421 /// thread::sleep(Duration::from_millis(1000));
1422 /// ```
1423 ///
1424 /// [`Clone`]: ../../std/clone/trait.Clone.html
1425 /// [`thread::spawn`]: fn.spawn.html
1426 /// [`thread::Builder::spawn`]: struct.Builder.html#method.spawn
1427 #[stable(feature = "rust1", since = "1.0.0")]
1428 pub struct JoinHandle<T>(JoinInner<T>);
1429
1430 #[stable(feature = "joinhandle_impl_send_sync", since = "1.29.0")]
1431 unsafe impl<T> Send for JoinHandle<T> {}
1432 #[stable(feature = "joinhandle_impl_send_sync", since = "1.29.0")]
1433 unsafe impl<T> Sync for JoinHandle<T> {}
1434
1435 impl<T> JoinHandle<T> {
1436     /// Extracts a handle to the underlying thread.
1437     ///
1438     /// # Examples
1439     ///
1440     /// ```
1441     /// use std::thread;
1442     ///
1443     /// let builder = thread::Builder::new();
1444     ///
1445     /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1446     ///     // some work here
1447     /// }).unwrap();
1448     ///
1449     /// let thread = join_handle.thread();
1450     /// println!("thread id: {:?}", thread.id());
1451     /// ```
1452     #[stable(feature = "rust1", since = "1.0.0")]
1453     pub fn thread(&self) -> &Thread {
1454         &self.0.thread
1455     }
1456
1457     /// Waits for the associated thread to finish.
1458     ///
1459     /// In terms of [atomic memory orderings],  the completion of the associated
1460     /// thread synchronizes with this function returning. In other words, all
1461     /// operations performed by that thread are ordered before all
1462     /// operations that happen after `join` returns.
1463     ///
1464     /// If the child thread panics, [`Err`] is returned with the parameter given
1465     /// to [`panic`].
1466     ///
1467     /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1468     /// [`panic`]: ../../std/macro.panic.html
1469     /// [atomic memory orderings]: ../../std/sync/atomic/index.html
1470     ///
1471     /// # Panics
1472     ///
1473     /// This function may panic on some platforms if a thread attempts to join
1474     /// itself or otherwise may create a deadlock with joining threads.
1475     ///
1476     /// # Examples
1477     ///
1478     /// ```
1479     /// use std::thread;
1480     ///
1481     /// let builder = thread::Builder::new();
1482     ///
1483     /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1484     ///     // some work here
1485     /// }).unwrap();
1486     /// join_handle.join().expect("Couldn't join on the associated thread");
1487     /// ```
1488     #[stable(feature = "rust1", since = "1.0.0")]
1489     pub fn join(mut self) -> Result<T> {
1490         self.0.join()
1491     }
1492 }
1493
1494 impl<T> AsInner<imp::Thread> for JoinHandle<T> {
1495     fn as_inner(&self) -> &imp::Thread {
1496         self.0.native.as_ref().unwrap()
1497     }
1498 }
1499
1500 impl<T> IntoInner<imp::Thread> for JoinHandle<T> {
1501     fn into_inner(self) -> imp::Thread {
1502         self.0.native.unwrap()
1503     }
1504 }
1505
1506 #[stable(feature = "std_debug", since = "1.16.0")]
1507 impl<T> fmt::Debug for JoinHandle<T> {
1508     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1509         f.pad("JoinHandle { .. }")
1510     }
1511 }
1512
1513 fn _assert_sync_and_send() {
1514     fn _assert_both<T: Send + Sync>() {}
1515     _assert_both::<JoinHandle<()>>();
1516     _assert_both::<Thread>();
1517 }
1518
1519 ////////////////////////////////////////////////////////////////////////////////
1520 // Tests
1521 ////////////////////////////////////////////////////////////////////////////////
1522
1523 #[cfg(all(test, not(target_os = "emscripten")))]
1524 mod tests {
1525     use super::Builder;
1526     use crate::any::Any;
1527     use crate::mem;
1528     use crate::result;
1529     use crate::sync::mpsc::{channel, Sender};
1530     use crate::thread::{self, ThreadId};
1531     use crate::time::Duration;
1532
1533     // !!! These tests are dangerous. If something is buggy, they will hang, !!!
1534     // !!! instead of exiting cleanly. This might wedge the buildbots.       !!!
1535
1536     #[test]
1537     fn test_unnamed_thread() {
1538         thread::spawn(move || {
1539             assert!(thread::current().name().is_none());
1540         })
1541         .join()
1542         .ok()
1543         .expect("thread panicked");
1544     }
1545
1546     #[test]
1547     fn test_named_thread() {
1548         Builder::new()
1549             .name("ada lovelace".to_string())
1550             .spawn(move || {
1551                 assert!(thread::current().name().unwrap() == "ada lovelace".to_string());
1552             })
1553             .unwrap()
1554             .join()
1555             .unwrap();
1556     }
1557
1558     #[test]
1559     #[should_panic]
1560     fn test_invalid_named_thread() {
1561         let _ = Builder::new().name("ada l\0velace".to_string()).spawn(|| {});
1562     }
1563
1564     #[test]
1565     fn test_run_basic() {
1566         let (tx, rx) = channel();
1567         thread::spawn(move || {
1568             tx.send(()).unwrap();
1569         });
1570         rx.recv().unwrap();
1571     }
1572
1573     #[test]
1574     fn test_join_panic() {
1575         match thread::spawn(move || panic!()).join() {
1576             result::Result::Err(_) => (),
1577             result::Result::Ok(()) => panic!(),
1578         }
1579     }
1580
1581     #[test]
1582     fn test_spawn_sched() {
1583         let (tx, rx) = channel();
1584
1585         fn f(i: i32, tx: Sender<()>) {
1586             let tx = tx.clone();
1587             thread::spawn(move || {
1588                 if i == 0 {
1589                     tx.send(()).unwrap();
1590                 } else {
1591                     f(i - 1, tx);
1592                 }
1593             });
1594         }
1595         f(10, tx);
1596         rx.recv().unwrap();
1597     }
1598
1599     #[test]
1600     fn test_spawn_sched_childs_on_default_sched() {
1601         let (tx, rx) = channel();
1602
1603         thread::spawn(move || {
1604             thread::spawn(move || {
1605                 tx.send(()).unwrap();
1606             });
1607         });
1608
1609         rx.recv().unwrap();
1610     }
1611
1612     fn avoid_copying_the_body<F>(spawnfn: F)
1613     where
1614         F: FnOnce(Box<dyn Fn() + Send>),
1615     {
1616         let (tx, rx) = channel();
1617
1618         let x: Box<_> = box 1;
1619         let x_in_parent = (&*x) as *const i32 as usize;
1620
1621         spawnfn(Box::new(move || {
1622             let x_in_child = (&*x) as *const i32 as usize;
1623             tx.send(x_in_child).unwrap();
1624         }));
1625
1626         let x_in_child = rx.recv().unwrap();
1627         assert_eq!(x_in_parent, x_in_child);
1628     }
1629
1630     #[test]
1631     fn test_avoid_copying_the_body_spawn() {
1632         avoid_copying_the_body(|v| {
1633             thread::spawn(move || v());
1634         });
1635     }
1636
1637     #[test]
1638     fn test_avoid_copying_the_body_thread_spawn() {
1639         avoid_copying_the_body(|f| {
1640             thread::spawn(move || {
1641                 f();
1642             });
1643         })
1644     }
1645
1646     #[test]
1647     fn test_avoid_copying_the_body_join() {
1648         avoid_copying_the_body(|f| {
1649             let _ = thread::spawn(move || f()).join();
1650         })
1651     }
1652
1653     #[test]
1654     fn test_child_doesnt_ref_parent() {
1655         // If the child refcounts the parent thread, this will stack overflow when
1656         // climbing the thread tree to dereference each ancestor. (See #1789)
1657         // (well, it would if the constant were 8000+ - I lowered it to be more
1658         // valgrind-friendly. try this at home, instead..!)
1659         const GENERATIONS: u32 = 16;
1660         fn child_no(x: u32) -> Box<dyn Fn() + Send> {
1661             return Box::new(move || {
1662                 if x < GENERATIONS {
1663                     thread::spawn(move || child_no(x + 1)());
1664                 }
1665             });
1666         }
1667         thread::spawn(|| child_no(0)());
1668     }
1669
1670     #[test]
1671     fn test_simple_newsched_spawn() {
1672         thread::spawn(move || {});
1673     }
1674
1675     #[test]
1676     fn test_try_panic_message_static_str() {
1677         match thread::spawn(move || {
1678             panic!("static string");
1679         })
1680         .join()
1681         {
1682             Err(e) => {
1683                 type T = &'static str;
1684                 assert!(e.is::<T>());
1685                 assert_eq!(*e.downcast::<T>().unwrap(), "static string");
1686             }
1687             Ok(()) => panic!(),
1688         }
1689     }
1690
1691     #[test]
1692     fn test_try_panic_message_owned_str() {
1693         match thread::spawn(move || {
1694             panic!("owned string".to_string());
1695         })
1696         .join()
1697         {
1698             Err(e) => {
1699                 type T = String;
1700                 assert!(e.is::<T>());
1701                 assert_eq!(*e.downcast::<T>().unwrap(), "owned string".to_string());
1702             }
1703             Ok(()) => panic!(),
1704         }
1705     }
1706
1707     #[test]
1708     fn test_try_panic_message_any() {
1709         match thread::spawn(move || {
1710             panic!(box 413u16 as Box<dyn Any + Send>);
1711         })
1712         .join()
1713         {
1714             Err(e) => {
1715                 type T = Box<dyn Any + Send>;
1716                 assert!(e.is::<T>());
1717                 let any = e.downcast::<T>().unwrap();
1718                 assert!(any.is::<u16>());
1719                 assert_eq!(*any.downcast::<u16>().unwrap(), 413);
1720             }
1721             Ok(()) => panic!(),
1722         }
1723     }
1724
1725     #[test]
1726     fn test_try_panic_message_unit_struct() {
1727         struct Juju;
1728
1729         match thread::spawn(move || panic!(Juju)).join() {
1730             Err(ref e) if e.is::<Juju>() => {}
1731             Err(_) | Ok(()) => panic!(),
1732         }
1733     }
1734
1735     #[test]
1736     fn test_park_timeout_unpark_before() {
1737         for _ in 0..10 {
1738             thread::current().unpark();
1739             thread::park_timeout(Duration::from_millis(u32::MAX as u64));
1740         }
1741     }
1742
1743     #[test]
1744     fn test_park_timeout_unpark_not_called() {
1745         for _ in 0..10 {
1746             thread::park_timeout(Duration::from_millis(10));
1747         }
1748     }
1749
1750     #[test]
1751     fn test_park_timeout_unpark_called_other_thread() {
1752         for _ in 0..10 {
1753             let th = thread::current();
1754
1755             let _guard = thread::spawn(move || {
1756                 super::sleep(Duration::from_millis(50));
1757                 th.unpark();
1758             });
1759
1760             thread::park_timeout(Duration::from_millis(u32::MAX as u64));
1761         }
1762     }
1763
1764     #[test]
1765     fn sleep_ms_smoke() {
1766         thread::sleep(Duration::from_millis(2));
1767     }
1768
1769     #[test]
1770     fn test_size_of_option_thread_id() {
1771         assert_eq!(mem::size_of::<Option<ThreadId>>(), mem::size_of::<ThreadId>());
1772     }
1773
1774     #[test]
1775     fn test_thread_id_equal() {
1776         assert!(thread::current().id() == thread::current().id());
1777     }
1778
1779     #[test]
1780     fn test_thread_id_not_equal() {
1781         let spawned_id = thread::spawn(|| thread::current().id()).join().unwrap();
1782         assert!(thread::current().id() != spawned_id);
1783     }
1784
1785     // NOTE: the corresponding test for stderr is in ui/thread-stderr, due
1786     // to the test harness apparently interfering with stderr configuration.
1787 }