1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 //! ## The threading model
15 //! An executing Rust program consists of a collection of native OS threads,
16 //! each with their own stack and local state. Threads can be named, and
17 //! provide some built-in support for low-level synchronization.
19 //! Communication between threads can be done through
20 //! [channels], Rust's message-passing types, along with [other forms of thread
21 //! synchronization](../../std/sync/index.html) and shared-memory data
22 //! structures. In particular, types that are guaranteed to be
23 //! threadsafe are easily shared between threads using the
24 //! atomically-reference-counted container, [`Arc`].
26 //! Fatal logic errors in Rust cause *thread panic*, during which
27 //! a thread will unwind the stack, running destructors and freeing
28 //! owned resources. While not meant as a 'try/catch' mechanism, panics
29 //! in Rust can nonetheless be caught (unless compiling with `panic=abort`) with
30 //! [`catch_unwind`](../../std/panic/fn.catch_unwind.html) and recovered
31 //! from, or alternatively be resumed with
32 //! [`resume_unwind`](../../std/panic/fn.resume_unwind.html). If the panic
33 //! is not caught the thread will exit, but the panic may optionally be
34 //! detected from a different thread with [`join`]. If the main thread panics
35 //! without the panic being caught, the application will exit with a
36 //! non-zero exit code.
38 //! When the main thread of a Rust program terminates, the entire program shuts
39 //! down, even if other threads are still running. However, this module provides
40 //! convenient facilities for automatically waiting for the termination of a
41 //! child thread (i.e., join).
43 //! ## Spawning a thread
45 //! A new thread can be spawned using the [`thread::spawn`][`spawn`] function:
50 //! thread::spawn(move || {
55 //! In this example, the spawned thread is "detached" from the current
56 //! thread. This means that it can outlive its parent (the thread that spawned
57 //! it), unless this parent is the main thread.
59 //! The parent thread can also wait on the completion of the child
60 //! thread; a call to [`spawn`] produces a [`JoinHandle`], which provides
61 //! a `join` method for waiting:
66 //! let child = thread::spawn(move || {
70 //! let res = child.join();
73 //! The [`join`] method returns a [`thread::Result`] containing [`Ok`] of the final
74 //! value produced by the child thread, or [`Err`] of the value given to
75 //! a call to [`panic!`] if the child panicked.
77 //! ## Configuring threads
79 //! A new thread can be configured before it is spawned via the [`Builder`] type,
80 //! which currently allows you to set the name and stack size for the child thread:
83 //! # #![allow(unused_must_use)]
86 //! thread::Builder::new().name("child1".to_string()).spawn(move || {
87 //! println!("Hello, world!");
91 //! ## The `Thread` type
93 //! Threads are represented via the [`Thread`] type, which you can get in one of
96 //! * By spawning a new thread, e.g., using the [`thread::spawn`][`spawn`]
97 //! function, and calling [`thread`][`JoinHandle::thread`] on the [`JoinHandle`].
98 //! * By requesting the current thread, using the [`thread::current`] function.
100 //! The [`thread::current`] function is available even for threads not spawned
101 //! by the APIs of this module.
103 //! ## Thread-local storage
105 //! This module also provides an implementation of thread-local storage for Rust
106 //! programs. Thread-local storage is a method of storing data into a global
107 //! variable that each thread in the program will have its own copy of.
108 //! Threads do not share this data, so accesses do not need to be synchronized.
110 //! A thread-local key owns the value it contains and will destroy the value when the
111 //! thread exits. It is created with the [`thread_local!`] macro and can contain any
112 //! value that is `'static` (no borrowed pointers). It provides an accessor function,
113 //! [`with`], that yields a shared reference to the value to the specified
114 //! closure. Thread-local keys allow only shared access to values, as there would be no
115 //! way to guarantee uniqueness if mutable borrows were allowed. Most values
116 //! will want to make use of some form of **interior mutability** through the
117 //! [`Cell`] or [`RefCell`] types.
119 //! ## Naming threads
121 //! Threads are able to have associated names for identification purposes. By default, spawned
122 //! threads are unnamed. To specify a name for a thread, build the thread with [`Builder`] and pass
123 //! the desired thread name to [`Builder::name`]. To retrieve the thread name from within the
124 //! thread, use [`Thread::name`]. A couple examples of where the name of a thread gets used:
126 //! * If a panic occurs in a named thread, the thread name will be printed in the panic message.
127 //! * The thread name is provided to the OS where applicable (e.g., `pthread_setname_np` in
128 //! unix-like platforms).
132 //! The default stack size for spawned threads is 2 MiB, though this particular stack size is
133 //! subject to change in the future. There are two ways to manually specify the stack size for
136 //! * Build the thread with [`Builder`] and pass the desired stack size to [`Builder::stack_size`].
137 //! * Set the `RUST_MIN_STACK` environment variable to an integer representing the desired stack
138 //! size (in bytes). Note that setting [`Builder::stack_size`] will override this.
140 //! Note that the stack size of the main thread is *not* determined by Rust.
142 //! [channels]: ../../std/sync/mpsc/index.html
143 //! [`Arc`]: ../../std/sync/struct.Arc.html
144 //! [`spawn`]: ../../std/thread/fn.spawn.html
145 //! [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
146 //! [`JoinHandle::thread`]: ../../std/thread/struct.JoinHandle.html#method.thread
147 //! [`join`]: ../../std/thread/struct.JoinHandle.html#method.join
148 //! [`Result`]: ../../std/result/enum.Result.html
149 //! [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
150 //! [`Err`]: ../../std/result/enum.Result.html#variant.Err
151 //! [`panic!`]: ../../std/macro.panic.html
152 //! [`Builder`]: ../../std/thread/struct.Builder.html
153 //! [`Builder::stack_size`]: ../../std/thread/struct.Builder.html#method.stack_size
154 //! [`Builder::name`]: ../../std/thread/struct.Builder.html#method.name
155 //! [`thread::current`]: ../../std/thread/fn.current.html
156 //! [`thread::Result`]: ../../std/thread/type.Result.html
157 //! [`Thread`]: ../../std/thread/struct.Thread.html
158 //! [`park`]: ../../std/thread/fn.park.html
159 //! [`unpark`]: ../../std/thread/struct.Thread.html#method.unpark
160 //! [`Thread::name`]: ../../std/thread/struct.Thread.html#method.name
161 //! [`thread::park_timeout`]: ../../std/thread/fn.park_timeout.html
162 //! [`Cell`]: ../cell/struct.Cell.html
163 //! [`RefCell`]: ../cell/struct.RefCell.html
164 //! [`thread_local!`]: ../macro.thread_local.html
165 //! [`with`]: struct.LocalKey.html#method.with
167 #![stable(feature = "rust1", since = "1.0.0")]
171 use cell::UnsafeCell;
172 use ffi::{CStr, CString};
179 use sync::{Mutex, Condvar, Arc};
180 use sync::atomic::AtomicUsize;
181 use sync::atomic::Ordering::SeqCst;
182 use sys::thread as imp;
183 use sys_common::mutex;
184 use sys_common::thread_info;
185 use sys_common::thread;
186 use sys_common::{AsInner, IntoInner};
189 ////////////////////////////////////////////////////////////////////////////////
190 // Thread-local storage
191 ////////////////////////////////////////////////////////////////////////////////
193 #[macro_use] mod local;
195 #[stable(feature = "rust1", since = "1.0.0")]
196 pub use self::local::{LocalKey, AccessError};
198 // The types used by the thread_local! macro to access TLS keys. Note that there
199 // are two types, the "OS" type and the "fast" type. The OS thread local key
200 // type is accessed via platform-specific API calls and is slow, while the fast
201 // key type is accessed via code generated via LLVM, where TLS keys are set up
202 // by the elf linker. Note that the OS TLS type is always available: on macOS
203 // the standard library is compiled with support for older platform versions
204 // where fast TLS was not available; end-user code is compiled with fast TLS
205 // where available, but both are needed.
207 #[unstable(feature = "libstd_thread_internals", issue = "0")]
208 #[cfg(all(target_arch = "wasm32", not(target_feature = "atomics")))]
209 #[doc(hidden)] pub use self::local::statik::Key as __StaticLocalKeyInner;
210 #[unstable(feature = "libstd_thread_internals", issue = "0")]
211 #[cfg(target_thread_local)]
212 #[doc(hidden)] pub use self::local::fast::Key as __FastLocalKeyInner;
213 #[unstable(feature = "libstd_thread_internals", issue = "0")]
214 #[doc(hidden)] pub use self::local::os::Key as __OsLocalKeyInner;
216 ////////////////////////////////////////////////////////////////////////////////
218 ////////////////////////////////////////////////////////////////////////////////
220 /// Thread factory, which can be used in order to configure the properties of
223 /// Methods can be chained on it in order to configure it.
225 /// The two configurations available are:
227 /// - [`name`]: specifies an [associated name for the thread][naming-threads]
228 /// - [`stack_size`]: specifies the [desired stack size for the thread][stack-size]
230 /// The [`spawn`] method will take ownership of the builder and create an
231 /// [`io::Result`] to the thread handle with the given configuration.
233 /// The [`thread::spawn`] free function uses a `Builder` with default
234 /// configuration and [`unwrap`]s its return value.
236 /// You may want to use [`spawn`] instead of [`thread::spawn`], when you want
237 /// to recover from a failure to launch a thread, indeed the free function will
238 /// panic where the `Builder` method will return a [`io::Result`].
245 /// let builder = thread::Builder::new();
247 /// let handler = builder.spawn(|| {
251 /// handler.join().unwrap();
254 /// [`thread::spawn`]: ../../std/thread/fn.spawn.html
255 /// [`stack_size`]: ../../std/thread/struct.Builder.html#method.stack_size
256 /// [`name`]: ../../std/thread/struct.Builder.html#method.name
257 /// [`spawn`]: ../../std/thread/struct.Builder.html#method.spawn
258 /// [`io::Result`]: ../../std/io/type.Result.html
259 /// [`unwrap`]: ../../std/result/enum.Result.html#method.unwrap
260 /// [naming-threads]: ./index.html#naming-threads
261 /// [stack-size]: ./index.html#stack-size
262 #[stable(feature = "rust1", since = "1.0.0")]
265 // A name for the thread-to-be, for identification in panic messages
266 name: Option<String>,
267 // The size of the stack for the spawned thread in bytes
268 stack_size: Option<usize>,
272 /// Generates the base configuration for spawning a thread, from which
273 /// configuration methods can be chained.
280 /// let builder = thread::Builder::new()
281 /// .name("foo".into())
284 /// let handler = builder.spawn(|| {
288 /// handler.join().unwrap();
290 #[stable(feature = "rust1", since = "1.0.0")]
291 pub fn new() -> Builder {
298 /// Names the thread-to-be. Currently the name is used for identification
299 /// only in panic messages.
301 /// The name must not contain null bytes (`\0`).
303 /// For more information about named threads, see
304 /// [this module-level documentation][naming-threads].
311 /// let builder = thread::Builder::new()
312 /// .name("foo".into());
314 /// let handler = builder.spawn(|| {
315 /// assert_eq!(thread::current().name(), Some("foo"))
318 /// handler.join().unwrap();
321 /// [naming-threads]: ./index.html#naming-threads
322 #[stable(feature = "rust1", since = "1.0.0")]
323 pub fn name(mut self, name: String) -> Builder {
324 self.name = Some(name);
328 /// Sets the size of the stack (in bytes) for the new thread.
330 /// The actual stack size may be greater than this value if
331 /// the platform specifies a minimal stack size.
333 /// For more information about the stack size for threads, see
334 /// [this module-level documentation][stack-size].
341 /// let builder = thread::Builder::new().stack_size(32 * 1024);
344 /// [stack-size]: ./index.html#stack-size
345 #[stable(feature = "rust1", since = "1.0.0")]
346 pub fn stack_size(mut self, size: usize) -> Builder {
347 self.stack_size = Some(size);
351 /// Spawns a new thread by taking ownership of the `Builder`, and returns an
352 /// [`io::Result`] to its [`JoinHandle`].
354 /// The spawned thread may outlive the caller (unless the caller thread
355 /// is the main thread; the whole process is terminated when the main
356 /// thread finishes). The join handle can be used to block on
357 /// termination of the child thread, including recovering its panics.
359 /// For a more complete documentation see [`thread::spawn`][`spawn`].
363 /// Unlike the [`spawn`] free function, this method yields an
364 /// [`io::Result`] to capture any failure to create the thread at
367 /// [`spawn`]: ../../std/thread/fn.spawn.html
368 /// [`io::Result`]: ../../std/io/type.Result.html
369 /// [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
373 /// Panics if a thread name was set and it contained null bytes.
380 /// let builder = thread::Builder::new();
382 /// let handler = builder.spawn(|| {
386 /// handler.join().unwrap();
388 #[stable(feature = "rust1", since = "1.0.0")]
389 pub fn spawn<F, T>(self, f: F) -> io::Result<JoinHandle<T>> where
390 F: FnOnce() -> T, F: Send + 'static, T: Send + 'static
392 unsafe { self.spawn_unchecked(f) }
395 /// Spawns a new thread without any lifetime restrictions by taking ownership
396 /// of the `Builder`, and returns an [`io::Result`] to its [`JoinHandle`].
398 /// The spawned thread may outlive the caller (unless the caller thread
399 /// is the main thread; the whole process is terminated when the main
400 /// thread finishes). The join handle can be used to block on
401 /// termination of the child thread, including recovering its panics.
403 /// This method is identical to [`thread::Builder::spawn`][`Builder::spawn`],
404 /// except for the relaxed lifetime bounds, which render it unsafe.
405 /// For a more complete documentation see [`thread::spawn`][`spawn`].
409 /// Unlike the [`spawn`] free function, this method yields an
410 /// [`io::Result`] to capture any failure to create the thread at
415 /// Panics if a thread name was set and it contained null bytes.
419 /// The caller has to ensure that no references in the supplied thread closure
420 /// or its return type can outlive the spawned thread's lifetime. This can be
421 /// guaranteed in two ways:
423 /// - ensure that [`join`][`JoinHandle::join`] is called before any referenced
425 /// - use only types with `'static` lifetime bounds, i.e., those with no or only
426 /// `'static` references (both [`thread::Builder::spawn`][`Builder::spawn`]
427 /// and [`thread::spawn`][`spawn`] enforce this property statically)
432 /// #![feature(thread_spawn_unchecked)]
435 /// let builder = thread::Builder::new();
438 /// let thread_x = &x;
440 /// let handler = unsafe {
441 /// builder.spawn_unchecked(move || {
442 /// println!("x = {}", *thread_x);
446 /// // caller has to ensure `join()` is called, otherwise
447 /// // it is possible to access freed memory if `x` gets
448 /// // dropped before the thread closure is executed!
449 /// handler.join().unwrap();
452 /// [`spawn`]: ../../std/thread/fn.spawn.html
453 /// [`Builder::spawn`]: ../../std/thread/struct.Builder.html#method.spawn
454 /// [`io::Result`]: ../../std/io/type.Result.html
455 /// [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
456 #[unstable(feature = "thread_spawn_unchecked", issue = "55132")]
457 pub unsafe fn spawn_unchecked<'a, F, T>(self, f: F) -> io::Result<JoinHandle<T>> where
458 F: FnOnce() -> T, F: Send + 'a, T: Send + 'a
460 let Builder { name, stack_size } = self;
462 let stack_size = stack_size.unwrap_or_else(thread::min_stack);
464 let my_thread = Thread::new(name);
465 let their_thread = my_thread.clone();
467 let my_packet : Arc<UnsafeCell<Option<Result<T>>>>
468 = Arc::new(UnsafeCell::new(None));
469 let their_packet = my_packet.clone();
472 if let Some(name) = their_thread.cname() {
473 imp::Thread::set_name(name);
476 thread_info::set(imp::guard::current(), their_thread);
477 #[cfg(feature = "backtrace")]
478 let try_result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
479 ::sys_common::backtrace::__rust_begin_short_backtrace(f)
481 #[cfg(not(feature = "backtrace"))]
482 let try_result = panic::catch_unwind(panic::AssertUnwindSafe(f));
483 *their_packet.get() = Some(try_result);
486 Ok(JoinHandle(JoinInner {
487 // `imp::Thread::new` takes a closure with a `'static` lifetime, since it's passed
488 // through FFI or otherwise used with low-level threading primitives that have no
489 // notion of or way to enforce lifetimes.
491 // As mentioned in the `Safety` section of this function's documentation, the caller of
492 // this function needs to guarantee that the passed-in lifetime is sufficiently long
493 // for the lifetime of the thread.
495 // Similarly, the `sys` implementation must guarantee that no references to the closure
496 // exist after the thread has terminated, which is signaled by `Thread::join`
498 native: Some(imp::Thread::new(
500 mem::transmute::<Box<dyn FnBox() + 'a>, Box<dyn FnBox() + 'static>>(Box::new(main))
503 packet: Packet(my_packet),
508 ////////////////////////////////////////////////////////////////////////////////
510 ////////////////////////////////////////////////////////////////////////////////
512 /// Spawns a new thread, returning a [`JoinHandle`] for it.
514 /// The join handle will implicitly *detach* the child thread upon being
515 /// dropped. In this case, the child thread may outlive the parent (unless
516 /// the parent thread is the main thread; the whole process is terminated when
517 /// the main thread finishes). Additionally, the join handle provides a [`join`]
518 /// method that can be used to join the child thread. If the child thread
519 /// panics, [`join`] will return an [`Err`] containing the argument given to
522 /// This will create a thread using default parameters of [`Builder`], if you
523 /// want to specify the stack size or the name of the thread, use this API
526 /// As you can see in the signature of `spawn` there are two constraints on
527 /// both the closure given to `spawn` and its return value, let's explain them:
529 /// - The `'static` constraint means that the closure and its return value
530 /// must have a lifetime of the whole program execution. The reason for this
531 /// is that threads can `detach` and outlive the lifetime they have been
533 /// Indeed if the thread, and by extension its return value, can outlive their
534 /// caller, we need to make sure that they will be valid afterwards, and since
535 /// we *can't* know when it will return we need to have them valid as long as
536 /// possible, that is until the end of the program, hence the `'static`
538 /// - The [`Send`] constraint is because the closure will need to be passed
539 /// *by value* from the thread where it is spawned to the new thread. Its
540 /// return value will need to be passed from the new thread to the thread
541 /// where it is `join`ed.
542 /// As a reminder, the [`Send`] marker trait expresses that it is safe to be
543 /// passed from thread to thread. [`Sync`] expresses that it is safe to have a
544 /// reference be passed from thread to thread.
548 /// Panics if the OS fails to create a thread; use [`Builder::spawn`]
549 /// to recover from such errors.
553 /// Creating a thread.
558 /// let handler = thread::spawn(|| {
562 /// handler.join().unwrap();
565 /// As mentioned in the module documentation, threads are usually made to
566 /// communicate using [`channels`], here is how it usually looks.
568 /// This example also shows how to use `move`, in order to give ownership
569 /// of values to a thread.
573 /// use std::sync::mpsc::channel;
575 /// let (tx, rx) = channel();
577 /// let sender = thread::spawn(move || {
578 /// tx.send("Hello, thread".to_owned())
579 /// .expect("Unable to send on channel");
582 /// let receiver = thread::spawn(move || {
583 /// let value = rx.recv().expect("Unable to receive from channel");
584 /// println!("{}", value);
587 /// sender.join().expect("The sender thread has panicked");
588 /// receiver.join().expect("The receiver thread has panicked");
591 /// A thread can also return a value through its [`JoinHandle`], you can use
592 /// this to make asynchronous computations (futures might be more appropriate
598 /// let computation = thread::spawn(|| {
599 /// // Some expensive computation.
603 /// let result = computation.join().unwrap();
604 /// println!("{}", result);
607 /// [`channels`]: ../../std/sync/mpsc/index.html
608 /// [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
609 /// [`join`]: ../../std/thread/struct.JoinHandle.html#method.join
610 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
611 /// [`panic`]: ../../std/macro.panic.html
612 /// [`Builder::spawn`]: ../../std/thread/struct.Builder.html#method.spawn
613 /// [`Builder`]: ../../std/thread/struct.Builder.html
614 /// [`Send`]: ../../std/marker/trait.Send.html
615 /// [`Sync`]: ../../std/marker/trait.Sync.html
616 #[stable(feature = "rust1", since = "1.0.0")]
617 pub fn spawn<F, T>(f: F) -> JoinHandle<T> where
618 F: FnOnce() -> T, F: Send + 'static, T: Send + 'static
620 Builder::new().spawn(f).unwrap()
623 /// Gets a handle to the thread that invokes it.
627 /// Getting a handle to the current thread with `thread::current()`:
632 /// let handler = thread::Builder::new()
633 /// .name("named thread".into())
635 /// let handle = thread::current();
636 /// assert_eq!(handle.name(), Some("named thread"));
640 /// handler.join().unwrap();
642 #[stable(feature = "rust1", since = "1.0.0")]
643 pub fn current() -> Thread {
644 thread_info::current_thread().expect("use of std::thread::current() is not \
645 possible after the thread's local \
646 data has been destroyed")
649 /// Cooperatively gives up a timeslice to the OS scheduler.
651 /// This is used when the programmer knows that the thread will have nothing
652 /// to do for some time, and thus avoid wasting computing time.
654 /// For example when polling on a resource, it is common to check that it is
655 /// available, and if not to yield in order to avoid busy waiting.
657 /// Thus the pattern of `yield`ing after a failed poll is rather common when
658 /// implementing low-level shared resources or synchronization primitives.
660 /// However programmers will usually prefer to use [`channel`]s, [`Condvar`]s,
661 /// [`Mutex`]es or [`join`] for their synchronization routines, as they avoid
662 /// thinking about thread scheduling.
664 /// Note that [`channel`]s for example are implemented using this primitive.
665 /// Indeed when you call `send` or `recv`, which are blocking, they will yield
666 /// if the channel is not available.
673 /// thread::yield_now();
676 /// [`channel`]: ../../std/sync/mpsc/index.html
677 /// [`spawn`]: ../../std/thread/fn.spawn.html
678 /// [`join`]: ../../std/thread/struct.JoinHandle.html#method.join
679 /// [`Mutex`]: ../../std/sync/struct.Mutex.html
680 /// [`Condvar`]: ../../std/sync/struct.Condvar.html
681 #[stable(feature = "rust1", since = "1.0.0")]
683 imp::Thread::yield_now()
686 /// Determines whether the current thread is unwinding because of panic.
688 /// A common use of this feature is to poison shared resources when writing
689 /// unsafe code, by checking `panicking` when the `drop` is called.
691 /// This is usually not needed when writing safe code, as [`Mutex`es][Mutex]
692 /// already poison themselves when a thread panics while holding the lock.
694 /// This can also be used in multithreaded applications, in order to send a
695 /// message to other threads warning that a thread has panicked (e.g., for
696 /// monitoring purposes).
703 /// struct SomeStruct;
705 /// impl Drop for SomeStruct {
706 /// fn drop(&mut self) {
707 /// if thread::panicking() {
708 /// println!("dropped while unwinding");
710 /// println!("dropped while not unwinding");
717 /// let a = SomeStruct;
722 /// let b = SomeStruct;
727 /// [Mutex]: ../../std/sync/struct.Mutex.html
729 #[stable(feature = "rust1", since = "1.0.0")]
730 pub fn panicking() -> bool {
731 panicking::panicking()
734 /// Puts the current thread to sleep for at least the specified amount of time.
736 /// The thread may sleep longer than the duration specified due to scheduling
737 /// specifics or platform-dependent functionality. It will never sleep less.
739 /// # Platform-specific behavior
741 /// On Unix platforms, the underlying syscall may be interrupted by a
742 /// spurious wakeup or signal handler. To ensure the sleep occurs for at least
743 /// the specified duration, this function may invoke that system call multiple
751 /// // Let's sleep for 2 seconds:
752 /// thread::sleep_ms(2000);
754 #[stable(feature = "rust1", since = "1.0.0")]
755 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::sleep`")]
756 pub fn sleep_ms(ms: u32) {
757 sleep(Duration::from_millis(ms as u64))
760 /// Puts the current thread to sleep for at least the specified amount of time.
762 /// The thread may sleep longer than the duration specified due to scheduling
763 /// specifics or platform-dependent functionality. It will never sleep less.
765 /// # Platform-specific behavior
767 /// On Unix platforms, the underlying syscall may be interrupted by a
768 /// spurious wakeup or signal handler. To ensure the sleep occurs for at least
769 /// the specified duration, this function may invoke that system call multiple
771 /// Platforms which do not support nanosecond precision for sleeping will
772 /// have `dur` rounded up to the nearest granularity of time they can sleep for.
777 /// use std::{thread, time};
779 /// let ten_millis = time::Duration::from_millis(10);
780 /// let now = time::Instant::now();
782 /// thread::sleep(ten_millis);
784 /// assert!(now.elapsed() >= ten_millis);
786 #[stable(feature = "thread_sleep", since = "1.4.0")]
787 pub fn sleep(dur: Duration) {
788 imp::Thread::sleep(dur)
791 // constants for park/unpark
792 const EMPTY: usize = 0;
793 const PARKED: usize = 1;
794 const NOTIFIED: usize = 2;
796 /// Blocks unless or until the current thread's token is made available.
798 /// A call to `park` does not guarantee that the thread will remain parked
799 /// forever, and callers should be prepared for this possibility.
801 /// # park and unpark
803 /// Every thread is equipped with some basic low-level blocking support, via the
804 /// [`thread::park`][`park`] function and [`thread::Thread::unpark`][`unpark`]
805 /// method. [`park`] blocks the current thread, which can then be resumed from
806 /// another thread by calling the [`unpark`] method on the blocked thread's
809 /// Conceptually, each [`Thread`] handle has an associated token, which is
810 /// initially not present:
812 /// * The [`thread::park`][`park`] function blocks the current thread unless or
813 /// until the token is available for its thread handle, at which point it
814 /// atomically consumes the token. It may also return *spuriously*, without
815 /// consuming the token. [`thread::park_timeout`] does the same, but allows
816 /// specifying a maximum time to block the thread for.
818 /// * The [`unpark`] method on a [`Thread`] atomically makes the token available
819 /// if it wasn't already. Because the token is initially absent, [`unpark`]
820 /// followed by [`park`] will result in the second call returning immediately.
822 /// In other words, each [`Thread`] acts a bit like a spinlock that can be
823 /// locked and unlocked using `park` and `unpark`.
825 /// The API is typically used by acquiring a handle to the current thread,
826 /// placing that handle in a shared data structure so that other threads can
827 /// find it, and then `park`ing. When some desired condition is met, another
828 /// thread calls [`unpark`] on the handle.
830 /// The motivation for this design is twofold:
832 /// * It avoids the need to allocate mutexes and condvars when building new
833 /// synchronization primitives; the threads already provide basic
834 /// blocking/signaling.
836 /// * It can be implemented very efficiently on many platforms.
842 /// use std::time::Duration;
844 /// let parked_thread = thread::Builder::new()
846 /// println!("Parking thread");
848 /// println!("Thread unparked");
852 /// // Let some time pass for the thread to be spawned.
853 /// thread::sleep(Duration::from_millis(10));
855 /// // There is no race condition here, if `unpark`
856 /// // happens first, `park` will return immediately.
857 /// println!("Unpark the thread");
858 /// parked_thread.thread().unpark();
860 /// parked_thread.join().unwrap();
863 /// [`Thread`]: ../../std/thread/struct.Thread.html
864 /// [`park`]: ../../std/thread/fn.park.html
865 /// [`unpark`]: ../../std/thread/struct.Thread.html#method.unpark
866 /// [`thread::park_timeout`]: ../../std/thread/fn.park_timeout.html
868 // The implementation currently uses the trivial strategy of a Mutex+Condvar
869 // with wakeup flag, which does not actually allow spurious wakeups. In the
870 // future, this will be implemented in a more efficient way, perhaps along the lines of
871 // http://cr.openjdk.java.net/~stefank/6989984.1/raw_files/new/src/os/linux/vm/os_linux.cpp
872 // or futuxes, and in either case may allow spurious wakeups.
873 #[stable(feature = "rust1", since = "1.0.0")]
875 let thread = current();
877 // If we were previously notified then we consume this notification and
879 if thread.inner.state.compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst).is_ok() {
883 // Otherwise we need to coordinate going to sleep
884 let mut m = thread.inner.lock.lock().unwrap();
885 match thread.inner.state.compare_exchange(EMPTY, PARKED, SeqCst, SeqCst) {
888 // We must read here, even though we know it will be `NOTIFIED`.
889 // This is because `unpark` may have been called again since we read
890 // `NOTIFIED` in the `compare_exchange` above. We must perform an
891 // acquire operation that synchronizes with that `unpark` to observe
892 // any writes it made before the call to unpark. To do that we must
893 // read from the write it made to `state`.
894 let old = thread.inner.state.swap(EMPTY, SeqCst);
895 assert_eq!(old, NOTIFIED, "park state changed unexpectedly");
897 } // should consume this notification, so prohibit spurious wakeups in next park.
898 Err(_) => panic!("inconsistent park state"),
901 m = thread.inner.cvar.wait(m).unwrap();
902 match thread.inner.state.compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst) {
903 Ok(_) => return, // got a notification
904 Err(_) => {} // spurious wakeup, go back to sleep
909 /// Use [`park_timeout`].
911 /// Blocks unless or until the current thread's token is made available or
912 /// the specified duration has been reached (may wake spuriously).
914 /// The semantics of this function are equivalent to [`park`] except
915 /// that the thread will be blocked for roughly no longer than `dur`. This
916 /// method should not be used for precise timing due to anomalies such as
917 /// preemption or platform differences that may not cause the maximum
918 /// amount of time waited to be precisely `ms` long.
920 /// See the [park documentation][`park`] for more detail.
922 /// [`park_timeout`]: fn.park_timeout.html
923 /// [`park`]: ../../std/thread/fn.park.html
924 #[stable(feature = "rust1", since = "1.0.0")]
925 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::park_timeout`")]
926 pub fn park_timeout_ms(ms: u32) {
927 park_timeout(Duration::from_millis(ms as u64))
930 /// Blocks unless or until the current thread's token is made available or
931 /// the specified duration has been reached (may wake spuriously).
933 /// The semantics of this function are equivalent to [`park`][park] except
934 /// that the thread will be blocked for roughly no longer than `dur`. This
935 /// method should not be used for precise timing due to anomalies such as
936 /// preemption or platform differences that may not cause the maximum
937 /// amount of time waited to be precisely `dur` long.
939 /// See the [park documentation][park] for more details.
941 /// # Platform-specific behavior
943 /// Platforms which do not support nanosecond precision for sleeping will have
944 /// `dur` rounded up to the nearest granularity of time they can sleep for.
948 /// Waiting for the complete expiration of the timeout:
951 /// use std::thread::park_timeout;
952 /// use std::time::{Instant, Duration};
954 /// let timeout = Duration::from_secs(2);
955 /// let beginning_park = Instant::now();
957 /// let mut timeout_remaining = timeout;
959 /// park_timeout(timeout_remaining);
960 /// let elapsed = beginning_park.elapsed();
961 /// if elapsed >= timeout {
964 /// println!("restarting park_timeout after {:?}", elapsed);
965 /// timeout_remaining = timeout - elapsed;
969 /// [park]: fn.park.html
970 #[stable(feature = "park_timeout", since = "1.4.0")]
971 pub fn park_timeout(dur: Duration) {
972 let thread = current();
974 // Like `park` above we have a fast path for an already-notified thread, and
975 // afterwards we start coordinating for a sleep.
977 if thread.inner.state.compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst).is_ok() {
980 let m = thread.inner.lock.lock().unwrap();
981 match thread.inner.state.compare_exchange(EMPTY, PARKED, SeqCst, SeqCst) {
984 // We must read again here, see `park`.
985 let old = thread.inner.state.swap(EMPTY, SeqCst);
986 assert_eq!(old, NOTIFIED, "park state changed unexpectedly");
988 } // should consume this notification, so prohibit spurious wakeups in next park.
989 Err(_) => panic!("inconsistent park_timeout state"),
992 // Wait with a timeout, and if we spuriously wake up or otherwise wake up
993 // from a notification we just want to unconditionally set the state back to
994 // empty, either consuming a notification or un-flagging ourselves as
996 let (_m, _result) = thread.inner.cvar.wait_timeout(m, dur).unwrap();
997 match thread.inner.state.swap(EMPTY, SeqCst) {
998 NOTIFIED => {} // got a notification, hurray!
999 PARKED => {} // no notification, alas
1000 n => panic!("inconsistent park_timeout state: {}", n),
1004 ////////////////////////////////////////////////////////////////////////////////
1006 ////////////////////////////////////////////////////////////////////////////////
1008 /// A unique identifier for a running thread.
1010 /// A `ThreadId` is an opaque object that has a unique value for each thread
1011 /// that creates one. `ThreadId`s are not guaranteed to correspond to a thread's
1012 /// system-designated identifier. A `ThreadId` can be retrieved from the [`id`]
1013 /// method on a [`Thread`].
1018 /// use std::thread;
1020 /// let other_thread = thread::spawn(|| {
1021 /// thread::current().id()
1024 /// let other_thread_id = other_thread.join().unwrap();
1025 /// assert!(thread::current().id() != other_thread_id);
1028 /// [`id`]: ../../std/thread/struct.Thread.html#method.id
1029 /// [`Thread`]: ../../std/thread/struct.Thread.html
1030 #[stable(feature = "thread_id", since = "1.19.0")]
1031 #[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
1032 pub struct ThreadId(u64);
1035 // Generate a new unique thread ID.
1036 fn new() -> ThreadId {
1037 // We never call `GUARD.init()`, so it is UB to attempt to
1038 // acquire this mutex reentrantly!
1039 static GUARD: mutex::Mutex = mutex::Mutex::new();
1040 static mut COUNTER: u64 = 0;
1043 let _guard = GUARD.lock();
1045 // If we somehow use up all our bits, panic so that we're not
1046 // covering up subtle bugs of IDs being reused.
1047 if COUNTER == ::u64::MAX {
1048 panic!("failed to generate unique thread ID: bitspace exhausted");
1059 ////////////////////////////////////////////////////////////////////////////////
1061 ////////////////////////////////////////////////////////////////////////////////
1063 /// The internal representation of a `Thread` handle
1065 name: Option<CString>, // Guaranteed to be UTF-8
1068 // state for thread park/unpark
1075 #[stable(feature = "rust1", since = "1.0.0")]
1076 /// A handle to a thread.
1078 /// Threads are represented via the `Thread` type, which you can get in one of
1081 /// * By spawning a new thread, e.g., using the [`thread::spawn`][`spawn`]
1082 /// function, and calling [`thread`][`JoinHandle::thread`] on the
1084 /// * By requesting the current thread, using the [`thread::current`] function.
1086 /// The [`thread::current`] function is available even for threads not spawned
1087 /// by the APIs of this module.
1089 /// There is usually no need to create a `Thread` struct yourself, one
1090 /// should instead use a function like `spawn` to create new threads, see the
1091 /// docs of [`Builder`] and [`spawn`] for more details.
1093 /// [`Builder`]: ../../std/thread/struct.Builder.html
1094 /// [`JoinHandle::thread`]: ../../std/thread/struct.JoinHandle.html#method.thread
1095 /// [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
1096 /// [`thread::current`]: ../../std/thread/fn.current.html
1097 /// [`spawn`]: ../../std/thread/fn.spawn.html
1104 // Used only internally to construct a thread object without spawning
1105 // Panics if the name contains nuls.
1106 pub(crate) fn new(name: Option<String>) -> Thread {
1107 let cname = name.map(|n| {
1108 CString::new(n).expect("thread name may not contain interior null bytes")
1111 inner: Arc::new(Inner {
1113 id: ThreadId::new(),
1114 state: AtomicUsize::new(EMPTY),
1115 lock: Mutex::new(()),
1116 cvar: Condvar::new(),
1121 /// Atomically makes the handle's token available if it is not already.
1123 /// Every thread is equipped with some basic low-level blocking support, via
1124 /// the [`park`][park] function and the `unpark()` method. These can be
1125 /// used as a more CPU-efficient implementation of a spinlock.
1127 /// See the [park documentation][park] for more details.
1132 /// use std::thread;
1133 /// use std::time::Duration;
1135 /// let parked_thread = thread::Builder::new()
1137 /// println!("Parking thread");
1139 /// println!("Thread unparked");
1143 /// // Let some time pass for the thread to be spawned.
1144 /// thread::sleep(Duration::from_millis(10));
1146 /// println!("Unpark the thread");
1147 /// parked_thread.thread().unpark();
1149 /// parked_thread.join().unwrap();
1152 /// [park]: fn.park.html
1153 #[stable(feature = "rust1", since = "1.0.0")]
1154 pub fn unpark(&self) {
1155 // To ensure the unparked thread will observe any writes we made
1156 // before this call, we must perform a release operation that `park`
1157 // can synchronize with. To do that we must write `NOTIFIED` even if
1158 // `state` is already `NOTIFIED`. That is why this must be a swap
1159 // rather than a compare-and-swap that returns if it reads `NOTIFIED`
1161 match self.inner.state.swap(NOTIFIED, SeqCst) {
1162 EMPTY => return, // no one was waiting
1163 NOTIFIED => return, // already unparked
1164 PARKED => {} // gotta go wake someone up
1165 _ => panic!("inconsistent state in unpark"),
1168 // There is a period between when the parked thread sets `state` to
1169 // `PARKED` (or last checked `state` in the case of a spurious wake
1170 // up) and when it actually waits on `cvar`. If we were to notify
1171 // during this period it would be ignored and then when the parked
1172 // thread went to sleep it would never wake up. Fortunately, it has
1173 // `lock` locked at this stage so we can acquire `lock` to wait until
1174 // it is ready to receive the notification.
1176 // Releasing `lock` before the call to `notify_one` means that when the
1177 // parked thread wakes it doesn't get woken only to have to wait for us
1178 // to release `lock`.
1179 drop(self.inner.lock.lock().unwrap());
1180 self.inner.cvar.notify_one()
1183 /// Gets the thread's unique identifier.
1188 /// use std::thread;
1190 /// let other_thread = thread::spawn(|| {
1191 /// thread::current().id()
1194 /// let other_thread_id = other_thread.join().unwrap();
1195 /// assert!(thread::current().id() != other_thread_id);
1197 #[stable(feature = "thread_id", since = "1.19.0")]
1198 pub fn id(&self) -> ThreadId {
1202 /// Gets the thread's name.
1204 /// For more information about named threads, see
1205 /// [this module-level documentation][naming-threads].
1209 /// Threads by default have no name specified:
1212 /// use std::thread;
1214 /// let builder = thread::Builder::new();
1216 /// let handler = builder.spawn(|| {
1217 /// assert!(thread::current().name().is_none());
1220 /// handler.join().unwrap();
1223 /// Thread with a specified name:
1226 /// use std::thread;
1228 /// let builder = thread::Builder::new()
1229 /// .name("foo".into());
1231 /// let handler = builder.spawn(|| {
1232 /// assert_eq!(thread::current().name(), Some("foo"))
1235 /// handler.join().unwrap();
1238 /// [naming-threads]: ./index.html#naming-threads
1239 #[stable(feature = "rust1", since = "1.0.0")]
1240 pub fn name(&self) -> Option<&str> {
1241 self.cname().map(|s| unsafe { str::from_utf8_unchecked(s.to_bytes()) } )
1244 fn cname(&self) -> Option<&CStr> {
1245 self.inner.name.as_ref().map(|s| &**s)
1249 #[stable(feature = "rust1", since = "1.0.0")]
1250 impl fmt::Debug for Thread {
1251 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1252 fmt::Debug::fmt(&self.name(), f)
1256 ////////////////////////////////////////////////////////////////////////////////
1258 ////////////////////////////////////////////////////////////////////////////////
1260 /// A specialized [`Result`] type for threads.
1262 /// Indicates the manner in which a thread exited.
1264 /// A thread that completes without panicking is considered to exit successfully.
1269 /// use std::thread;
1272 /// fn copy_in_thread() -> thread::Result<()> {
1273 /// thread::spawn(move || { fs::copy("foo.txt", "bar.txt").unwrap(); }).join()
1277 /// match copy_in_thread() {
1278 /// Ok(_) => println!("this is fine"),
1279 /// Err(_) => println!("thread panicked"),
1284 /// [`Result`]: ../../std/result/enum.Result.html
1285 #[stable(feature = "rust1", since = "1.0.0")]
1286 pub type Result<T> = ::result::Result<T, Box<dyn Any + Send + 'static>>;
1288 // This packet is used to communicate the return value between the child thread
1289 // and the parent thread. Memory is shared through the `Arc` within and there's
1290 // no need for a mutex here because synchronization happens with `join()` (the
1291 // parent thread never reads this packet until the child has exited).
1293 // This packet itself is then stored into a `JoinInner` which in turns is placed
1294 // in `JoinHandle` and `JoinGuard`. Due to the usage of `UnsafeCell` we need to
1295 // manually worry about impls like Send and Sync. The type `T` should
1296 // already always be Send (otherwise the thread could not have been created) and
1297 // this type is inherently Sync because no methods take &self. Regardless,
1298 // however, we add inheriting impls for Send/Sync to this type to ensure it's
1299 // Send/Sync and that future modifications will still appropriately classify it.
1300 struct Packet<T>(Arc<UnsafeCell<Option<Result<T>>>>);
1302 unsafe impl<T: Send> Send for Packet<T> {}
1303 unsafe impl<T: Sync> Sync for Packet<T> {}
1305 /// Inner representation for JoinHandle
1306 struct JoinInner<T> {
1307 native: Option<imp::Thread>,
1312 impl<T> JoinInner<T> {
1313 fn join(&mut self) -> Result<T> {
1314 self.native.take().unwrap().join();
1316 (*self.packet.0.get()).take().unwrap()
1321 /// An owned permission to join on a thread (block on its termination).
1323 /// A `JoinHandle` *detaches* the associated thread when it is dropped, which
1324 /// means that there is no longer any handle to thread and no way to `join`
1327 /// Due to platform restrictions, it is not possible to [`Clone`] this
1328 /// handle: the ability to join a thread is a uniquely-owned permission.
1330 /// This `struct` is created by the [`thread::spawn`] function and the
1331 /// [`thread::Builder::spawn`] method.
1335 /// Creation from [`thread::spawn`]:
1338 /// use std::thread;
1340 /// let join_handle: thread::JoinHandle<_> = thread::spawn(|| {
1341 /// // some work here
1345 /// Creation from [`thread::Builder::spawn`]:
1348 /// use std::thread;
1350 /// let builder = thread::Builder::new();
1352 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1353 /// // some work here
1357 /// Child being detached and outliving its parent:
1360 /// use std::thread;
1361 /// use std::time::Duration;
1363 /// let original_thread = thread::spawn(|| {
1364 /// let _detached_thread = thread::spawn(|| {
1365 /// // Here we sleep to make sure that the first thread returns before.
1366 /// thread::sleep(Duration::from_millis(10));
1367 /// // This will be called, even though the JoinHandle is dropped.
1368 /// println!("♫ Still alive ♫");
1372 /// original_thread.join().expect("The thread being joined has panicked");
1373 /// println!("Original thread is joined.");
1375 /// // We make sure that the new thread has time to run, before the main
1376 /// // thread returns.
1378 /// thread::sleep(Duration::from_millis(1000));
1381 /// [`Clone`]: ../../std/clone/trait.Clone.html
1382 /// [`thread::spawn`]: fn.spawn.html
1383 /// [`thread::Builder::spawn`]: struct.Builder.html#method.spawn
1384 #[stable(feature = "rust1", since = "1.0.0")]
1385 pub struct JoinHandle<T>(JoinInner<T>);
1387 #[stable(feature = "joinhandle_impl_send_sync", since = "1.29.0")]
1388 unsafe impl<T> Send for JoinHandle<T> {}
1389 #[stable(feature = "joinhandle_impl_send_sync", since = "1.29.0")]
1390 unsafe impl<T> Sync for JoinHandle<T> {}
1392 impl<T> JoinHandle<T> {
1393 /// Extracts a handle to the underlying thread.
1398 /// use std::thread;
1400 /// let builder = thread::Builder::new();
1402 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1403 /// // some work here
1406 /// let thread = join_handle.thread();
1407 /// println!("thread id: {:?}", thread.id());
1409 #[stable(feature = "rust1", since = "1.0.0")]
1410 pub fn thread(&self) -> &Thread {
1414 /// Waits for the associated thread to finish.
1416 /// In terms of [atomic memory orderings], the completion of the associated
1417 /// thread synchronizes with this function returning. In other words, all
1418 /// operations performed by that thread are ordered before all
1419 /// operations that happen after `join` returns.
1421 /// If the child thread panics, [`Err`] is returned with the parameter given
1424 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1425 /// [`panic`]: ../../std/macro.panic.html
1426 /// [atomic memory orderings]: ../../std/sync/atomic/index.html
1430 /// This function may panic on some platforms if a thread attempts to join
1431 /// itself or otherwise may create a deadlock with joining threads.
1436 /// use std::thread;
1438 /// let builder = thread::Builder::new();
1440 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1441 /// // some work here
1443 /// join_handle.join().expect("Couldn't join on the associated thread");
1445 #[stable(feature = "rust1", since = "1.0.0")]
1446 pub fn join(mut self) -> Result<T> {
1451 impl<T> AsInner<imp::Thread> for JoinHandle<T> {
1452 fn as_inner(&self) -> &imp::Thread { self.0.native.as_ref().unwrap() }
1455 impl<T> IntoInner<imp::Thread> for JoinHandle<T> {
1456 fn into_inner(self) -> imp::Thread { self.0.native.unwrap() }
1459 #[stable(feature = "std_debug", since = "1.16.0")]
1460 impl<T> fmt::Debug for JoinHandle<T> {
1461 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1462 f.pad("JoinHandle { .. }")
1466 fn _assert_sync_and_send() {
1467 fn _assert_both<T: Send + Sync>() {}
1468 _assert_both::<JoinHandle<()>>();
1469 _assert_both::<Thread>();
1472 ////////////////////////////////////////////////////////////////////////////////
1474 ////////////////////////////////////////////////////////////////////////////////
1476 #[cfg(all(test, not(target_os = "emscripten")))]
1479 use sync::mpsc::{channel, Sender};
1481 use super::{Builder};
1486 // !!! These tests are dangerous. If something is buggy, they will hang, !!!
1487 // !!! instead of exiting cleanly. This might wedge the buildbots. !!!
1490 fn test_unnamed_thread() {
1491 thread::spawn(move|| {
1492 assert!(thread::current().name().is_none());
1493 }).join().ok().unwrap();
1497 fn test_named_thread() {
1498 Builder::new().name("ada lovelace".to_string()).spawn(move|| {
1499 assert!(thread::current().name().unwrap() == "ada lovelace".to_string());
1500 }).unwrap().join().unwrap();
1505 fn test_invalid_named_thread() {
1506 let _ = Builder::new().name("ada l\0velace".to_string()).spawn(|| {});
1510 fn test_run_basic() {
1511 let (tx, rx) = channel();
1512 thread::spawn(move|| {
1513 tx.send(()).unwrap();
1519 fn test_join_panic() {
1520 match thread::spawn(move|| {
1523 result::Result::Err(_) => (),
1524 result::Result::Ok(()) => panic!()
1529 fn test_spawn_sched() {
1530 let (tx, rx) = channel();
1532 fn f(i: i32, tx: Sender<()>) {
1533 let tx = tx.clone();
1534 thread::spawn(move|| {
1536 tx.send(()).unwrap();
1548 fn test_spawn_sched_childs_on_default_sched() {
1549 let (tx, rx) = channel();
1551 thread::spawn(move|| {
1552 thread::spawn(move|| {
1553 tx.send(()).unwrap();
1560 fn avoid_copying_the_body<F>(spawnfn: F) where F: FnOnce(Box<dyn Fn() + Send>) {
1561 let (tx, rx) = channel();
1563 let x: Box<_> = box 1;
1564 let x_in_parent = (&*x) as *const i32 as usize;
1566 spawnfn(Box::new(move|| {
1567 let x_in_child = (&*x) as *const i32 as usize;
1568 tx.send(x_in_child).unwrap();
1571 let x_in_child = rx.recv().unwrap();
1572 assert_eq!(x_in_parent, x_in_child);
1576 fn test_avoid_copying_the_body_spawn() {
1577 avoid_copying_the_body(|v| {
1578 thread::spawn(move || v());
1583 fn test_avoid_copying_the_body_thread_spawn() {
1584 avoid_copying_the_body(|f| {
1585 thread::spawn(move|| {
1592 fn test_avoid_copying_the_body_join() {
1593 avoid_copying_the_body(|f| {
1594 let _ = thread::spawn(move|| {
1601 fn test_child_doesnt_ref_parent() {
1602 // If the child refcounts the parent thread, this will stack overflow when
1603 // climbing the thread tree to dereference each ancestor. (See #1789)
1604 // (well, it would if the constant were 8000+ - I lowered it to be more
1605 // valgrind-friendly. try this at home, instead..!)
1606 const GENERATIONS: u32 = 16;
1607 fn child_no(x: u32) -> Box<dyn Fn() + Send> {
1608 return Box::new(move|| {
1609 if x < GENERATIONS {
1610 thread::spawn(move|| child_no(x+1)());
1614 thread::spawn(|| child_no(0)());
1618 fn test_simple_newsched_spawn() {
1619 thread::spawn(move || {});
1623 fn test_try_panic_message_static_str() {
1624 match thread::spawn(move|| {
1625 panic!("static string");
1628 type T = &'static str;
1629 assert!(e.is::<T>());
1630 assert_eq!(*e.downcast::<T>().unwrap(), "static string");
1637 fn test_try_panic_message_owned_str() {
1638 match thread::spawn(move|| {
1639 panic!("owned string".to_string());
1643 assert!(e.is::<T>());
1644 assert_eq!(*e.downcast::<T>().unwrap(), "owned string".to_string());
1651 fn test_try_panic_message_any() {
1652 match thread::spawn(move|| {
1653 panic!(box 413u16 as Box<dyn Any + Send>);
1656 type T = Box<dyn Any + Send>;
1657 assert!(e.is::<T>());
1658 let any = e.downcast::<T>().unwrap();
1659 assert!(any.is::<u16>());
1660 assert_eq!(*any.downcast::<u16>().unwrap(), 413);
1667 fn test_try_panic_message_unit_struct() {
1670 match thread::spawn(move|| {
1673 Err(ref e) if e.is::<Juju>() => {}
1674 Err(_) | Ok(()) => panic!()
1679 fn test_park_timeout_unpark_before() {
1681 thread::current().unpark();
1682 thread::park_timeout(Duration::from_millis(u32::MAX as u64));
1687 fn test_park_timeout_unpark_not_called() {
1689 thread::park_timeout(Duration::from_millis(10));
1694 fn test_park_timeout_unpark_called_other_thread() {
1696 let th = thread::current();
1698 let _guard = thread::spawn(move || {
1699 super::sleep(Duration::from_millis(50));
1703 thread::park_timeout(Duration::from_millis(u32::MAX as u64));
1708 fn sleep_ms_smoke() {
1709 thread::sleep(Duration::from_millis(2));
1713 fn test_thread_id_equal() {
1714 assert!(thread::current().id() == thread::current().id());
1718 fn test_thread_id_not_equal() {
1719 let spawned_id = thread::spawn(|| thread::current().id()).join().unwrap();
1720 assert!(thread::current().id() != spawned_id);
1723 // NOTE: the corresponding test for stderr is in run-pass/thread-stderr, due
1724 // to the test harness apparently interfering with stderr configuration.