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