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