3 //! ## The threading model
5 //! An executing Rust program consists of a collection of native OS threads,
6 //! each with their own stack and local state. Threads can be named, and
7 //! provide some built-in support for low-level synchronization.
9 //! Communication between threads can be done through
10 //! [channels], Rust's message-passing types, along with [other forms of thread
11 //! synchronization](../../std/sync/index.html) and shared-memory data
12 //! structures. In particular, types that are guaranteed to be
13 //! threadsafe are easily shared between threads using the
14 //! atomically-reference-counted container, [`Arc`].
16 //! Fatal logic errors in Rust cause *thread panic*, during which
17 //! a thread will unwind the stack, running destructors and freeing
18 //! owned resources. While not meant as a 'try/catch' mechanism, panics
19 //! in Rust can nonetheless be caught (unless compiling with `panic=abort`) with
20 //! [`catch_unwind`](../../std/panic/fn.catch_unwind.html) and recovered
21 //! from, or alternatively be resumed with
22 //! [`resume_unwind`](../../std/panic/fn.resume_unwind.html). If the panic
23 //! is not caught the thread will exit, but the panic may optionally be
24 //! detected from a different thread with [`join`]. If the main thread panics
25 //! without the panic being caught, the application will exit with a
26 //! non-zero exit code.
28 //! When the main thread of a Rust program terminates, the entire program shuts
29 //! down, even if other threads are still running. However, this module provides
30 //! convenient facilities for automatically waiting for the termination of a
31 //! child thread (i.e., join).
33 //! ## Spawning a thread
35 //! A new thread can be spawned using the [`thread::spawn`][`spawn`] function:
40 //! thread::spawn(move || {
45 //! In this example, the spawned thread is "detached" from the current
46 //! thread. This means that it can outlive its parent (the thread that spawned
47 //! it), unless this parent is the main thread.
49 //! The parent thread can also wait on the completion of the child
50 //! thread; a call to [`spawn`] produces a [`JoinHandle`], which provides
51 //! a `join` method for waiting:
56 //! let child = thread::spawn(move || {
60 //! let res = child.join();
63 //! The [`join`] method returns a [`thread::Result`] containing [`Ok`] of the final
64 //! value produced by the child thread, or [`Err`] of the value given to
65 //! a call to [`panic!`] if the child panicked.
67 //! ## Configuring threads
69 //! A new thread can be configured before it is spawned via the [`Builder`] type,
70 //! which currently allows you to set the name and stack size for the child thread:
73 //! # #![allow(unused_must_use)]
76 //! thread::Builder::new().name("child1".to_string()).spawn(move || {
77 //! println!("Hello, world!");
81 //! ## The `Thread` type
83 //! Threads are represented via the [`Thread`] type, which you can get in one of
86 //! * By spawning a new thread, e.g., using the [`thread::spawn`][`spawn`]
87 //! function, and calling [`thread`][`JoinHandle::thread`] on the [`JoinHandle`].
88 //! * By requesting the current thread, using the [`thread::current`] function.
90 //! The [`thread::current`] function is available even for threads not spawned
91 //! by the APIs of this module.
93 //! ## Thread-local storage
95 //! This module also provides an implementation of thread-local storage for Rust
96 //! programs. Thread-local storage is a method of storing data into a global
97 //! variable that each thread in the program will have its own copy of.
98 //! Threads do not share this data, so accesses do not need to be synchronized.
100 //! A thread-local key owns the value it contains and will destroy the value when the
101 //! thread exits. It is created with the [`thread_local!`] macro and can contain any
102 //! value that is `'static` (no borrowed pointers). It provides an accessor function,
103 //! [`with`], that yields a shared reference to the value to the specified
104 //! closure. Thread-local keys allow only shared access to values, as there would be no
105 //! way to guarantee uniqueness if mutable borrows were allowed. Most values
106 //! will want to make use of some form of **interior mutability** through the
107 //! [`Cell`] or [`RefCell`] types.
109 //! ## Naming threads
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:
116 //! * If a panic occurs in a named thread, the thread name will be printed in the panic message.
117 //! * The thread name is provided to the OS where applicable (e.g., `pthread_setname_np` in
118 //! unix-like platforms).
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
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.
130 //! Note that the stack size of the main thread is *not* determined by Rust.
132 //! [channels]: ../../std/sync/mpsc/index.html
133 //! [`Arc`]: ../../std/sync/struct.Arc.html
134 //! [`spawn`]: ../../std/thread/fn.spawn.html
135 //! [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
136 //! [`JoinHandle::thread`]: ../../std/thread/struct.JoinHandle.html#method.thread
137 //! [`join`]: ../../std/thread/struct.JoinHandle.html#method.join
138 //! [`Result`]: ../../std/result/enum.Result.html
139 //! [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
140 //! [`Err`]: ../../std/result/enum.Result.html#variant.Err
141 //! [`panic!`]: ../../std/macro.panic.html
142 //! [`Builder`]: ../../std/thread/struct.Builder.html
143 //! [`Builder::stack_size`]: ../../std/thread/struct.Builder.html#method.stack_size
144 //! [`Builder::name`]: ../../std/thread/struct.Builder.html#method.name
145 //! [`thread::current`]: ../../std/thread/fn.current.html
146 //! [`thread::Result`]: ../../std/thread/type.Result.html
147 //! [`Thread`]: ../../std/thread/struct.Thread.html
148 //! [`park`]: ../../std/thread/fn.park.html
149 //! [`unpark`]: ../../std/thread/struct.Thread.html#method.unpark
150 //! [`Thread::name`]: ../../std/thread/struct.Thread.html#method.name
151 //! [`thread::park_timeout`]: ../../std/thread/fn.park_timeout.html
152 //! [`Cell`]: ../cell/struct.Cell.html
153 //! [`RefCell`]: ../cell/struct.RefCell.html
154 //! [`thread_local!`]: ../macro.thread_local.html
155 //! [`with`]: struct.LocalKey.html#method.with
157 #![stable(feature = "rust1", since = "1.0.0")]
160 use crate::cell::UnsafeCell;
161 use crate::ffi::{CStr, CString};
165 use crate::num::NonZeroU64;
167 use crate::panicking;
169 use crate::sync::atomic::AtomicUsize;
170 use crate::sync::atomic::Ordering::SeqCst;
171 use crate::sync::{Arc, Condvar, Mutex};
172 use crate::sys::thread as imp;
173 use crate::sys_common::mutex;
174 use crate::sys_common::thread;
175 use crate::sys_common::thread_info;
176 use crate::sys_common::{AsInner, IntoInner};
177 use crate::time::Duration;
179 ////////////////////////////////////////////////////////////////////////////////
180 // Thread-local storage
181 ////////////////////////////////////////////////////////////////////////////////
186 #[stable(feature = "rust1", since = "1.0.0")]
187 pub use self::local::{AccessError, LocalKey};
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.
198 #[unstable(feature = "libstd_thread_internals", issue = "none")]
199 #[cfg(target_thread_local)]
201 pub use self::local::fast::Key as __FastLocalKeyInner;
202 #[unstable(feature = "libstd_thread_internals", issue = "none")]
204 pub use self::local::os::Key as __OsLocalKeyInner;
205 #[unstable(feature = "libstd_thread_internals", issue = "none")]
206 #[cfg(all(target_arch = "wasm32", not(target_feature = "atomics")))]
208 pub use self::local::statik::Key as __StaticLocalKeyInner;
210 ////////////////////////////////////////////////////////////////////////////////
212 ////////////////////////////////////////////////////////////////////////////////
214 /// Thread factory, which can be used in order to configure the properties of
217 /// Methods can be chained on it in order to configure it.
219 /// The two configurations available are:
221 /// - [`name`]: specifies an [associated name for the thread][naming-threads]
222 /// - [`stack_size`]: specifies the [desired stack size for the thread][stack-size]
224 /// The [`spawn`] method will take ownership of the builder and create an
225 /// [`io::Result`] to the thread handle with the given configuration.
227 /// The [`thread::spawn`] free function uses a `Builder` with default
228 /// configuration and [`unwrap`]s its return value.
230 /// You may want to use [`spawn`] instead of [`thread::spawn`], when you want
231 /// to recover from a failure to launch a thread, indeed the free function will
232 /// panic where the `Builder` method will return a [`io::Result`].
239 /// let builder = thread::Builder::new();
241 /// let handler = builder.spawn(|| {
245 /// handler.join().unwrap();
248 /// [`thread::spawn`]: ../../std/thread/fn.spawn.html
249 /// [`stack_size`]: ../../std/thread/struct.Builder.html#method.stack_size
250 /// [`name`]: ../../std/thread/struct.Builder.html#method.name
251 /// [`spawn`]: ../../std/thread/struct.Builder.html#method.spawn
252 /// [`io::Result`]: ../../std/io/type.Result.html
253 /// [`unwrap`]: ../../std/result/enum.Result.html#method.unwrap
254 /// [naming-threads]: ./index.html#naming-threads
255 /// [stack-size]: ./index.html#stack-size
256 #[stable(feature = "rust1", since = "1.0.0")]
259 // A name for the thread-to-be, for identification in panic messages
260 name: Option<String>,
261 // The size of the stack for the spawned thread in bytes
262 stack_size: Option<usize>,
266 /// Generates the base configuration for spawning a thread, from which
267 /// configuration methods can be chained.
274 /// let builder = thread::Builder::new()
275 /// .name("foo".into())
276 /// .stack_size(32 * 1024);
278 /// let handler = builder.spawn(|| {
282 /// handler.join().unwrap();
284 #[stable(feature = "rust1", since = "1.0.0")]
285 pub fn new() -> Builder {
286 Builder { name: None, stack_size: None }
289 /// Names the thread-to-be. Currently the name is used for identification
290 /// only in panic messages.
292 /// The name must not contain null bytes (`\0`).
294 /// For more information about named threads, see
295 /// [this module-level documentation][naming-threads].
302 /// let builder = thread::Builder::new()
303 /// .name("foo".into());
305 /// let handler = builder.spawn(|| {
306 /// assert_eq!(thread::current().name(), Some("foo"))
309 /// handler.join().unwrap();
312 /// [naming-threads]: ./index.html#naming-threads
313 #[stable(feature = "rust1", since = "1.0.0")]
314 pub fn name(mut self, name: String) -> Builder {
315 self.name = Some(name);
319 /// Sets the size of the stack (in bytes) for the new thread.
321 /// The actual stack size may be greater than this value if
322 /// the platform specifies a minimal stack size.
324 /// For more information about the stack size for threads, see
325 /// [this module-level documentation][stack-size].
332 /// let builder = thread::Builder::new().stack_size(32 * 1024);
335 /// [stack-size]: ./index.html#stack-size
336 #[stable(feature = "rust1", since = "1.0.0")]
337 pub fn stack_size(mut self, size: usize) -> Builder {
338 self.stack_size = Some(size);
342 /// Spawns a new thread by taking ownership of the `Builder`, and returns an
343 /// [`io::Result`] to its [`JoinHandle`].
345 /// The spawned thread may outlive the caller (unless the caller thread
346 /// is the main thread; the whole process is terminated when the main
347 /// thread finishes). The join handle can be used to block on
348 /// termination of the child thread, including recovering its panics.
350 /// For a more complete documentation see [`thread::spawn`][`spawn`].
354 /// Unlike the [`spawn`] free function, this method yields an
355 /// [`io::Result`] to capture any failure to create the thread at
358 /// [`spawn`]: ../../std/thread/fn.spawn.html
359 /// [`io::Result`]: ../../std/io/type.Result.html
360 /// [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
364 /// Panics if a thread name was set and it contained null bytes.
371 /// let builder = thread::Builder::new();
373 /// let handler = builder.spawn(|| {
377 /// handler.join().unwrap();
379 #[stable(feature = "rust1", since = "1.0.0")]
380 pub fn spawn<F, T>(self, f: F) -> io::Result<JoinHandle<T>>
386 unsafe { self.spawn_unchecked(f) }
389 /// Spawns a new thread without any lifetime restrictions by taking ownership
390 /// of the `Builder`, and returns an [`io::Result`] to its [`JoinHandle`].
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.
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`].
403 /// Unlike the [`spawn`] free function, this method yields an
404 /// [`io::Result`] to capture any failure to create the thread at
409 /// Panics if a thread name was set and it contained null bytes.
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:
417 /// - ensure that [`join`][`JoinHandle::join`] is called before any referenced
419 /// - use only types with `'static` lifetime bounds, i.e., those with no or only
420 /// `'static` references (both [`thread::Builder::spawn`][`Builder::spawn`]
421 /// and [`thread::spawn`][`spawn`] enforce this property statically)
426 /// #![feature(thread_spawn_unchecked)]
429 /// let builder = thread::Builder::new();
432 /// let thread_x = &x;
434 /// let handler = unsafe {
435 /// builder.spawn_unchecked(move || {
436 /// println!("x = {}", *thread_x);
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();
446 /// [`spawn`]: ../../std/thread/fn.spawn.html
447 /// [`Builder::spawn`]: ../../std/thread/struct.Builder.html#method.spawn
448 /// [`io::Result`]: ../../std/io/type.Result.html
449 /// [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
450 /// [`JoinHandle::join`]: ../../std/thread/struct.JoinHandle.html#method.join
451 #[unstable(feature = "thread_spawn_unchecked", issue = "55132")]
452 pub unsafe fn spawn_unchecked<'a, F, T>(self, f: F) -> io::Result<JoinHandle<T>>
458 let Builder { name, stack_size } = self;
460 let stack_size = stack_size.unwrap_or_else(thread::min_stack);
462 let my_thread = Thread::new(name);
463 let their_thread = my_thread.clone();
465 let my_packet: Arc<UnsafeCell<Option<Result<T>>>> = Arc::new(UnsafeCell::new(None));
466 let their_packet = my_packet.clone();
469 if let Some(name) = their_thread.cname() {
470 imp::Thread::set_name(name);
473 thread_info::set(imp::guard::current(), their_thread);
474 let try_result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
475 crate::sys_common::backtrace::__rust_begin_short_backtrace(f)
477 *their_packet.get() = Some(try_result);
480 Ok(JoinHandle(JoinInner {
481 // `imp::Thread::new` takes a closure with a `'static` lifetime, since it's passed
482 // through FFI or otherwise used with low-level threading primitives that have no
483 // notion of or way to enforce lifetimes.
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.
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`
492 native: Some(imp::Thread::new(
494 mem::transmute::<Box<dyn FnOnce() + 'a>, Box<dyn FnOnce() + 'static>>(Box::new(
499 packet: Packet(my_packet),
504 ////////////////////////////////////////////////////////////////////////////////
506 ////////////////////////////////////////////////////////////////////////////////
508 /// Spawns a new thread, returning a [`JoinHandle`] for it.
510 /// The join handle will implicitly *detach* the child thread upon being
511 /// dropped. In this case, the child thread may outlive the parent (unless
512 /// the parent thread is the main thread; the whole process is terminated when
513 /// the main thread finishes). Additionally, the join handle provides a [`join`]
514 /// method that can be used to join the child thread. If the child thread
515 /// panics, [`join`] will return an [`Err`] containing the argument given to
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
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:
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
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`
534 /// - The [`Send`] constraint is because the closure will need to be passed
535 /// *by value* from the thread where it is spawned to the new thread. Its
536 /// return value will need to be passed from the new thread to the thread
537 /// where it is `join`ed.
538 /// As a reminder, the [`Send`] marker trait expresses that it is safe to be
539 /// passed from thread to thread. [`Sync`] expresses that it is safe to have a
540 /// reference be passed from thread to thread.
544 /// Panics if the OS fails to create a thread; use [`Builder::spawn`]
545 /// to recover from such errors.
549 /// Creating a thread.
554 /// let handler = thread::spawn(|| {
558 /// handler.join().unwrap();
561 /// As mentioned in the module documentation, threads are usually made to
562 /// communicate using [`channels`], here is how it usually looks.
564 /// This example also shows how to use `move`, in order to give ownership
565 /// of values to a thread.
569 /// use std::sync::mpsc::channel;
571 /// let (tx, rx) = channel();
573 /// let sender = thread::spawn(move || {
574 /// tx.send("Hello, thread".to_owned())
575 /// .expect("Unable to send on channel");
578 /// let receiver = thread::spawn(move || {
579 /// let value = rx.recv().expect("Unable to receive from channel");
580 /// println!("{}", value);
583 /// sender.join().expect("The sender thread has panicked");
584 /// receiver.join().expect("The receiver thread has panicked");
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
594 /// let computation = thread::spawn(|| {
595 /// // Some expensive computation.
599 /// let result = computation.join().unwrap();
600 /// println!("{}", result);
603 /// [`channels`]: ../../std/sync/mpsc/index.html
604 /// [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
605 /// [`join`]: ../../std/thread/struct.JoinHandle.html#method.join
606 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
607 /// [`panic`]: ../../std/macro.panic.html
608 /// [`Builder::spawn`]: ../../std/thread/struct.Builder.html#method.spawn
609 /// [`Builder`]: ../../std/thread/struct.Builder.html
610 /// [`Send`]: ../../std/marker/trait.Send.html
611 /// [`Sync`]: ../../std/marker/trait.Sync.html
612 #[stable(feature = "rust1", since = "1.0.0")]
613 pub fn spawn<F, T>(f: F) -> JoinHandle<T>
619 Builder::new().spawn(f).expect("failed to spawn thread")
622 /// Gets a handle to the thread that invokes it.
626 /// Getting a handle to the current thread with `thread::current()`:
631 /// let handler = thread::Builder::new()
632 /// .name("named thread".into())
634 /// let handle = thread::current();
635 /// assert_eq!(handle.name(), Some("named thread"));
639 /// handler.join().unwrap();
641 #[stable(feature = "rust1", since = "1.0.0")]
642 pub fn current() -> Thread {
643 thread_info::current_thread().expect(
644 "use of std::thread::current() is not \
645 possible after the thread's local \
646 data has been destroyed",
650 /// Cooperatively gives up a timeslice to the OS scheduler.
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.
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.
658 /// Thus the pattern of `yield`ing after a failed poll is rather common when
659 /// implementing low-level shared resources or synchronization primitives.
661 /// However programmers will usually prefer to use [`channel`]s, [`Condvar`]s,
662 /// [`Mutex`]es or [`join`] for their synchronization routines, as they avoid
663 /// thinking about thread scheduling.
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.
674 /// thread::yield_now();
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
682 #[stable(feature = "rust1", since = "1.0.0")]
684 imp::Thread::yield_now()
687 /// Determines whether the current thread is unwinding because of panic.
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.
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.
695 /// This can also be used in multithreaded applications, in order to send a
696 /// message to other threads warning that a thread has panicked (e.g., for
697 /// monitoring purposes).
704 /// struct SomeStruct;
706 /// impl Drop for SomeStruct {
707 /// fn drop(&mut self) {
708 /// if thread::panicking() {
709 /// println!("dropped while unwinding");
711 /// println!("dropped while not unwinding");
718 /// let a = SomeStruct;
723 /// let b = SomeStruct;
728 /// [Mutex]: ../../std/sync/struct.Mutex.html
730 #[stable(feature = "rust1", since = "1.0.0")]
731 pub fn panicking() -> bool {
732 panicking::panicking()
735 /// Puts the current thread to sleep for at least the specified amount of time.
737 /// The thread may sleep longer than the duration specified due to scheduling
738 /// specifics or platform-dependent functionality. It will never sleep less.
740 /// # Platform-specific behavior
742 /// On Unix platforms, the underlying syscall may be interrupted by a
743 /// spurious wakeup or signal handler. To ensure the sleep occurs for at least
744 /// the specified duration, this function may invoke that system call multiple
752 /// // Let's sleep for 2 seconds:
753 /// thread::sleep_ms(2000);
755 #[stable(feature = "rust1", since = "1.0.0")]
756 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::sleep`")]
757 pub fn sleep_ms(ms: u32) {
758 sleep(Duration::from_millis(ms as u64))
761 /// Puts the current thread to sleep for at least the specified amount of time.
763 /// The thread may sleep longer than the duration specified due to scheduling
764 /// specifics or platform-dependent functionality. It will never sleep less.
766 /// # Platform-specific behavior
768 /// On Unix platforms, the underlying syscall may be interrupted by a
769 /// spurious wakeup or signal handler. To ensure the sleep occurs for at least
770 /// the specified duration, this function may invoke that system call multiple
772 /// Platforms which do not support nanosecond precision for sleeping will
773 /// have `dur` rounded up to the nearest granularity of time they can sleep for.
778 /// use std::{thread, time};
780 /// let ten_millis = time::Duration::from_millis(10);
781 /// let now = time::Instant::now();
783 /// thread::sleep(ten_millis);
785 /// assert!(now.elapsed() >= ten_millis);
787 #[stable(feature = "thread_sleep", since = "1.4.0")]
788 pub fn sleep(dur: Duration) {
789 imp::Thread::sleep(dur)
792 // constants for park/unpark
793 const EMPTY: usize = 0;
794 const PARKED: usize = 1;
795 const NOTIFIED: usize = 2;
797 /// Blocks unless or until the current thread's token is made available.
799 /// A call to `park` does not guarantee that the thread will remain parked
800 /// forever, and callers should be prepared for this possibility.
802 /// # park and unpark
804 /// Every thread is equipped with some basic low-level blocking support, via the
805 /// [`thread::park`][`park`] function and [`thread::Thread::unpark`][`unpark`]
806 /// method. [`park`] blocks the current thread, which can then be resumed from
807 /// another thread by calling the [`unpark`] method on the blocked thread's
810 /// Conceptually, each [`Thread`] handle has an associated token, which is
811 /// initially not present:
813 /// * The [`thread::park`][`park`] function blocks the current thread unless or
814 /// until the token is available for its thread handle, at which point it
815 /// atomically consumes the token. It may also return *spuriously*, without
816 /// consuming the token. [`thread::park_timeout`] does the same, but allows
817 /// specifying a maximum time to block the thread for.
819 /// * The [`unpark`] method on a [`Thread`] atomically makes the token available
820 /// if it wasn't already. Because the token is initially absent, [`unpark`]
821 /// followed by [`park`] will result in the second call returning immediately.
823 /// In other words, each [`Thread`] acts a bit like a spinlock that can be
824 /// locked and unlocked using `park` and `unpark`.
826 /// Notice that being unblocked does not imply any synchronization with someone
827 /// that unparked this thread, it could also be spurious.
828 /// For example, it would be a valid, but inefficient, implementation to make both [`park`] and
829 /// [`unpark`] return immediately without doing anything.
831 /// The API is typically used by acquiring a handle to the current thread,
832 /// placing that handle in a shared data structure so that other threads can
833 /// find it, and then `park`ing in a loop. When some desired condition is met, another
834 /// thread calls [`unpark`] on the handle.
836 /// The motivation for this design is twofold:
838 /// * It avoids the need to allocate mutexes and condvars when building new
839 /// synchronization primitives; the threads already provide basic
840 /// blocking/signaling.
842 /// * It can be implemented very efficiently on many platforms.
848 /// use std::sync::{Arc, atomic::{Ordering, AtomicBool}};
849 /// use std::time::Duration;
851 /// let flag = Arc::new(AtomicBool::new(false));
852 /// let flag2 = Arc::clone(&flag);
854 /// let parked_thread = thread::spawn(move || {
855 /// // We want to wait until the flag is set. We *could* just spin, but using
856 /// // park/unpark is more efficient.
857 /// while !flag2.load(Ordering::Acquire) {
858 /// println!("Parking thread");
860 /// // We *could* get here spuriously, i.e., way before the 10ms below are over!
861 /// // But that is no problem, we are in a loop until the flag is set anyway.
862 /// println!("Thread unparked");
864 /// println!("Flag received");
867 /// // Let some time pass for the thread to be spawned.
868 /// thread::sleep(Duration::from_millis(10));
870 /// // Set the flag, and let the thread wake up.
871 /// // There is no race condition here, if `unpark`
872 /// // happens first, `park` will return immediately.
873 /// // Hence there is no risk of a deadlock.
874 /// flag.store(true, Ordering::Release);
875 /// println!("Unpark the thread");
876 /// parked_thread.thread().unpark();
878 /// parked_thread.join().unwrap();
881 /// [`Thread`]: ../../std/thread/struct.Thread.html
882 /// [`park`]: ../../std/thread/fn.park.html
883 /// [`unpark`]: ../../std/thread/struct.Thread.html#method.unpark
884 /// [`thread::park_timeout`]: ../../std/thread/fn.park_timeout.html
886 // The implementation currently uses the trivial strategy of a Mutex+Condvar
887 // with wakeup flag, which does not actually allow spurious wakeups. In the
888 // future, this will be implemented in a more efficient way, perhaps along the lines of
889 // http://cr.openjdk.java.net/~stefank/6989984.1/raw_files/new/src/os/linux/vm/os_linux.cpp
890 // or futuxes, and in either case may allow spurious wakeups.
891 #[stable(feature = "rust1", since = "1.0.0")]
893 let thread = current();
895 // If we were previously notified then we consume this notification and
897 if thread.inner.state.compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst).is_ok() {
901 // Otherwise we need to coordinate going to sleep
902 let mut m = thread.inner.lock.lock().unwrap();
903 match thread.inner.state.compare_exchange(EMPTY, PARKED, SeqCst, SeqCst) {
906 // We must read here, even though we know it will be `NOTIFIED`.
907 // This is because `unpark` may have been called again since we read
908 // `NOTIFIED` in the `compare_exchange` above. We must perform an
909 // acquire operation that synchronizes with that `unpark` to observe
910 // any writes it made before the call to unpark. To do that we must
911 // read from the write it made to `state`.
912 let old = thread.inner.state.swap(EMPTY, SeqCst);
913 assert_eq!(old, NOTIFIED, "park state changed unexpectedly");
915 } // should consume this notification, so prohibit spurious wakeups in next park.
916 Err(_) => panic!("inconsistent park state"),
919 m = thread.inner.cvar.wait(m).unwrap();
920 match thread.inner.state.compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst) {
921 Ok(_) => return, // got a notification
922 Err(_) => {} // spurious wakeup, go back to sleep
927 /// Use [`park_timeout`].
929 /// Blocks unless or until the current thread's token is made available or
930 /// the specified duration has been reached (may wake spuriously).
932 /// The semantics of this function are equivalent to [`park`] except
933 /// that the thread will be blocked for roughly no longer than `dur`. This
934 /// method should not be used for precise timing due to anomalies such as
935 /// preemption or platform differences that may not cause the maximum
936 /// amount of time waited to be precisely `ms` long.
938 /// See the [park documentation][`park`] for more detail.
940 /// [`park_timeout`]: fn.park_timeout.html
941 /// [`park`]: ../../std/thread/fn.park.html
942 #[stable(feature = "rust1", since = "1.0.0")]
943 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::park_timeout`")]
944 pub fn park_timeout_ms(ms: u32) {
945 park_timeout(Duration::from_millis(ms as u64))
948 /// Blocks unless or until the current thread's token is made available or
949 /// the specified duration has been reached (may wake spuriously).
951 /// The semantics of this function are equivalent to [`park`][park] except
952 /// that the thread will be blocked for roughly no longer than `dur`. This
953 /// method should not be used for precise timing due to anomalies such as
954 /// preemption or platform differences that may not cause the maximum
955 /// amount of time waited to be precisely `dur` long.
957 /// See the [park documentation][park] for more details.
959 /// # Platform-specific behavior
961 /// Platforms which do not support nanosecond precision for sleeping will have
962 /// `dur` rounded up to the nearest granularity of time they can sleep for.
966 /// Waiting for the complete expiration of the timeout:
969 /// use std::thread::park_timeout;
970 /// use std::time::{Instant, Duration};
972 /// let timeout = Duration::from_secs(2);
973 /// let beginning_park = Instant::now();
975 /// let mut timeout_remaining = timeout;
977 /// park_timeout(timeout_remaining);
978 /// let elapsed = beginning_park.elapsed();
979 /// if elapsed >= timeout {
982 /// println!("restarting park_timeout after {:?}", elapsed);
983 /// timeout_remaining = timeout - elapsed;
987 /// [park]: fn.park.html
988 #[stable(feature = "park_timeout", since = "1.4.0")]
989 pub fn park_timeout(dur: Duration) {
990 let thread = current();
992 // Like `park` above we have a fast path for an already-notified thread, and
993 // afterwards we start coordinating for a sleep.
995 if thread.inner.state.compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst).is_ok() {
998 let m = thread.inner.lock.lock().unwrap();
999 match thread.inner.state.compare_exchange(EMPTY, PARKED, SeqCst, SeqCst) {
1002 // We must read again here, see `park`.
1003 let old = thread.inner.state.swap(EMPTY, SeqCst);
1004 assert_eq!(old, NOTIFIED, "park state changed unexpectedly");
1006 } // should consume this notification, so prohibit spurious wakeups in next park.
1007 Err(_) => panic!("inconsistent park_timeout state"),
1010 // Wait with a timeout, and if we spuriously wake up or otherwise wake up
1011 // from a notification we just want to unconditionally set the state back to
1012 // empty, either consuming a notification or un-flagging ourselves as
1014 let (_m, _result) = thread.inner.cvar.wait_timeout(m, dur).unwrap();
1015 match thread.inner.state.swap(EMPTY, SeqCst) {
1016 NOTIFIED => {} // got a notification, hurray!
1017 PARKED => {} // no notification, alas
1018 n => panic!("inconsistent park_timeout state: {}", n),
1022 ////////////////////////////////////////////////////////////////////////////////
1024 ////////////////////////////////////////////////////////////////////////////////
1026 /// A unique identifier for a running thread.
1028 /// A `ThreadId` is an opaque object that has a unique value for each thread
1029 /// that creates one. `ThreadId`s are not guaranteed to correspond to a thread's
1030 /// system-designated identifier. A `ThreadId` can be retrieved from the [`id`]
1031 /// method on a [`Thread`].
1036 /// use std::thread;
1038 /// let other_thread = thread::spawn(|| {
1039 /// thread::current().id()
1042 /// let other_thread_id = other_thread.join().unwrap();
1043 /// assert!(thread::current().id() != other_thread_id);
1046 /// [`id`]: ../../std/thread/struct.Thread.html#method.id
1047 /// [`Thread`]: ../../std/thread/struct.Thread.html
1048 #[stable(feature = "thread_id", since = "1.19.0")]
1049 #[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
1050 pub struct ThreadId(NonZeroU64);
1053 // Generate a new unique thread ID.
1054 fn new() -> ThreadId {
1055 // We never call `GUARD.init()`, so it is UB to attempt to
1056 // acquire this mutex reentrantly!
1057 static GUARD: mutex::Mutex = mutex::Mutex::new();
1058 static mut COUNTER: u64 = 1;
1061 let _guard = GUARD.lock();
1063 // If we somehow use up all our bits, panic so that we're not
1064 // covering up subtle bugs of IDs being reused.
1065 if COUNTER == crate::u64::MAX {
1066 panic!("failed to generate unique thread ID: bitspace exhausted");
1072 ThreadId(NonZeroU64::new(id).unwrap())
1077 ////////////////////////////////////////////////////////////////////////////////
1079 ////////////////////////////////////////////////////////////////////////////////
1081 /// The internal representation of a `Thread` handle
1083 name: Option<CString>, // Guaranteed to be UTF-8
1086 // state for thread park/unpark
1093 #[stable(feature = "rust1", since = "1.0.0")]
1094 /// A handle to a thread.
1096 /// Threads are represented via the `Thread` type, which you can get in one of
1099 /// * By spawning a new thread, e.g., using the [`thread::spawn`][`spawn`]
1100 /// function, and calling [`thread`][`JoinHandle::thread`] on the
1102 /// * By requesting the current thread, using the [`thread::current`] function.
1104 /// The [`thread::current`] function is available even for threads not spawned
1105 /// by the APIs of this module.
1107 /// There is usually no need to create a `Thread` struct yourself, one
1108 /// should instead use a function like `spawn` to create new threads, see the
1109 /// docs of [`Builder`] and [`spawn`] for more details.
1111 /// [`Builder`]: ../../std/thread/struct.Builder.html
1112 /// [`JoinHandle::thread`]: ../../std/thread/struct.JoinHandle.html#method.thread
1113 /// [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
1114 /// [`thread::current`]: ../../std/thread/fn.current.html
1115 /// [`spawn`]: ../../std/thread/fn.spawn.html
1122 // Used only internally to construct a thread object without spawning
1123 // Panics if the name contains nuls.
1124 pub(crate) fn new(name: Option<String>) -> Thread {
1126 name.map(|n| CString::new(n).expect("thread name may not contain interior null bytes"));
1128 inner: Arc::new(Inner {
1130 id: ThreadId::new(),
1131 state: AtomicUsize::new(EMPTY),
1132 lock: Mutex::new(()),
1133 cvar: Condvar::new(),
1138 /// Atomically makes the handle's token available if it is not already.
1140 /// Every thread is equipped with some basic low-level blocking support, via
1141 /// the [`park`][park] function and the `unpark()` method. These can be
1142 /// used as a more CPU-efficient implementation of a spinlock.
1144 /// See the [park documentation][park] for more details.
1149 /// use std::thread;
1150 /// use std::time::Duration;
1152 /// let parked_thread = thread::Builder::new()
1154 /// println!("Parking thread");
1156 /// println!("Thread unparked");
1160 /// // Let some time pass for the thread to be spawned.
1161 /// thread::sleep(Duration::from_millis(10));
1163 /// println!("Unpark the thread");
1164 /// parked_thread.thread().unpark();
1166 /// parked_thread.join().unwrap();
1169 /// [park]: fn.park.html
1170 #[stable(feature = "rust1", since = "1.0.0")]
1171 pub fn unpark(&self) {
1172 // To ensure the unparked thread will observe any writes we made
1173 // before this call, we must perform a release operation that `park`
1174 // can synchronize with. To do that we must write `NOTIFIED` even if
1175 // `state` is already `NOTIFIED`. That is why this must be a swap
1176 // rather than a compare-and-swap that returns if it reads `NOTIFIED`
1178 match self.inner.state.swap(NOTIFIED, SeqCst) {
1179 EMPTY => return, // no one was waiting
1180 NOTIFIED => return, // already unparked
1181 PARKED => {} // gotta go wake someone up
1182 _ => panic!("inconsistent state in unpark"),
1185 // There is a period between when the parked thread sets `state` to
1186 // `PARKED` (or last checked `state` in the case of a spurious wake
1187 // up) and when it actually waits on `cvar`. If we were to notify
1188 // during this period it would be ignored and then when the parked
1189 // thread went to sleep it would never wake up. Fortunately, it has
1190 // `lock` locked at this stage so we can acquire `lock` to wait until
1191 // it is ready to receive the notification.
1193 // Releasing `lock` before the call to `notify_one` means that when the
1194 // parked thread wakes it doesn't get woken only to have to wait for us
1195 // to release `lock`.
1196 drop(self.inner.lock.lock().unwrap());
1197 self.inner.cvar.notify_one()
1200 /// Gets the thread's unique identifier.
1205 /// use std::thread;
1207 /// let other_thread = thread::spawn(|| {
1208 /// thread::current().id()
1211 /// let other_thread_id = other_thread.join().unwrap();
1212 /// assert!(thread::current().id() != other_thread_id);
1214 #[stable(feature = "thread_id", since = "1.19.0")]
1215 pub fn id(&self) -> ThreadId {
1219 /// Gets the thread's name.
1221 /// For more information about named threads, see
1222 /// [this module-level documentation][naming-threads].
1226 /// Threads by default have no name specified:
1229 /// use std::thread;
1231 /// let builder = thread::Builder::new();
1233 /// let handler = builder.spawn(|| {
1234 /// assert!(thread::current().name().is_none());
1237 /// handler.join().unwrap();
1240 /// Thread with a specified name:
1243 /// use std::thread;
1245 /// let builder = thread::Builder::new()
1246 /// .name("foo".into());
1248 /// let handler = builder.spawn(|| {
1249 /// assert_eq!(thread::current().name(), Some("foo"))
1252 /// handler.join().unwrap();
1255 /// [naming-threads]: ./index.html#naming-threads
1256 #[stable(feature = "rust1", since = "1.0.0")]
1257 pub fn name(&self) -> Option<&str> {
1258 self.cname().map(|s| unsafe { str::from_utf8_unchecked(s.to_bytes()) })
1261 fn cname(&self) -> Option<&CStr> {
1262 self.inner.name.as_ref().map(|s| &**s)
1266 #[stable(feature = "rust1", since = "1.0.0")]
1267 impl fmt::Debug for Thread {
1268 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1269 f.debug_struct("Thread").field("id", &self.id()).field("name", &self.name()).finish()
1273 ////////////////////////////////////////////////////////////////////////////////
1275 ////////////////////////////////////////////////////////////////////////////////
1277 /// A specialized [`Result`] type for threads.
1279 /// Indicates the manner in which a thread exited.
1281 /// The value contained in the `Result::Err` variant
1282 /// is the value the thread panicked with;
1283 /// that is, the argument the `panic!` macro was called with.
1284 /// Unlike with normal errors, this value doesn't implement
1285 /// the [`Error`](crate::error::Error) trait.
1287 /// Thus, a sensible way to handle a thread panic is to either:
1288 /// 1. `unwrap` the `Result<T>`, propagating the panic
1289 /// 2. or in case the thread is intended to be a subsystem boundary
1290 /// that is supposed to isolate system-level failures,
1291 /// match on the `Err` variant and handle the panic in an appropriate way.
1293 /// A thread that completes without panicking is considered to exit successfully.
1298 /// use std::thread;
1301 /// fn copy_in_thread() -> thread::Result<()> {
1302 /// thread::spawn(move || { fs::copy("foo.txt", "bar.txt").unwrap(); }).join()
1306 /// match copy_in_thread() {
1307 /// Ok(_) => println!("this is fine"),
1308 /// Err(_) => println!("thread panicked"),
1313 /// [`Result`]: ../../std/result/enum.Result.html
1314 #[stable(feature = "rust1", since = "1.0.0")]
1315 pub type Result<T> = crate::result::Result<T, Box<dyn Any + Send + 'static>>;
1317 // This packet is used to communicate the return value between the child thread
1318 // and the parent thread. Memory is shared through the `Arc` within and there's
1319 // no need for a mutex here because synchronization happens with `join()` (the
1320 // parent thread never reads this packet until the child has exited).
1322 // This packet itself is then stored into a `JoinInner` which in turns is placed
1323 // in `JoinHandle` and `JoinGuard`. Due to the usage of `UnsafeCell` we need to
1324 // manually worry about impls like Send and Sync. The type `T` should
1325 // already always be Send (otherwise the thread could not have been created) and
1326 // this type is inherently Sync because no methods take &self. Regardless,
1327 // however, we add inheriting impls for Send/Sync to this type to ensure it's
1328 // Send/Sync and that future modifications will still appropriately classify it.
1329 struct Packet<T>(Arc<UnsafeCell<Option<Result<T>>>>);
1331 unsafe impl<T: Send> Send for Packet<T> {}
1332 unsafe impl<T: Sync> Sync for Packet<T> {}
1334 /// Inner representation for JoinHandle
1335 struct JoinInner<T> {
1336 native: Option<imp::Thread>,
1341 impl<T> JoinInner<T> {
1342 fn join(&mut self) -> Result<T> {
1343 self.native.take().unwrap().join();
1344 unsafe { (*self.packet.0.get()).take().unwrap() }
1348 /// An owned permission to join on a thread (block on its termination).
1350 /// A `JoinHandle` *detaches* the associated thread when it is dropped, which
1351 /// means that there is no longer any handle to thread and no way to `join`
1354 /// Due to platform restrictions, it is not possible to [`Clone`] this
1355 /// handle: the ability to join a thread is a uniquely-owned permission.
1357 /// This `struct` is created by the [`thread::spawn`] function and the
1358 /// [`thread::Builder::spawn`] method.
1362 /// Creation from [`thread::spawn`]:
1365 /// use std::thread;
1367 /// let join_handle: thread::JoinHandle<_> = thread::spawn(|| {
1368 /// // some work here
1372 /// Creation from [`thread::Builder::spawn`]:
1375 /// use std::thread;
1377 /// let builder = thread::Builder::new();
1379 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1380 /// // some work here
1384 /// Child being detached and outliving its parent:
1387 /// use std::thread;
1388 /// use std::time::Duration;
1390 /// let original_thread = thread::spawn(|| {
1391 /// let _detached_thread = thread::spawn(|| {
1392 /// // Here we sleep to make sure that the first thread returns before.
1393 /// thread::sleep(Duration::from_millis(10));
1394 /// // This will be called, even though the JoinHandle is dropped.
1395 /// println!("♫ Still alive ♫");
1399 /// original_thread.join().expect("The thread being joined has panicked");
1400 /// println!("Original thread is joined.");
1402 /// // We make sure that the new thread has time to run, before the main
1403 /// // thread returns.
1405 /// thread::sleep(Duration::from_millis(1000));
1408 /// [`Clone`]: ../../std/clone/trait.Clone.html
1409 /// [`thread::spawn`]: fn.spawn.html
1410 /// [`thread::Builder::spawn`]: struct.Builder.html#method.spawn
1411 #[stable(feature = "rust1", since = "1.0.0")]
1412 pub struct JoinHandle<T>(JoinInner<T>);
1414 #[stable(feature = "joinhandle_impl_send_sync", since = "1.29.0")]
1415 unsafe impl<T> Send for JoinHandle<T> {}
1416 #[stable(feature = "joinhandle_impl_send_sync", since = "1.29.0")]
1417 unsafe impl<T> Sync for JoinHandle<T> {}
1419 impl<T> JoinHandle<T> {
1420 /// Extracts a handle to the underlying thread.
1425 /// use std::thread;
1427 /// let builder = thread::Builder::new();
1429 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1430 /// // some work here
1433 /// let thread = join_handle.thread();
1434 /// println!("thread id: {:?}", thread.id());
1436 #[stable(feature = "rust1", since = "1.0.0")]
1437 pub fn thread(&self) -> &Thread {
1441 /// Waits for the associated thread to finish.
1443 /// In terms of [atomic memory orderings], the completion of the associated
1444 /// thread synchronizes with this function returning. In other words, all
1445 /// operations performed by that thread are ordered before all
1446 /// operations that happen after `join` returns.
1448 /// If the child thread panics, [`Err`] is returned with the parameter given
1451 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1452 /// [`panic`]: ../../std/macro.panic.html
1453 /// [atomic memory orderings]: ../../std/sync/atomic/index.html
1457 /// This function may panic on some platforms if a thread attempts to join
1458 /// itself or otherwise may create a deadlock with joining threads.
1463 /// use std::thread;
1465 /// let builder = thread::Builder::new();
1467 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1468 /// // some work here
1470 /// join_handle.join().expect("Couldn't join on the associated thread");
1472 #[stable(feature = "rust1", since = "1.0.0")]
1473 pub fn join(mut self) -> Result<T> {
1478 impl<T> AsInner<imp::Thread> for JoinHandle<T> {
1479 fn as_inner(&self) -> &imp::Thread {
1480 self.0.native.as_ref().unwrap()
1484 impl<T> IntoInner<imp::Thread> for JoinHandle<T> {
1485 fn into_inner(self) -> imp::Thread {
1486 self.0.native.unwrap()
1490 #[stable(feature = "std_debug", since = "1.16.0")]
1491 impl<T> fmt::Debug for JoinHandle<T> {
1492 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1493 f.pad("JoinHandle { .. }")
1497 fn _assert_sync_and_send() {
1498 fn _assert_both<T: Send + Sync>() {}
1499 _assert_both::<JoinHandle<()>>();
1500 _assert_both::<Thread>();
1503 ////////////////////////////////////////////////////////////////////////////////
1505 ////////////////////////////////////////////////////////////////////////////////
1507 #[cfg(all(test, not(target_os = "emscripten")))]
1510 use crate::any::Any;
1513 use crate::sync::mpsc::{channel, Sender};
1514 use crate::thread::{self, ThreadId};
1515 use crate::time::Duration;
1518 // !!! These tests are dangerous. If something is buggy, they will hang, !!!
1519 // !!! instead of exiting cleanly. This might wedge the buildbots. !!!
1522 fn test_unnamed_thread() {
1523 thread::spawn(move || {
1524 assert!(thread::current().name().is_none());
1528 .expect("thread panicked");
1532 fn test_named_thread() {
1534 .name("ada lovelace".to_string())
1536 assert!(thread::current().name().unwrap() == "ada lovelace".to_string());
1545 fn test_invalid_named_thread() {
1546 let _ = Builder::new().name("ada l\0velace".to_string()).spawn(|| {});
1550 fn test_run_basic() {
1551 let (tx, rx) = channel();
1552 thread::spawn(move || {
1553 tx.send(()).unwrap();
1559 fn test_join_panic() {
1560 match thread::spawn(move || panic!()).join() {
1561 result::Result::Err(_) => (),
1562 result::Result::Ok(()) => panic!(),
1567 fn test_spawn_sched() {
1568 let (tx, rx) = channel();
1570 fn f(i: i32, tx: Sender<()>) {
1571 let tx = tx.clone();
1572 thread::spawn(move || {
1574 tx.send(()).unwrap();
1585 fn test_spawn_sched_childs_on_default_sched() {
1586 let (tx, rx) = channel();
1588 thread::spawn(move || {
1589 thread::spawn(move || {
1590 tx.send(()).unwrap();
1597 fn avoid_copying_the_body<F>(spawnfn: F)
1599 F: FnOnce(Box<dyn Fn() + Send>),
1601 let (tx, rx) = channel();
1603 let x: Box<_> = box 1;
1604 let x_in_parent = (&*x) as *const i32 as usize;
1606 spawnfn(Box::new(move || {
1607 let x_in_child = (&*x) as *const i32 as usize;
1608 tx.send(x_in_child).unwrap();
1611 let x_in_child = rx.recv().unwrap();
1612 assert_eq!(x_in_parent, x_in_child);
1616 fn test_avoid_copying_the_body_spawn() {
1617 avoid_copying_the_body(|v| {
1618 thread::spawn(move || v());
1623 fn test_avoid_copying_the_body_thread_spawn() {
1624 avoid_copying_the_body(|f| {
1625 thread::spawn(move || {
1632 fn test_avoid_copying_the_body_join() {
1633 avoid_copying_the_body(|f| {
1634 let _ = thread::spawn(move || f()).join();
1639 fn test_child_doesnt_ref_parent() {
1640 // If the child refcounts the parent thread, this will stack overflow when
1641 // climbing the thread tree to dereference each ancestor. (See #1789)
1642 // (well, it would if the constant were 8000+ - I lowered it to be more
1643 // valgrind-friendly. try this at home, instead..!)
1644 const GENERATIONS: u32 = 16;
1645 fn child_no(x: u32) -> Box<dyn Fn() + Send> {
1646 return Box::new(move || {
1647 if x < GENERATIONS {
1648 thread::spawn(move || child_no(x + 1)());
1652 thread::spawn(|| child_no(0)());
1656 fn test_simple_newsched_spawn() {
1657 thread::spawn(move || {});
1661 fn test_try_panic_message_static_str() {
1662 match thread::spawn(move || {
1663 panic!("static string");
1668 type T = &'static str;
1669 assert!(e.is::<T>());
1670 assert_eq!(*e.downcast::<T>().unwrap(), "static string");
1677 fn test_try_panic_message_owned_str() {
1678 match thread::spawn(move || {
1679 panic!("owned string".to_string());
1685 assert!(e.is::<T>());
1686 assert_eq!(*e.downcast::<T>().unwrap(), "owned string".to_string());
1693 fn test_try_panic_message_any() {
1694 match thread::spawn(move || {
1695 panic!(box 413u16 as Box<dyn Any + Send>);
1700 type T = Box<dyn Any + Send>;
1701 assert!(e.is::<T>());
1702 let any = e.downcast::<T>().unwrap();
1703 assert!(any.is::<u16>());
1704 assert_eq!(*any.downcast::<u16>().unwrap(), 413);
1711 fn test_try_panic_message_unit_struct() {
1714 match thread::spawn(move || panic!(Juju)).join() {
1715 Err(ref e) if e.is::<Juju>() => {}
1716 Err(_) | Ok(()) => panic!(),
1721 fn test_park_timeout_unpark_before() {
1723 thread::current().unpark();
1724 thread::park_timeout(Duration::from_millis(u32::MAX as u64));
1729 #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1730 fn test_park_timeout_unpark_not_called() {
1732 thread::park_timeout(Duration::from_millis(10));
1737 #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1738 fn test_park_timeout_unpark_called_other_thread() {
1740 let th = thread::current();
1742 let _guard = thread::spawn(move || {
1743 super::sleep(Duration::from_millis(50));
1747 thread::park_timeout(Duration::from_millis(u32::MAX as u64));
1752 #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1753 fn sleep_ms_smoke() {
1754 thread::sleep(Duration::from_millis(2));
1758 fn test_size_of_option_thread_id() {
1759 assert_eq!(mem::size_of::<Option<ThreadId>>(), mem::size_of::<ThreadId>());
1763 fn test_thread_id_equal() {
1764 assert!(thread::current().id() == thread::current().id());
1768 fn test_thread_id_not_equal() {
1769 let spawned_id = thread::spawn(|| thread::current().id()).join().unwrap();
1770 assert!(thread::current().id() != spawned_id);
1773 // NOTE: the corresponding test for stderr is in ui/thread-stderr, due
1774 // to the test harness apparently interfering with stderr configuration.