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 //! ## Thread-local storage
101 //! This module also provides an implementation of thread-local storage for Rust
102 //! programs. Thread-local storage is a method of storing data into a global
103 //! variable that each thread in the program will have its own copy of.
104 //! Threads do not share this data, so accesses do not need to be synchronized.
106 //! A thread-local key owns the value it contains and will destroy the value when the
107 //! thread exits. It is created with the [`thread_local!`] macro and can contain any
108 //! value that is `'static` (no borrowed pointers). It provides an accessor function,
109 //! [`with`], that yields a shared reference to the value to the specified
110 //! closure. Thread-local keys allow only shared access to values, as there would be no
111 //! way to guarantee uniqueness if mutable borrows were allowed. Most values
112 //! will want to make use of some form of **interior mutability** through the
113 //! [`Cell`] or [`RefCell`] types.
115 //! [channels]: ../../std/sync/mpsc/index.html
116 //! [`Arc`]: ../../std/sync/struct.Arc.html
117 //! [`spawn`]: ../../std/thread/fn.spawn.html
118 //! [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
119 //! [`JoinHandle::thread`]: ../../std/thread/struct.JoinHandle.html#method.thread
120 //! [`join`]: ../../std/thread/struct.JoinHandle.html#method.join
121 //! [`Result`]: ../../std/result/enum.Result.html
122 //! [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
123 //! [`Err`]: ../../std/result/enum.Result.html#variant.Err
124 //! [`panic!`]: ../../std/macro.panic.html
125 //! [`Builder`]: ../../std/thread/struct.Builder.html
126 //! [`thread::current`]: ../../std/thread/fn.current.html
127 //! [`thread::Result`]: ../../std/thread/type.Result.html
128 //! [`Thread`]: ../../std/thread/struct.Thread.html
129 //! [`park`]: ../../std/thread/fn.park.html
130 //! [`unpark`]: ../../std/thread/struct.Thread.html#method.unpark
131 //! [`thread::park_timeout`]: ../../std/thread/fn.park_timeout.html
132 //! [`Cell`]: ../cell/struct.Cell.html
133 //! [`RefCell`]: ../cell/struct.RefCell.html
134 //! [`thread_local!`]: ../macro.thread_local.html
135 //! [`with`]: struct.LocalKey.html#method.with
137 #![stable(feature = "rust1", since = "1.0.0")]
140 use cell::UnsafeCell;
141 use ffi::{CStr, CString};
147 use sync::{Mutex, Condvar, Arc};
148 use sys::thread as imp;
149 use sys_common::mutex;
150 use sys_common::thread_info;
151 use sys_common::util;
152 use sys_common::{AsInner, IntoInner};
155 ////////////////////////////////////////////////////////////////////////////////
156 // Thread-local storage
157 ////////////////////////////////////////////////////////////////////////////////
159 #[macro_use] mod local;
161 #[stable(feature = "rust1", since = "1.0.0")]
162 pub use self::local::{LocalKey, LocalKeyState};
164 // The types used by the thread_local! macro to access TLS keys. Note that there
165 // are two types, the "OS" type and the "fast" type. The OS thread local key
166 // type is accessed via platform-specific API calls and is slow, while the fast
167 // key type is accessed via code generated via LLVM, where TLS keys are set up
168 // by the elf linker. Note that the OS TLS type is always available: on macOS
169 // the standard library is compiled with support for older platform versions
170 // where fast TLS was not available; end-user code is compiled with fast TLS
171 // where available, but both are needed.
173 #[unstable(feature = "libstd_thread_internals", issue = "0")]
174 #[cfg(target_thread_local)]
175 #[doc(hidden)] pub use sys::fast_thread_local::Key as __FastLocalKeyInner;
176 #[unstable(feature = "libstd_thread_internals", issue = "0")]
177 #[doc(hidden)] pub use self::local::os::Key as __OsLocalKeyInner;
179 ////////////////////////////////////////////////////////////////////////////////
181 ////////////////////////////////////////////////////////////////////////////////
183 /// Thread factory, which can be used in order to configure the properties of
186 /// Methods can be chained on it in order to configure it.
188 /// The two configurations available are:
190 /// - [`name`]: allows to give a name to the thread which is currently
191 /// only used in `panic` messages.
192 /// - [`stack_size`]: specifies the desired stack size. Note that this can
193 /// be overriden by the OS.
195 /// If the [`stack_size`] field is not specified, the stack size
196 /// will be the `RUST_MIN_STACK` environment variable. If it is
197 /// not specified either, a sensible default will be set.
199 /// If the [`name`] field is not specified, the thread will not be named.
201 /// The [`spawn`] method will take ownership of the builder and create an
202 /// [`io::Result`] to the thread handle with the given configuration.
204 /// The [`thread::spawn`] free function uses a `Builder` with default
205 /// configuration and [`unwrap`]s its return value.
207 /// You may want to use [`spawn`] instead of [`thread::spawn`], when you want
208 /// to recover from a failure to launch a thread, indeed the free function will
209 /// panick where the `Builder` method will return a [`io::Result`].
216 /// let builder = thread::Builder::new();
218 /// let handler = builder.spawn(|| {
222 /// handler.join().unwrap();
225 /// [`thread::spawn`]: ../../std/thread/fn.spawn.html
226 /// [`stack_size`]: ../../std/thread/struct.Builder.html#method.stack_size
227 /// [`name`]: ../../std/thread/struct.Builder.html#method.name
228 /// [`spawn`]: ../../std/thread/struct.Builder.html#method.spawn
229 /// [`io::Result`]: ../../std/io/type.Result.html
230 /// [`unwrap`]: ../../std/result/enum.Result.html#method.unwrap
231 #[stable(feature = "rust1", since = "1.0.0")]
234 // A name for the thread-to-be, for identification in panic messages
235 name: Option<String>,
236 // The size of the stack for the spawned thread in bytes
237 stack_size: Option<usize>,
241 /// Generates the base configuration for spawning a thread, from which
242 /// configuration methods can be chained.
249 /// let builder = thread::Builder::new()
250 /// .name("foo".into())
253 /// let handler = builder.spawn(|| {
257 /// handler.join().unwrap();
259 #[stable(feature = "rust1", since = "1.0.0")]
260 pub fn new() -> Builder {
267 /// Names the thread-to-be. Currently the name is used for identification
268 /// only in panic messages.
275 /// let builder = thread::Builder::new()
276 /// .name("foo".into());
278 /// let handler = builder.spawn(|| {
279 /// assert_eq!(thread::current().name(), Some("foo"))
282 /// handler.join().unwrap();
284 #[stable(feature = "rust1", since = "1.0.0")]
285 pub fn name(mut self, name: String) -> Builder {
286 self.name = Some(name);
290 /// Sets the size of the stack (in bytes) for the new thread.
292 /// The actual stack size may be greater than this value if
293 /// the platform specifies minimal stack size.
300 /// let builder = thread::Builder::new().stack_size(32 * 1024);
302 #[stable(feature = "rust1", since = "1.0.0")]
303 pub fn stack_size(mut self, size: usize) -> Builder {
304 self.stack_size = Some(size);
308 /// Spawns a new thread by taking ownership of the `Builder`, and returns an
309 /// [`io::Result`] to its [`JoinHandle`].
311 /// The spawned thread may outlive the caller (unless the caller thread
312 /// is the main thread; the whole process is terminated when the main
313 /// thread finishes). The join handle can be used to block on
314 /// termination of the child thread, including recovering its panics.
316 /// For a more complete documentation see [`thread::spawn`][`spawn`].
320 /// Unlike the [`spawn`] free function, this method yields an
321 /// [`io::Result`] to capture any failure to create the thread at
324 /// [`spawn`]: ../../std/thread/fn.spawn.html
325 /// [`io::Result`]: ../../std/io/type.Result.html
326 /// [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
333 /// let builder = thread::Builder::new();
335 /// let handler = builder.spawn(|| {
339 /// handler.join().unwrap();
341 #[stable(feature = "rust1", since = "1.0.0")]
342 pub fn spawn<F, T>(self, f: F) -> io::Result<JoinHandle<T>> where
343 F: FnOnce() -> T, F: Send + 'static, T: Send + 'static
345 let Builder { name, stack_size } = self;
347 let stack_size = stack_size.unwrap_or(util::min_stack());
349 let my_thread = Thread::new(name);
350 let their_thread = my_thread.clone();
352 let my_packet : Arc<UnsafeCell<Option<Result<T>>>>
353 = Arc::new(UnsafeCell::new(None));
354 let their_packet = my_packet.clone();
357 if let Some(name) = their_thread.cname() {
358 imp::Thread::set_name(name);
361 thread_info::set(imp::guard::current(), their_thread);
362 let try_result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
363 ::sys_common::backtrace::__rust_begin_short_backtrace(f)
365 *their_packet.get() = Some(try_result);
369 Ok(JoinHandle(JoinInner {
371 Some(imp::Thread::new(stack_size, Box::new(main))?)
374 packet: Packet(my_packet),
379 ////////////////////////////////////////////////////////////////////////////////
381 ////////////////////////////////////////////////////////////////////////////////
383 /// Spawns a new thread, returning a [`JoinHandle`] for it.
385 /// The join handle will implicitly *detach* the child thread upon being
386 /// dropped. In this case, the child thread may outlive the parent (unless
387 /// the parent thread is the main thread; the whole process is terminated when
388 /// the main thread finishes). Additionally, the join handle provides a [`join`]
389 /// method that can be used to join the child thread. If the child thread
390 /// panics, [`join`] will return an [`Err`] containing the argument given to
393 /// This will create a thread using default parameters of [`Builder`], if you
394 /// want to specify the stack size or the name of the thread, use this API
399 /// Panics if the OS fails to create a thread; use [`Builder::spawn`]
400 /// to recover from such errors.
404 /// Creating a thread.
409 /// let handler = thread::spawn(|| {
413 /// handler.join().unwrap();
416 /// As mentioned in the module documentation, threads are usually made to
417 /// communicate using [`channels`], here is how it usually looks.
419 /// This example also shows how to use `move`, in order to give ownership
420 /// of values to a thread.
424 /// use std::sync::mpsc::channel;
426 /// let (tx, rx) = channel();
428 /// let sender = thread::spawn(move || {
429 /// let _ = tx.send("Hello, thread".to_owned());
432 /// let receiver = thread::spawn(move || {
433 /// println!("{}", rx.recv().unwrap());
436 /// let _ = sender.join();
437 /// let _ = receiver.join();
440 /// A thread can also return a value through its [`JoinHandle`], you can use
441 /// this to make asynchronous computations (futures might be more appropriate
447 /// let computation = thread::spawn(|| {
448 /// // Some expensive computation.
452 /// let result = computation.join().unwrap();
453 /// println!("{}", result);
456 /// [`channels`]: ../../std/sync/mpsc/index.html
457 /// [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
458 /// [`join`]: ../../std/thread/struct.JoinHandle.html#method.join
459 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
460 /// [`panic`]: ../../std/macro.panic.html
461 /// [`Builder::spawn`]: ../../std/thread/struct.Builder.html#method.spawn
462 /// [`Builder`]: ../../std/thread/struct.Builder.html
463 #[stable(feature = "rust1", since = "1.0.0")]
464 pub fn spawn<F, T>(f: F) -> JoinHandle<T> where
465 F: FnOnce() -> T, F: Send + 'static, T: Send + 'static
467 Builder::new().spawn(f).unwrap()
470 /// Gets a handle to the thread that invokes it.
474 /// Getting a handle to the current thread with `thread::current()`:
479 /// let handler = thread::Builder::new()
480 /// .name("named thread".into())
482 /// let handle = thread::current();
483 /// assert_eq!(handle.name(), Some("named thread"));
487 /// handler.join().unwrap();
489 #[stable(feature = "rust1", since = "1.0.0")]
490 pub fn current() -> Thread {
491 thread_info::current_thread().expect("use of std::thread::current() is not \
492 possible after the thread's local \
493 data has been destroyed")
496 /// Cooperatively gives up a timeslice to the OS scheduler.
498 /// This is used when the programmer knows that the thread will have nothing
499 /// to do for some time, and thus avoid wasting computing time.
501 /// For example when polling on a resource, it is common to check that it is
502 /// available, and if not to yield in order to avoid busy waiting.
504 /// Thus the pattern of `yield`ing after a failed poll is rather common when
505 /// implementing low-level shared resources or synchronization primitives.
507 /// However programmers will usualy prefer to use, [`channel`]s, [`Condvar`]s,
508 /// [`Mutex`]es or [`join`] for their synchronisation routines, as they avoid
509 /// thinking about thread schedulling.
511 /// Note that [`channel`]s for example are implemented using this primitive.
512 /// Indeed when you call `send` or `recv`, which are blocking, they will yield
513 /// if the channel is not available.
520 /// thread::yield_now();
523 /// [`channel`]: ../../std/sync/mpsc/index.html
524 /// [`spawn`]: ../../std/thread/fn.spawn.html
525 /// [`join`]: ../../std/thread/struct.JoinHandle.html#method.join
526 /// [`Mutex`]: ../../std/sync/struct.Mutex.html
527 /// [`Condvar`]: ../../std/sync/struct.Condvar.html
528 #[stable(feature = "rust1", since = "1.0.0")]
530 imp::Thread::yield_now()
533 /// Determines whether the current thread is unwinding because of panic.
535 /// A common use of this feature is to poison shared resources when writing
536 /// unsafe code, by checking `panicking` when the `drop` is called.
538 /// This is usually not needed when writing safe code, as [`Mutex`es][Mutex]
539 /// already poison themselves when a thread panics while holding the lock.
541 /// This can also be used in multithreaded applications, in order to send a
542 /// message to other threads warning that a thread has panicked (e.g. for
543 /// monitoring purposes).
550 /// struct SomeStruct;
552 /// impl Drop for SomeStruct {
553 /// fn drop(&mut self) {
554 /// if thread::panicking() {
555 /// println!("dropped while unwinding");
557 /// println!("dropped while not unwinding");
564 /// let a = SomeStruct;
569 /// let b = SomeStruct;
574 /// [Mutex]: ../../std/sync/struct.Mutex.html
576 #[stable(feature = "rust1", since = "1.0.0")]
577 pub fn panicking() -> bool {
578 panicking::panicking()
581 /// Puts the current thread to sleep for the specified amount of time.
583 /// The thread may sleep longer than the duration specified due to scheduling
584 /// specifics or platform-dependent functionality.
586 /// # Platform behavior
588 /// On Unix platforms this function will not return early due to a
589 /// signal being received or a spurious wakeup.
596 /// // Let's sleep for 2 seconds:
597 /// thread::sleep_ms(2000);
599 #[stable(feature = "rust1", since = "1.0.0")]
600 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::sleep`")]
601 pub fn sleep_ms(ms: u32) {
602 sleep(Duration::from_millis(ms as u64))
605 /// Puts the current thread to sleep for the specified amount of time.
607 /// The thread may sleep longer than the duration specified due to scheduling
608 /// specifics or platform-dependent functionality.
610 /// # Platform behavior
612 /// On Unix platforms this function will not return early due to a
613 /// signal being received or a spurious wakeup. Platforms which do not support
614 /// nanosecond precision for sleeping will have `dur` rounded up to the nearest
615 /// granularity of time they can sleep for.
620 /// use std::{thread, time};
622 /// let ten_millis = time::Duration::from_millis(10);
623 /// let now = time::Instant::now();
625 /// thread::sleep(ten_millis);
627 /// assert!(now.elapsed() >= ten_millis);
629 #[stable(feature = "thread_sleep", since = "1.4.0")]
630 pub fn sleep(dur: Duration) {
631 imp::Thread::sleep(dur)
634 /// Blocks unless or until the current thread's token is made available.
636 /// A call to `park` does not guarantee that the thread will remain parked
637 /// forever, and callers should be prepared for this possibility.
639 /// # park and unpark
641 /// Every thread is equipped with some basic low-level blocking support, via the
642 /// [`thread::park`][`park`] function and [`thread::Thread::unpark`][`unpark`]
643 /// method. [`park`] blocks the current thread, which can then be resumed from
644 /// another thread by calling the [`unpark`] method on the blocked thread's
647 /// Conceptually, each [`Thread`] handle has an associated token, which is
648 /// initially not present:
650 /// * The [`thread::park`][`park`] function blocks the current thread unless or
651 /// until the token is available for its thread handle, at which point it
652 /// atomically consumes the token. It may also return *spuriously*, without
653 /// consuming the token. [`thread::park_timeout`] does the same, but allows
654 /// specifying a maximum time to block the thread for.
656 /// * The [`unpark`] method on a [`Thread`] atomically makes the token available
657 /// if it wasn't already.
659 /// In other words, each [`Thread`] acts a bit like a spinlock that can be
660 /// locked and unlocked using `park` and `unpark`.
662 /// The API is typically used by acquiring a handle to the current thread,
663 /// placing that handle in a shared data structure so that other threads can
664 /// find it, and then `park`ing. When some desired condition is met, another
665 /// thread calls [`unpark`] on the handle.
667 /// The motivation for this design is twofold:
669 /// * It avoids the need to allocate mutexes and condvars when building new
670 /// synchronization primitives; the threads already provide basic
671 /// blocking/signaling.
673 /// * It can be implemented very efficiently on many platforms.
679 /// use std::time::Duration;
681 /// let parked_thread = thread::Builder::new()
683 /// println!("Parking thread");
685 /// println!("Thread unparked");
689 /// // Let some time pass for the thread to be spawned.
690 /// thread::sleep(Duration::from_millis(10));
692 /// println!("Unpark the thread");
693 /// parked_thread.thread().unpark();
695 /// parked_thread.join().unwrap();
698 /// [`Thread`]: ../../std/thread/struct.Thread.html
699 /// [`park`]: ../../std/thread/fn.park.html
700 /// [`unpark`]: ../../std/thread/struct.Thread.html#method.unpark
701 /// [`thread::park_timeout`]: ../../std/thread/fn.park_timeout.html
703 // The implementation currently uses the trivial strategy of a Mutex+Condvar
704 // with wakeup flag, which does not actually allow spurious wakeups. In the
705 // future, this will be implemented in a more efficient way, perhaps along the lines of
706 // http://cr.openjdk.java.net/~stefank/6989984.1/raw_files/new/src/os/linux/vm/os_linux.cpp
707 // or futuxes, and in either case may allow spurious wakeups.
708 #[stable(feature = "rust1", since = "1.0.0")]
710 let thread = current();
711 let mut guard = thread.inner.lock.lock().unwrap();
713 guard = thread.inner.cvar.wait(guard).unwrap();
718 /// Use [`park_timeout`].
720 /// Blocks unless or until the current thread's token is made available or
721 /// the specified duration has been reached (may wake spuriously).
723 /// The semantics of this function are equivalent to [`park`] except
724 /// that the thread will be blocked for roughly no longer than `dur`. This
725 /// method should not be used for precise timing due to anomalies such as
726 /// preemption or platform differences that may not cause the maximum
727 /// amount of time waited to be precisely `ms` long.
729 /// See the [park documentation][`park`] for more detail.
731 /// [`park_timeout`]: fn.park_timeout.html
732 /// [`park`]: ../../std/thread/fn.park.html
733 #[stable(feature = "rust1", since = "1.0.0")]
734 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::park_timeout`")]
735 pub fn park_timeout_ms(ms: u32) {
736 park_timeout(Duration::from_millis(ms as u64))
739 /// Blocks unless or until the current thread's token is made available or
740 /// the specified duration has been reached (may wake spuriously).
742 /// The semantics of this function are equivalent to [`park`][park] except
743 /// that the thread will be blocked for roughly no longer than `dur`. This
744 /// method should not be used for precise timing due to anomalies such as
745 /// preemption or platform differences that may not cause the maximum
746 /// amount of time waited to be precisely `dur` long.
748 /// See the [park dococumentation][park] for more details.
750 /// # Platform behavior
752 /// Platforms which do not support nanosecond precision for sleeping will have
753 /// `dur` rounded up to the nearest granularity of time they can sleep for.
757 /// Waiting for the complete expiration of the timeout:
760 /// use std::thread::park_timeout;
761 /// use std::time::{Instant, Duration};
763 /// let timeout = Duration::from_secs(2);
764 /// let beginning_park = Instant::now();
765 /// park_timeout(timeout);
767 /// while beginning_park.elapsed() < timeout {
768 /// println!("restarting park_timeout after {:?}", beginning_park.elapsed());
769 /// let timeout = timeout - beginning_park.elapsed();
770 /// park_timeout(timeout);
774 /// [park]: fn.park.html
775 #[stable(feature = "park_timeout", since = "1.4.0")]
776 pub fn park_timeout(dur: Duration) {
777 let thread = current();
778 let mut guard = thread.inner.lock.lock().unwrap();
780 let (g, _) = thread.inner.cvar.wait_timeout(guard, dur).unwrap();
786 ////////////////////////////////////////////////////////////////////////////////
788 ////////////////////////////////////////////////////////////////////////////////
790 /// A unique identifier for a running thread.
792 /// A `ThreadId` is an opaque object that has a unique value for each thread
793 /// that creates one. `ThreadId`s are not guaranteed to correspond to a thread's
794 /// system-designated identifier.
799 /// #![feature(thread_id)]
803 /// let other_thread = thread::spawn(|| {
804 /// thread::current().id()
807 /// let other_thread_id = other_thread.join().unwrap();
808 /// assert!(thread::current().id() != other_thread_id);
810 #[unstable(feature = "thread_id", issue = "21507")]
811 #[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
812 pub struct ThreadId(u64);
815 // Generate a new unique thread ID.
816 fn new() -> ThreadId {
817 static GUARD: mutex::Mutex = mutex::Mutex::new();
818 static mut COUNTER: u64 = 0;
823 // If we somehow use up all our bits, panic so that we're not
824 // covering up subtle bugs of IDs being reused.
825 if COUNTER == ::u64::MAX {
827 panic!("failed to generate unique thread ID: bitspace exhausted");
840 ////////////////////////////////////////////////////////////////////////////////
842 ////////////////////////////////////////////////////////////////////////////////
844 /// The internal representation of a `Thread` handle
846 name: Option<CString>, // Guaranteed to be UTF-8
848 lock: Mutex<bool>, // true when there is a buffered unpark
853 #[stable(feature = "rust1", since = "1.0.0")]
854 /// A handle to a thread.
856 /// Threads are represented via the `Thread` type, which you can get in one of
859 /// * By spawning a new thread, e.g. using the [`thread::spawn`][`spawn`]
860 /// function, and calling [`thread`][`JoinHandle::thread`] on the
862 /// * By requesting the current thread, using the [`thread::current`] function.
864 /// The [`thread::current`] function is available even for threads not spawned
865 /// by the APIs of this module.
867 /// There is usualy no need to create a `Thread` struct yourself, one
868 /// should instead use a function like `spawn` to create new threads, see the
869 /// docs of [`Builder`] and [`spawn`] for more details.
871 /// [`Builder`]: ../../std/thread/struct.Builder.html
872 /// [`spawn`]: ../../std/thread/fn.spawn.html
879 // Used only internally to construct a thread object without spawning
880 pub(crate) fn new(name: Option<String>) -> Thread {
881 let cname = name.map(|n| {
882 CString::new(n).expect("thread name may not contain interior null bytes")
885 inner: Arc::new(Inner {
888 lock: Mutex::new(false),
889 cvar: Condvar::new(),
894 /// Atomically makes the handle's token available if it is not already.
896 /// Every thread is equipped with some basic low-level blocking support, via
897 /// the [`park`][park] function and the `unpark()` method. These can be
898 /// used as a more CPU-efficient implementation of a spinlock.
900 /// See the [park documentation][park] for more details.
906 /// use std::time::Duration;
908 /// let parked_thread = thread::Builder::new()
910 /// println!("Parking thread");
912 /// println!("Thread unparked");
916 /// // Let some time pass for the thread to be spawned.
917 /// thread::sleep(Duration::from_millis(10));
919 /// println!("Unpark the thread");
920 /// parked_thread.thread().unpark();
922 /// parked_thread.join().unwrap();
925 /// [park]: fn.park.html
926 #[stable(feature = "rust1", since = "1.0.0")]
927 pub fn unpark(&self) {
928 let mut guard = self.inner.lock.lock().unwrap();
931 self.inner.cvar.notify_one();
935 /// Gets the thread's unique identifier.
940 /// #![feature(thread_id)]
944 /// let other_thread = thread::spawn(|| {
945 /// thread::current().id()
948 /// let other_thread_id = other_thread.join().unwrap();
949 /// assert!(thread::current().id() != other_thread_id);
951 #[unstable(feature = "thread_id", issue = "21507")]
952 pub fn id(&self) -> ThreadId {
956 /// Gets the thread's name.
960 /// Threads by default have no name specified:
965 /// let builder = thread::Builder::new();
967 /// let handler = builder.spawn(|| {
968 /// assert!(thread::current().name().is_none());
971 /// handler.join().unwrap();
974 /// Thread with a specified name:
979 /// let builder = thread::Builder::new()
980 /// .name("foo".into());
982 /// let handler = builder.spawn(|| {
983 /// assert_eq!(thread::current().name(), Some("foo"))
986 /// handler.join().unwrap();
988 #[stable(feature = "rust1", since = "1.0.0")]
989 pub fn name(&self) -> Option<&str> {
990 self.cname().map(|s| unsafe { str::from_utf8_unchecked(s.to_bytes()) } )
993 fn cname(&self) -> Option<&CStr> {
994 self.inner.name.as_ref().map(|s| &**s)
998 #[stable(feature = "rust1", since = "1.0.0")]
999 impl fmt::Debug for Thread {
1000 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1001 fmt::Debug::fmt(&self.name(), f)
1005 ////////////////////////////////////////////////////////////////////////////////
1007 ////////////////////////////////////////////////////////////////////////////////
1009 /// A specialized [`Result`] type for threads.
1011 /// Indicates the manner in which a thread exited.
1013 /// A thread that completes without panicking is considered to exit successfully.
1018 /// use std::thread;
1021 /// fn copy_in_thread() -> thread::Result<()> {
1022 /// thread::spawn(move || { fs::copy("foo.txt", "bar.txt").unwrap(); }).join()
1026 /// match copy_in_thread() {
1027 /// Ok(_) => println!("this is fine"),
1028 /// Err(_) => println!("thread panicked"),
1033 /// [`Result`]: ../../std/result/enum.Result.html
1034 #[stable(feature = "rust1", since = "1.0.0")]
1035 pub type Result<T> = ::result::Result<T, Box<Any + Send + 'static>>;
1037 // This packet is used to communicate the return value between the child thread
1038 // and the parent thread. Memory is shared through the `Arc` within and there's
1039 // no need for a mutex here because synchronization happens with `join()` (the
1040 // parent thread never reads this packet until the child has exited).
1042 // This packet itself is then stored into a `JoinInner` which in turns is placed
1043 // in `JoinHandle` and `JoinGuard`. Due to the usage of `UnsafeCell` we need to
1044 // manually worry about impls like Send and Sync. The type `T` should
1045 // already always be Send (otherwise the thread could not have been created) and
1046 // this type is inherently Sync because no methods take &self. Regardless,
1047 // however, we add inheriting impls for Send/Sync to this type to ensure it's
1048 // Send/Sync and that future modifications will still appropriately classify it.
1049 struct Packet<T>(Arc<UnsafeCell<Option<Result<T>>>>);
1051 unsafe impl<T: Send> Send for Packet<T> {}
1052 unsafe impl<T: Sync> Sync for Packet<T> {}
1054 /// Inner representation for JoinHandle
1055 struct JoinInner<T> {
1056 native: Option<imp::Thread>,
1061 impl<T> JoinInner<T> {
1062 fn join(&mut self) -> Result<T> {
1063 self.native.take().unwrap().join();
1065 (*self.packet.0.get()).take().unwrap()
1070 /// An owned permission to join on a thread (block on its termination).
1072 /// A `JoinHandle` *detaches* the child thread when it is dropped.
1074 /// Due to platform restrictions, it is not possible to [`Clone`] this
1075 /// handle: the ability to join a child thread is a uniquely-owned
1078 /// This `struct` is created by the [`thread::spawn`] function and the
1079 /// [`thread::Builder::spawn`] method.
1083 /// Creation from [`thread::spawn`]:
1086 /// use std::thread;
1088 /// let join_handle: thread::JoinHandle<_> = thread::spawn(|| {
1089 /// // some work here
1093 /// Creation from [`thread::Builder::spawn`]:
1096 /// use std::thread;
1098 /// let builder = thread::Builder::new();
1100 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1101 /// // some work here
1105 /// [`Clone`]: ../../std/clone/trait.Clone.html
1106 /// [`thread::spawn`]: fn.spawn.html
1107 /// [`thread::Builder::spawn`]: struct.Builder.html#method.spawn
1108 #[stable(feature = "rust1", since = "1.0.0")]
1109 pub struct JoinHandle<T>(JoinInner<T>);
1111 impl<T> JoinHandle<T> {
1112 /// Extracts a handle to the underlying thread.
1117 /// #![feature(thread_id)]
1119 /// use std::thread;
1121 /// let builder = thread::Builder::new();
1123 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1124 /// // some work here
1127 /// let thread = join_handle.thread();
1128 /// println!("thread id: {:?}", thread.id());
1130 #[stable(feature = "rust1", since = "1.0.0")]
1131 pub fn thread(&self) -> &Thread {
1135 /// Waits for the associated thread to finish.
1137 /// If the child thread panics, [`Err`] is returned with the parameter given
1140 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1141 /// [`panic`]: ../../std/macro.panic.html
1146 /// use std::thread;
1148 /// let builder = thread::Builder::new();
1150 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
1151 /// // some work here
1153 /// join_handle.join().expect("Couldn't join on the associated thread");
1155 #[stable(feature = "rust1", since = "1.0.0")]
1156 pub fn join(mut self) -> Result<T> {
1161 impl<T> AsInner<imp::Thread> for JoinHandle<T> {
1162 fn as_inner(&self) -> &imp::Thread { self.0.native.as_ref().unwrap() }
1165 impl<T> IntoInner<imp::Thread> for JoinHandle<T> {
1166 fn into_inner(self) -> imp::Thread { self.0.native.unwrap() }
1169 #[stable(feature = "std_debug", since = "1.16.0")]
1170 impl<T> fmt::Debug for JoinHandle<T> {
1171 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1172 f.pad("JoinHandle { .. }")
1176 fn _assert_sync_and_send() {
1177 fn _assert_both<T: Send + Sync>() {}
1178 _assert_both::<JoinHandle<()>>();
1179 _assert_both::<Thread>();
1182 ////////////////////////////////////////////////////////////////////////////////
1184 ////////////////////////////////////////////////////////////////////////////////
1186 #[cfg(all(test, not(target_os = "emscripten")))]
1189 use sync::mpsc::{channel, Sender};
1191 use super::{Builder};
1196 // !!! These tests are dangerous. If something is buggy, they will hang, !!!
1197 // !!! instead of exiting cleanly. This might wedge the buildbots. !!!
1200 fn test_unnamed_thread() {
1201 thread::spawn(move|| {
1202 assert!(thread::current().name().is_none());
1203 }).join().ok().unwrap();
1207 fn test_named_thread() {
1208 Builder::new().name("ada lovelace".to_string()).spawn(move|| {
1209 assert!(thread::current().name().unwrap() == "ada lovelace".to_string());
1210 }).unwrap().join().unwrap();
1215 fn test_invalid_named_thread() {
1216 let _ = Builder::new().name("ada l\0velace".to_string()).spawn(|| {});
1220 fn test_run_basic() {
1221 let (tx, rx) = channel();
1222 thread::spawn(move|| {
1223 tx.send(()).unwrap();
1229 fn test_join_panic() {
1230 match thread::spawn(move|| {
1233 result::Result::Err(_) => (),
1234 result::Result::Ok(()) => panic!()
1239 fn test_spawn_sched() {
1240 let (tx, rx) = channel();
1242 fn f(i: i32, tx: Sender<()>) {
1243 let tx = tx.clone();
1244 thread::spawn(move|| {
1246 tx.send(()).unwrap();
1258 fn test_spawn_sched_childs_on_default_sched() {
1259 let (tx, rx) = channel();
1261 thread::spawn(move|| {
1262 thread::spawn(move|| {
1263 tx.send(()).unwrap();
1270 fn avoid_copying_the_body<F>(spawnfn: F) where F: FnOnce(Box<Fn() + Send>) {
1271 let (tx, rx) = channel();
1273 let x: Box<_> = box 1;
1274 let x_in_parent = (&*x) as *const i32 as usize;
1276 spawnfn(Box::new(move|| {
1277 let x_in_child = (&*x) as *const i32 as usize;
1278 tx.send(x_in_child).unwrap();
1281 let x_in_child = rx.recv().unwrap();
1282 assert_eq!(x_in_parent, x_in_child);
1286 fn test_avoid_copying_the_body_spawn() {
1287 avoid_copying_the_body(|v| {
1288 thread::spawn(move || v());
1293 fn test_avoid_copying_the_body_thread_spawn() {
1294 avoid_copying_the_body(|f| {
1295 thread::spawn(move|| {
1302 fn test_avoid_copying_the_body_join() {
1303 avoid_copying_the_body(|f| {
1304 let _ = thread::spawn(move|| {
1311 fn test_child_doesnt_ref_parent() {
1312 // If the child refcounts the parent thread, this will stack overflow when
1313 // climbing the thread tree to dereference each ancestor. (See #1789)
1314 // (well, it would if the constant were 8000+ - I lowered it to be more
1315 // valgrind-friendly. try this at home, instead..!)
1316 const GENERATIONS: u32 = 16;
1317 fn child_no(x: u32) -> Box<Fn() + Send> {
1318 return Box::new(move|| {
1319 if x < GENERATIONS {
1320 thread::spawn(move|| child_no(x+1)());
1324 thread::spawn(|| child_no(0)());
1328 fn test_simple_newsched_spawn() {
1329 thread::spawn(move || {});
1333 fn test_try_panic_message_static_str() {
1334 match thread::spawn(move|| {
1335 panic!("static string");
1338 type T = &'static str;
1339 assert!(e.is::<T>());
1340 assert_eq!(*e.downcast::<T>().unwrap(), "static string");
1347 fn test_try_panic_message_owned_str() {
1348 match thread::spawn(move|| {
1349 panic!("owned string".to_string());
1353 assert!(e.is::<T>());
1354 assert_eq!(*e.downcast::<T>().unwrap(), "owned string".to_string());
1361 fn test_try_panic_message_any() {
1362 match thread::spawn(move|| {
1363 panic!(box 413u16 as Box<Any + Send>);
1366 type T = Box<Any + Send>;
1367 assert!(e.is::<T>());
1368 let any = e.downcast::<T>().unwrap();
1369 assert!(any.is::<u16>());
1370 assert_eq!(*any.downcast::<u16>().unwrap(), 413);
1377 fn test_try_panic_message_unit_struct() {
1380 match thread::spawn(move|| {
1383 Err(ref e) if e.is::<Juju>() => {}
1384 Err(_) | Ok(()) => panic!()
1389 fn test_park_timeout_unpark_before() {
1391 thread::current().unpark();
1392 thread::park_timeout(Duration::from_millis(u32::MAX as u64));
1397 fn test_park_timeout_unpark_not_called() {
1399 thread::park_timeout(Duration::from_millis(10));
1404 fn test_park_timeout_unpark_called_other_thread() {
1406 let th = thread::current();
1408 let _guard = thread::spawn(move || {
1409 super::sleep(Duration::from_millis(50));
1413 thread::park_timeout(Duration::from_millis(u32::MAX as u64));
1418 fn sleep_ms_smoke() {
1419 thread::sleep(Duration::from_millis(2));
1423 fn test_thread_id_equal() {
1424 assert!(thread::current().id() == thread::current().id());
1428 fn test_thread_id_not_equal() {
1429 let spawned_id = thread::spawn(|| thread::current().id()).join().unwrap();
1430 assert!(thread::current().id() != spawned_id);
1433 // NOTE: the corresponding test for stderr is in run-pass/thread-stderr, due
1434 // to the test harness apparently interfering with stderr configuration.