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. Thread panic is unrecoverable from within
29 //! the panicking thread (i.e. there is no 'try/catch' in Rust), but
30 //! the panic may optionally be detected from a different thread. If
31 //! the main thread panics, the application will exit with a non-zero
34 //! When the main thread of a Rust program terminates, the entire program shuts
35 //! down, even if other threads are still running. However, this module provides
36 //! convenient facilities for automatically waiting for the termination of a
37 //! child thread (i.e., join).
39 //! ## Spawning a thread
41 //! A new thread can be spawned using the [`thread::spawn`][`spawn`] function:
46 //! thread::spawn(move || {
51 //! In this example, the spawned thread is "detached" from the current
52 //! thread. This means that it can outlive its parent (the thread that spawned
53 //! it), unless this parent is the main thread.
55 //! The parent thread can also wait on the completion of the child
56 //! thread; a call to [`spawn`] produces a [`JoinHandle`], which provides
57 //! a `join` method for waiting:
62 //! let child = thread::spawn(move || {
66 //! let res = child.join();
69 //! The [`join`] method returns a [`thread::Result`] containing [`Ok`] of the final
70 //! value produced by the child thread, or [`Err`] of the value given to
71 //! a call to [`panic!`] if the child panicked.
73 //! ## Configuring threads
75 //! A new thread can be configured before it is spawned via the [`Builder`] type,
76 //! which currently allows you to set the name and stack size for the child thread:
79 //! # #![allow(unused_must_use)]
82 //! thread::Builder::new().name("child1".to_string()).spawn(move || {
83 //! println!("Hello, world!");
87 //! ## The `Thread` type
89 //! Threads are represented via the [`Thread`] type, which you can get in one of
92 //! * By spawning a new thread, e.g. using the [`thread::spawn`][`spawn`]
93 //! function, and calling [`thread`][`JoinHandle::thread`] on the [`JoinHandle`].
94 //! * By requesting the current thread, using the [`thread::current`] function.
96 //! The [`thread::current`] function is available even for threads not spawned
97 //! by the APIs of this module.
99 //! ## Blocking support: park and unpark
101 //! Every thread is equipped with some basic low-level blocking support, via the
102 //! [`thread::park`][`park`] function and [`thread::Thread::unpark()`][`unpark`]
103 //! method. [`park`] blocks the current thread, which can then be resumed from
104 //! another thread by calling the [`unpark`] method on the blocked thread's handle.
106 //! Conceptually, each [`Thread`] handle has an associated token, which is
107 //! initially not present:
109 //! * The [`thread::park`][`park`] function blocks the current thread unless or until
110 //! the token is available for its thread handle, at which point it atomically
111 //! consumes the token. It may also return *spuriously*, without consuming the
112 //! token. [`thread::park_timeout`] does the same, but allows specifying a
113 //! maximum time to block the thread for.
115 //! * The [`unpark`] method on a [`Thread`] atomically makes the token available
116 //! if it wasn't already.
118 //! In other words, each [`Thread`] acts a bit like a semaphore with initial count
119 //! 0, except that the semaphore is *saturating* (the count cannot go above 1),
120 //! and can return spuriously.
122 //! The API is typically used by acquiring a handle to the current thread,
123 //! placing that handle in a shared data structure so that other threads can
124 //! find it, and then `park`ing. When some desired condition is met, another
125 //! thread calls [`unpark`] on the handle.
127 //! The motivation for this design is twofold:
129 //! * It avoids the need to allocate mutexes and condvars when building new
130 //! synchronization primitives; the threads already provide basic blocking/signaling.
132 //! * It can be implemented very efficiently on many platforms.
134 //! ## Thread-local storage
136 //! This module also provides an implementation of thread-local storage for Rust
137 //! programs. Thread-local storage is a method of storing data into a global
138 //! variable that each thread in the program will have its own copy of.
139 //! Threads do not share this data, so accesses do not need to be synchronized.
141 //! A thread-local key owns the value it contains and will destroy the value when the
142 //! thread exits. It is created with the [`thread_local!`] macro and can contain any
143 //! value that is `'static` (no borrowed pointers). It provides an accessor function,
144 //! [`with`], that yields a shared reference to the value to the specified
145 //! closure. Thread-local keys allow only shared access to values, as there would be no
146 //! way to guarantee uniqueness if mutable borrows were allowed. Most values
147 //! will want to make use of some form of **interior mutability** through the
148 //! [`Cell`] or [`RefCell`] types.
150 //! [channels]: ../../std/sync/mpsc/index.html
151 //! [`Arc`]: ../../std/sync/struct.Arc.html
152 //! [`spawn`]: ../../std/thread/fn.spawn.html
153 //! [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
154 //! [`JoinHandle::thread`]: ../../std/thread/struct.JoinHandle.html#method.thread
155 //! [`join`]: ../../std/thread/struct.JoinHandle.html#method.join
156 //! [`Result`]: ../../std/result/enum.Result.html
157 //! [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
158 //! [`Err`]: ../../std/result/enum.Result.html#variant.Err
159 //! [`panic!`]: ../../std/macro.panic.html
160 //! [`Builder`]: ../../std/thread/struct.Builder.html
161 //! [`thread::current`]: ../../std/thread/fn.current.html
162 //! [`thread::Result`]: ../../std/thread/type.Result.html
163 //! [`Thread`]: ../../std/thread/struct.Thread.html
164 //! [`park`]: ../../std/thread/fn.park.html
165 //! [`unpark`]: ../../std/thread/struct.Thread.html#method.unpark
166 //! [`thread::park_timeout`]: ../../std/thread/fn.park_timeout.html
167 //! [`Cell`]: ../cell/struct.Cell.html
168 //! [`RefCell`]: ../cell/struct.RefCell.html
169 //! [`thread_local!`]: ../macro.thread_local.html
170 //! [`with`]: struct.LocalKey.html#method.with
172 #![stable(feature = "rust1", since = "1.0.0")]
175 use cell::UnsafeCell;
176 use ffi::{CStr, CString};
182 use sync::{Mutex, Condvar, Arc};
183 use sys::thread as imp;
184 use sys_common::mutex;
185 use sys_common::thread_info;
186 use sys_common::util;
187 use sys_common::{AsInner, IntoInner};
190 ////////////////////////////////////////////////////////////////////////////////
191 // Thread-local storage
192 ////////////////////////////////////////////////////////////////////////////////
194 #[macro_use] mod local;
196 #[stable(feature = "rust1", since = "1.0.0")]
197 pub use self::local::{LocalKey, LocalKeyState};
199 // The types used by the thread_local! macro to access TLS keys. Note that there
200 // are two types, the "OS" type and the "fast" type. The OS thread local key
201 // type is accessed via platform-specific API calls and is slow, while the fast
202 // key type is accessed via code generated via LLVM, where TLS keys are set up
203 // by the elf linker. Note that the OS TLS type is always available: on macOS
204 // the standard library is compiled with support for older platform versions
205 // where fast TLS was not available; end-user code is compiled with fast TLS
206 // where available, but both are needed.
208 #[unstable(feature = "libstd_thread_internals", issue = "0")]
209 #[cfg(target_thread_local)]
210 #[doc(hidden)] pub use sys::fast_thread_local::Key as __FastLocalKeyInner;
211 #[unstable(feature = "libstd_thread_internals", issue = "0")]
212 #[doc(hidden)] pub use self::local::os::Key as __OsLocalKeyInner;
214 ////////////////////////////////////////////////////////////////////////////////
216 ////////////////////////////////////////////////////////////////////////////////
218 /// Thread configuration. Provides detailed control over the properties
219 /// and behavior of new threads.
226 /// let builder = thread::Builder::new();
228 /// let handler = builder.spawn(|| {
232 /// handler.join().unwrap();
234 #[stable(feature = "rust1", since = "1.0.0")]
237 // A name for the thread-to-be, for identification in panic messages
238 name: Option<String>,
239 // The size of the stack for the spawned thread in bytes
240 stack_size: Option<usize>,
244 /// Generates the base configuration for spawning a thread, from which
245 /// configuration methods can be chained.
247 /// If the [`stack_size`] field is not specified, the stack size
248 /// will be the `RUST_MIN_STACK` environment variable, if it is
249 /// not specified either, a sensible default size will be set (2MB as
250 /// of the writting of this doc).
257 /// let builder = thread::Builder::new()
258 /// .name("foo".into())
261 /// let handler = builder.spawn(|| {
265 /// handler.join().unwrap();
268 /// [`stack_size`]: ../../std/thread/struct.Builder.html#method.stack_size
269 #[stable(feature = "rust1", since = "1.0.0")]
270 pub fn new() -> Builder {
277 /// Names the thread-to-be. Currently the name is used for identification
278 /// only in panic messages.
285 /// let builder = thread::Builder::new()
286 /// .name("foo".into());
288 /// let handler = builder.spawn(|| {
289 /// assert_eq!(thread::current().name(), Some("foo"))
292 /// handler.join().unwrap();
294 #[stable(feature = "rust1", since = "1.0.0")]
295 pub fn name(mut self, name: String) -> Builder {
296 self.name = Some(name);
300 /// Sets the size of the stack (in bytes) for the new thread.
302 /// The actual stack size may be greater than this value if
303 /// the platform specifies minimal stack size.
310 /// let builder = thread::Builder::new().stack_size(32 * 1024);
312 #[stable(feature = "rust1", since = "1.0.0")]
313 pub fn stack_size(mut self, size: usize) -> Builder {
314 self.stack_size = Some(size);
318 /// Spawns a new thread, and returns a join handle for it.
320 /// The child thread may outlive the parent (unless the parent thread
321 /// is the main thread; the whole process is terminated when the main
322 /// thread finishes). The join handle can be used to block on
323 /// termination of the child thread, including recovering its panics.
327 /// Unlike the [`spawn`] free function, this method yields an
328 /// [`io::Result`] to capture any failure to create the thread at
331 /// [`spawn`]: ../../std/thread/fn.spawn.html
332 /// [`io::Result`]: ../../std/io/type.Result.html
339 /// let builder = thread::Builder::new();
341 /// let handler = builder.spawn(|| {
345 /// handler.join().unwrap();
347 #[stable(feature = "rust1", since = "1.0.0")]
348 pub fn spawn<F, T>(self, f: F) -> io::Result<JoinHandle<T>> where
349 F: FnOnce() -> T, F: Send + 'static, T: Send + 'static
351 let Builder { name, stack_size } = self;
353 let stack_size = stack_size.unwrap_or(util::min_stack());
355 let my_thread = Thread::new(name);
356 let their_thread = my_thread.clone();
358 let my_packet : Arc<UnsafeCell<Option<Result<T>>>>
359 = Arc::new(UnsafeCell::new(None));
360 let their_packet = my_packet.clone();
363 if let Some(name) = their_thread.cname() {
364 imp::Thread::set_name(name);
367 thread_info::set(imp::guard::current(), their_thread);
368 let try_result = panic::catch_unwind(panic::AssertUnwindSafe(f));
369 *their_packet.get() = Some(try_result);
373 Ok(JoinHandle(JoinInner {
375 Some(imp::Thread::new(stack_size, Box::new(main))?)
378 packet: Packet(my_packet),
383 ////////////////////////////////////////////////////////////////////////////////
385 ////////////////////////////////////////////////////////////////////////////////
387 /// Spawns a new thread, returning a [`JoinHandle`] for it.
389 /// The join handle will implicitly *detach* the child thread upon being
390 /// dropped. In this case, the child thread may outlive the parent (unless
391 /// the parent thread is the main thread; the whole process is terminated when
392 /// the main thread finishes). Additionally, the join handle provides a [`join`]
393 /// method that can be used to join the child thread. If the child thread
394 /// panics, [`join`] will return an [`Err`] containing the argument given to
399 /// Panics if the OS fails to create a thread; use [`Builder::spawn`]
400 /// to recover from such errors.
402 /// [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
403 /// [`join`]: ../../std/thread/struct.JoinHandle.html#method.join
404 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
405 /// [`panic`]: ../../std/macro.panic.html
406 /// [`Builder::spawn`]: ../../std/thread/struct.Builder.html#method.spawn
413 /// let handler = thread::spawn(|| {
417 /// handler.join().unwrap();
419 #[stable(feature = "rust1", since = "1.0.0")]
420 pub fn spawn<F, T>(f: F) -> JoinHandle<T> where
421 F: FnOnce() -> T, F: Send + 'static, T: Send + 'static
423 Builder::new().spawn(f).unwrap()
426 /// Gets a handle to the thread that invokes it.
430 /// Getting a handle to the current thread with `thread::current()`:
435 /// let handler = thread::Builder::new()
436 /// .name("named thread".into())
438 /// let handle = thread::current();
439 /// assert_eq!(handle.name(), Some("named thread"));
443 /// handler.join().unwrap();
445 #[stable(feature = "rust1", since = "1.0.0")]
446 pub fn current() -> Thread {
447 thread_info::current_thread().expect("use of std::thread::current() is not \
448 possible after the thread's local \
449 data has been destroyed")
452 /// Cooperatively gives up a timeslice to the OS scheduler.
459 /// thread::yield_now();
461 #[stable(feature = "rust1", since = "1.0.0")]
463 imp::Thread::yield_now()
466 /// Determines whether the current thread is unwinding because of panic.
468 /// A common use of this feature is to poison shared resources when writing
469 /// unsafe code, by checking `panicking` when the `drop` is called.
471 /// This is usually not needed when writing safe code, as [`Mutex`es][Mutex]
472 /// already poison themselves when a thread panics while holding the lock.
474 /// This can also be used in multithreaded applications, in order to send a
475 /// message to other threads warning that a thread has panicked (e.g. for
476 /// monitoring purposes).
483 /// struct SomeStruct;
485 /// impl Drop for SomeStruct {
486 /// fn drop(&mut self) {
487 /// if thread::panicking() {
488 /// println!("dropped while unwinding");
490 /// println!("dropped while not unwinding");
497 /// let a = SomeStruct;
502 /// let b = SomeStruct;
507 /// [Mutex]: ../../std/sync/struct.Mutex.html
509 #[stable(feature = "rust1", since = "1.0.0")]
510 pub fn panicking() -> bool {
511 panicking::panicking()
514 /// Puts the current thread to sleep for the specified amount of time.
516 /// The thread may sleep longer than the duration specified due to scheduling
517 /// specifics or platform-dependent functionality.
519 /// # Platform behavior
521 /// On Unix platforms this function will not return early due to a
522 /// signal being received or a spurious wakeup.
529 /// // Let's sleep for 2 seconds:
530 /// thread::sleep_ms(2000);
532 #[stable(feature = "rust1", since = "1.0.0")]
533 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::sleep`")]
534 pub fn sleep_ms(ms: u32) {
535 sleep(Duration::from_millis(ms as u64))
538 /// Puts the current thread to sleep for the specified amount of time.
540 /// The thread may sleep longer than the duration specified due to scheduling
541 /// specifics or platform-dependent functionality.
543 /// # Platform behavior
545 /// On Unix platforms this function will not return early due to a
546 /// signal being received or a spurious wakeup. Platforms which do not support
547 /// nanosecond precision for sleeping will have `dur` rounded up to the nearest
548 /// granularity of time they can sleep for.
553 /// use std::{thread, time};
555 /// let ten_millis = time::Duration::from_millis(10);
556 /// let now = time::Instant::now();
558 /// thread::sleep(ten_millis);
560 /// assert!(now.elapsed() >= ten_millis);
562 #[stable(feature = "thread_sleep", since = "1.4.0")]
563 pub fn sleep(dur: Duration) {
564 imp::Thread::sleep(dur)
567 /// Blocks unless or until the current thread's token is made available.
569 /// Every thread is equipped with some basic low-level blocking support, via
570 /// the `park()` function and the [`unpark`][unpark] method. These can be
571 /// used as a more CPU-efficient implementation of a spinlock.
573 /// [unpark]: struct.Thread.html#method.unpark
575 /// The API is typically used by acquiring a handle to the current thread,
576 /// placing that handle in a shared data structure so that other threads can
577 /// find it, and then parking (in a loop with a check for the token actually
580 /// A call to `park` does not guarantee that the thread will remain parked
581 /// forever, and callers should be prepared for this possibility.
583 /// See the [module documentation][thread] for more detail.
585 /// [thread]: index.html
587 // The implementation currently uses the trivial strategy of a Mutex+Condvar
588 // with wakeup flag, which does not actually allow spurious wakeups. In the
589 // future, this will be implemented in a more efficient way, perhaps along the lines of
590 // http://cr.openjdk.java.net/~stefank/6989984.1/raw_files/new/src/os/linux/vm/os_linux.cpp
591 // or futuxes, and in either case may allow spurious wakeups.
592 #[stable(feature = "rust1", since = "1.0.0")]
594 let thread = current();
595 let mut guard = thread.inner.lock.lock().unwrap();
597 guard = thread.inner.cvar.wait(guard).unwrap();
602 /// Use [park_timeout].
604 /// Blocks unless or until the current thread's token is made available or
605 /// the specified duration has been reached (may wake spuriously).
607 /// The semantics of this function are equivalent to `park()` except that the
608 /// thread will be blocked for roughly no longer than `ms`. This method
609 /// should not be used for precise timing due to anomalies such as
610 /// preemption or platform differences that may not cause the maximum
611 /// amount of time waited to be precisely `ms` long.
613 /// See the [module documentation][thread] for more detail.
615 /// [thread]: index.html
616 /// [park_timeout]: fn.park_timeout.html
617 #[stable(feature = "rust1", since = "1.0.0")]
618 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::park_timeout`")]
619 pub fn park_timeout_ms(ms: u32) {
620 park_timeout(Duration::from_millis(ms as u64))
623 /// Blocks unless or until the current thread's token is made available or
624 /// the specified duration has been reached (may wake spuriously).
626 /// The semantics of this function are equivalent to `park()` except that the
627 /// thread will be blocked for roughly no longer than `dur`. This method
628 /// should not be used for precise timing due to anomalies such as
629 /// preemption or platform differences that may not cause the maximum
630 /// amount of time waited to be precisely `dur` long.
632 /// See the module doc for more detail.
634 /// # Platform behavior
636 /// Platforms which do not support nanosecond precision for sleeping will have
637 /// `dur` rounded up to the nearest granularity of time they can sleep for.
641 /// Waiting for the complete expiration of the timeout:
644 /// use std::thread::park_timeout;
645 /// use std::time::{Instant, Duration};
647 /// let timeout = Duration::from_secs(2);
648 /// let beginning_park = Instant::now();
649 /// park_timeout(timeout);
651 /// while beginning_park.elapsed() < timeout {
652 /// println!("restarting park_timeout after {:?}", beginning_park.elapsed());
653 /// let timeout = timeout - beginning_park.elapsed();
654 /// park_timeout(timeout);
657 #[stable(feature = "park_timeout", since = "1.4.0")]
658 pub fn park_timeout(dur: Duration) {
659 let thread = current();
660 let mut guard = thread.inner.lock.lock().unwrap();
662 let (g, _) = thread.inner.cvar.wait_timeout(guard, dur).unwrap();
668 ////////////////////////////////////////////////////////////////////////////////
670 ////////////////////////////////////////////////////////////////////////////////
672 /// A unique identifier for a running thread.
674 /// A `ThreadId` is an opaque object that has a unique value for each thread
675 /// that creates one. `ThreadId`s are not guaranteed to correspond to a thread's
676 /// system-designated identifier.
681 /// #![feature(thread_id)]
685 /// let other_thread = thread::spawn(|| {
686 /// thread::current().id()
689 /// let other_thread_id = other_thread.join().unwrap();
690 /// assert!(thread::current().id() != other_thread_id);
692 #[unstable(feature = "thread_id", issue = "21507")]
693 #[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
694 pub struct ThreadId(u64);
697 // Generate a new unique thread ID.
698 fn new() -> ThreadId {
699 static GUARD: mutex::Mutex = mutex::Mutex::new();
700 static mut COUNTER: u64 = 0;
705 // If we somehow use up all our bits, panic so that we're not
706 // covering up subtle bugs of IDs being reused.
707 if COUNTER == ::u64::MAX {
709 panic!("failed to generate unique thread ID: bitspace exhausted");
722 ////////////////////////////////////////////////////////////////////////////////
724 ////////////////////////////////////////////////////////////////////////////////
726 /// The internal representation of a `Thread` handle
728 name: Option<CString>, // Guaranteed to be UTF-8
730 lock: Mutex<bool>, // true when there is a buffered unpark
735 #[stable(feature = "rust1", since = "1.0.0")]
736 /// A handle to a thread.
738 /// Threads are represented via the `Thread` type, which you can get in one of
741 /// * By spawning a new thread, e.g. using the [`thread::spawn`][`spawn`]
742 /// function, and calling [`thread`][`JoinHandle::thread`] on the
744 /// * By requesting the current thread, using the [`thread::current`] function.
746 /// The [`thread::current`] function is available even for threads not spawned
747 /// by the APIs of this module.
749 /// There is usualy no need to create a `Thread` struct yourself, one
750 /// should instead use a function like `spawn` to create new threads, see the
751 /// docs of [`Builder`] and [`spawn`] for more details.
753 /// [`Builder`]: ../../std/thread/struct.Builder.html
754 /// [`spawn`]: ../../std/thread/fn.spawn.html
761 // Used only internally to construct a thread object without spawning
762 pub(crate) fn new(name: Option<String>) -> Thread {
763 let cname = name.map(|n| {
764 CString::new(n).expect("thread name may not contain interior null bytes")
767 inner: Arc::new(Inner {
770 lock: Mutex::new(false),
771 cvar: Condvar::new(),
776 /// Atomically makes the handle's token available if it is not already.
778 /// See the module doc for more detail.
785 /// let handler = thread::Builder::new()
787 /// let thread = thread::current();
792 /// handler.join().unwrap();
794 #[stable(feature = "rust1", since = "1.0.0")]
795 pub fn unpark(&self) {
796 let mut guard = self.inner.lock.lock().unwrap();
799 self.inner.cvar.notify_one();
803 /// Gets the thread's unique identifier.
808 /// #![feature(thread_id)]
812 /// let other_thread = thread::spawn(|| {
813 /// thread::current().id()
816 /// let other_thread_id = other_thread.join().unwrap();
817 /// assert!(thread::current().id() != other_thread_id);
819 #[unstable(feature = "thread_id", issue = "21507")]
820 pub fn id(&self) -> ThreadId {
824 /// Gets the thread's name.
828 /// Threads by default have no name specified:
833 /// let builder = thread::Builder::new();
835 /// let handler = builder.spawn(|| {
836 /// assert!(thread::current().name().is_none());
839 /// handler.join().unwrap();
842 /// Thread with a specified name:
847 /// let builder = thread::Builder::new()
848 /// .name("foo".into());
850 /// let handler = builder.spawn(|| {
851 /// assert_eq!(thread::current().name(), Some("foo"))
854 /// handler.join().unwrap();
856 #[stable(feature = "rust1", since = "1.0.0")]
857 pub fn name(&self) -> Option<&str> {
858 self.cname().map(|s| unsafe { str::from_utf8_unchecked(s.to_bytes()) } )
861 fn cname(&self) -> Option<&CStr> {
862 self.inner.name.as_ref().map(|s| &**s)
866 #[stable(feature = "rust1", since = "1.0.0")]
867 impl fmt::Debug for Thread {
868 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
869 fmt::Debug::fmt(&self.name(), f)
873 ////////////////////////////////////////////////////////////////////////////////
875 ////////////////////////////////////////////////////////////////////////////////
877 /// A specialized [`Result`] type for threads.
879 /// Indicates the manner in which a thread exited.
881 /// A thread that completes without panicking is considered to exit successfully.
889 /// fn copy_in_thread() -> thread::Result<()> {
890 /// thread::spawn(move || { fs::copy("foo.txt", "bar.txt").unwrap(); }).join()
894 /// match copy_in_thread() {
895 /// Ok(_) => println!("this is fine"),
896 /// Err(_) => println!("thread panicked"),
901 /// [`Result`]: ../../std/result/enum.Result.html
902 #[stable(feature = "rust1", since = "1.0.0")]
903 pub type Result<T> = ::result::Result<T, Box<Any + Send + 'static>>;
905 // This packet is used to communicate the return value between the child thread
906 // and the parent thread. Memory is shared through the `Arc` within and there's
907 // no need for a mutex here because synchronization happens with `join()` (the
908 // parent thread never reads this packet until the child has exited).
910 // This packet itself is then stored into a `JoinInner` which in turns is placed
911 // in `JoinHandle` and `JoinGuard`. Due to the usage of `UnsafeCell` we need to
912 // manually worry about impls like Send and Sync. The type `T` should
913 // already always be Send (otherwise the thread could not have been created) and
914 // this type is inherently Sync because no methods take &self. Regardless,
915 // however, we add inheriting impls for Send/Sync to this type to ensure it's
916 // Send/Sync and that future modifications will still appropriately classify it.
917 struct Packet<T>(Arc<UnsafeCell<Option<Result<T>>>>);
919 unsafe impl<T: Send> Send for Packet<T> {}
920 unsafe impl<T: Sync> Sync for Packet<T> {}
922 /// Inner representation for JoinHandle
923 struct JoinInner<T> {
924 native: Option<imp::Thread>,
929 impl<T> JoinInner<T> {
930 fn join(&mut self) -> Result<T> {
931 self.native.take().unwrap().join();
933 (*self.packet.0.get()).take().unwrap()
938 /// An owned permission to join on a thread (block on its termination).
940 /// A `JoinHandle` *detaches* the child thread when it is dropped.
942 /// Due to platform restrictions, it is not possible to [`Clone`] this
943 /// handle: the ability to join a child thread is a uniquely-owned
946 /// This `struct` is created by the [`thread::spawn`] function and the
947 /// [`thread::Builder::spawn`] method.
951 /// Creation from [`thread::spawn`]:
956 /// let join_handle: thread::JoinHandle<_> = thread::spawn(|| {
957 /// // some work here
961 /// Creation from [`thread::Builder::spawn`]:
966 /// let builder = thread::Builder::new();
968 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
969 /// // some work here
973 /// [`Clone`]: ../../std/clone/trait.Clone.html
974 /// [`thread::spawn`]: fn.spawn.html
975 /// [`thread::Builder::spawn`]: struct.Builder.html#method.spawn
976 #[stable(feature = "rust1", since = "1.0.0")]
977 pub struct JoinHandle<T>(JoinInner<T>);
979 impl<T> JoinHandle<T> {
980 /// Extracts a handle to the underlying thread.
985 /// #![feature(thread_id)]
989 /// let builder = thread::Builder::new();
991 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
992 /// // some work here
995 /// let thread = join_handle.thread();
996 /// println!("thread id: {:?}", thread.id());
998 #[stable(feature = "rust1", since = "1.0.0")]
999 pub fn thread(&self) -> &Thread {
1003 /// Waits for the associated thread to finish.
1005 /// If the child thread panics, [`Err`] is returned with the parameter given
1008 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1009 /// [`panic`]: ../../std/macro.panic.html
1014 /// use std::thread;
1016 /// let builder = thread::Builder::new();
1018 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1019 /// // some work here
1021 /// join_handle.join().expect("Couldn't join on the associated thread");
1023 #[stable(feature = "rust1", since = "1.0.0")]
1024 pub fn join(mut self) -> Result<T> {
1029 impl<T> AsInner<imp::Thread> for JoinHandle<T> {
1030 fn as_inner(&self) -> &imp::Thread { self.0.native.as_ref().unwrap() }
1033 impl<T> IntoInner<imp::Thread> for JoinHandle<T> {
1034 fn into_inner(self) -> imp::Thread { self.0.native.unwrap() }
1037 #[stable(feature = "std_debug", since = "1.16.0")]
1038 impl<T> fmt::Debug for JoinHandle<T> {
1039 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1040 f.pad("JoinHandle { .. }")
1044 fn _assert_sync_and_send() {
1045 fn _assert_both<T: Send + Sync>() {}
1046 _assert_both::<JoinHandle<()>>();
1047 _assert_both::<Thread>();
1050 ////////////////////////////////////////////////////////////////////////////////
1052 ////////////////////////////////////////////////////////////////////////////////
1054 #[cfg(all(test, not(target_os = "emscripten")))]
1057 use sync::mpsc::{channel, Sender};
1059 use super::{Builder};
1064 // !!! These tests are dangerous. If something is buggy, they will hang, !!!
1065 // !!! instead of exiting cleanly. This might wedge the buildbots. !!!
1068 fn test_unnamed_thread() {
1069 thread::spawn(move|| {
1070 assert!(thread::current().name().is_none());
1071 }).join().ok().unwrap();
1075 fn test_named_thread() {
1076 Builder::new().name("ada lovelace".to_string()).spawn(move|| {
1077 assert!(thread::current().name().unwrap() == "ada lovelace".to_string());
1078 }).unwrap().join().unwrap();
1083 fn test_invalid_named_thread() {
1084 let _ = Builder::new().name("ada l\0velace".to_string()).spawn(|| {});
1088 fn test_run_basic() {
1089 let (tx, rx) = channel();
1090 thread::spawn(move|| {
1091 tx.send(()).unwrap();
1097 fn test_join_panic() {
1098 match thread::spawn(move|| {
1101 result::Result::Err(_) => (),
1102 result::Result::Ok(()) => panic!()
1107 fn test_spawn_sched() {
1108 let (tx, rx) = channel();
1110 fn f(i: i32, tx: Sender<()>) {
1111 let tx = tx.clone();
1112 thread::spawn(move|| {
1114 tx.send(()).unwrap();
1126 fn test_spawn_sched_childs_on_default_sched() {
1127 let (tx, rx) = channel();
1129 thread::spawn(move|| {
1130 thread::spawn(move|| {
1131 tx.send(()).unwrap();
1138 fn avoid_copying_the_body<F>(spawnfn: F) where F: FnOnce(Box<Fn() + Send>) {
1139 let (tx, rx) = channel();
1141 let x: Box<_> = box 1;
1142 let x_in_parent = (&*x) as *const i32 as usize;
1144 spawnfn(Box::new(move|| {
1145 let x_in_child = (&*x) as *const i32 as usize;
1146 tx.send(x_in_child).unwrap();
1149 let x_in_child = rx.recv().unwrap();
1150 assert_eq!(x_in_parent, x_in_child);
1154 fn test_avoid_copying_the_body_spawn() {
1155 avoid_copying_the_body(|v| {
1156 thread::spawn(move || v());
1161 fn test_avoid_copying_the_body_thread_spawn() {
1162 avoid_copying_the_body(|f| {
1163 thread::spawn(move|| {
1170 fn test_avoid_copying_the_body_join() {
1171 avoid_copying_the_body(|f| {
1172 let _ = thread::spawn(move|| {
1179 fn test_child_doesnt_ref_parent() {
1180 // If the child refcounts the parent thread, this will stack overflow when
1181 // climbing the thread tree to dereference each ancestor. (See #1789)
1182 // (well, it would if the constant were 8000+ - I lowered it to be more
1183 // valgrind-friendly. try this at home, instead..!)
1184 const GENERATIONS: u32 = 16;
1185 fn child_no(x: u32) -> Box<Fn() + Send> {
1186 return Box::new(move|| {
1187 if x < GENERATIONS {
1188 thread::spawn(move|| child_no(x+1)());
1192 thread::spawn(|| child_no(0)());
1196 fn test_simple_newsched_spawn() {
1197 thread::spawn(move || {});
1201 fn test_try_panic_message_static_str() {
1202 match thread::spawn(move|| {
1203 panic!("static string");
1206 type T = &'static str;
1207 assert!(e.is::<T>());
1208 assert_eq!(*e.downcast::<T>().unwrap(), "static string");
1215 fn test_try_panic_message_owned_str() {
1216 match thread::spawn(move|| {
1217 panic!("owned string".to_string());
1221 assert!(e.is::<T>());
1222 assert_eq!(*e.downcast::<T>().unwrap(), "owned string".to_string());
1229 fn test_try_panic_message_any() {
1230 match thread::spawn(move|| {
1231 panic!(box 413u16 as Box<Any + Send>);
1234 type T = Box<Any + Send>;
1235 assert!(e.is::<T>());
1236 let any = e.downcast::<T>().unwrap();
1237 assert!(any.is::<u16>());
1238 assert_eq!(*any.downcast::<u16>().unwrap(), 413);
1245 fn test_try_panic_message_unit_struct() {
1248 match thread::spawn(move|| {
1251 Err(ref e) if e.is::<Juju>() => {}
1252 Err(_) | Ok(()) => panic!()
1257 fn test_park_timeout_unpark_before() {
1259 thread::current().unpark();
1260 thread::park_timeout(Duration::from_millis(u32::MAX as u64));
1265 fn test_park_timeout_unpark_not_called() {
1267 thread::park_timeout(Duration::from_millis(10));
1272 fn test_park_timeout_unpark_called_other_thread() {
1274 let th = thread::current();
1276 let _guard = thread::spawn(move || {
1277 super::sleep(Duration::from_millis(50));
1281 thread::park_timeout(Duration::from_millis(u32::MAX as u64));
1286 fn sleep_ms_smoke() {
1287 thread::sleep(Duration::from_millis(2));
1291 fn test_thread_id_equal() {
1292 assert!(thread::current().id() == thread::current().id());
1296 fn test_thread_id_not_equal() {
1297 let spawned_id = thread::spawn(|| thread::current().id()).join().unwrap();
1298 assert!(thread::current().id() != spawned_id);
1301 // NOTE: the corresponding test for stderr is in run-pass/thread-stderr, due
1302 // to the test harness apparently interfering with stderr configuration.