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