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