]> git.lizzy.rs Git - rust.git/blob - src/libstd/thread/mod.rs
8e7eaa77cd7098be059fa392fdc28599b9cfd21e
[rust.git] / src / libstd / thread / mod.rs
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.
4 //
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.
10
11 //! Native threads.
12 //!
13 //! ## The threading model
14 //!
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.
18 //!
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`].
25 //!
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
32 //! exit code.
33 //!
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).
38 //!
39 //! ## Spawning a thread
40 //!
41 //! A new thread can be spawned using the [`thread::spawn`][`spawn`] function:
42 //!
43 //! ```rust
44 //! use std::thread;
45 //!
46 //! thread::spawn(move || {
47 //!     // some work here
48 //! });
49 //! ```
50 //!
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.
54 //!
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:
58 //!
59 //! ```rust
60 //! use std::thread;
61 //!
62 //! let child = thread::spawn(move || {
63 //!     // some work here
64 //! });
65 //! // some work here
66 //! let res = child.join();
67 //! ```
68 //!
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.
72 //!
73 //! ## Configuring threads
74 //!
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:
77 //!
78 //! ```rust
79 //! # #![allow(unused_must_use)]
80 //! use std::thread;
81 //!
82 //! thread::Builder::new().name("child1".to_string()).spawn(move || {
83 //!     println!("Hello, world!");
84 //! });
85 //! ```
86 //!
87 //! ## The `Thread` type
88 //!
89 //! Threads are represented via the [`Thread`] type, which you can get in one of
90 //! two ways:
91 //!
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.
95 //!
96 //! The [`thread::current`] function is available even for threads not spawned
97 //! by the APIs of this module.
98 //!
99 //! ## Blocking support: park and unpark
100 //!
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.
105 //!
106 //! Conceptually, each [`Thread`] handle has an associated token, which is
107 //! initially not present:
108 //!
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.
114 //!
115 //! * The [`unpark`] method on a [`Thread`] atomically makes the token available
116 //!   if it wasn't already.
117 //!
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.
121 //!
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.
126 //!
127 //! The motivation for this design is twofold:
128 //!
129 //! * It avoids the need to allocate mutexes and condvars when building new
130 //!   synchronization primitives; the threads already provide basic blocking/signaling.
131 //!
132 //! * It can be implemented very efficiently on many platforms.
133 //!
134 //! ## Thread-local storage
135 //!
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.
140 //!
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.
149 //!
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
171
172 #![stable(feature = "rust1", since = "1.0.0")]
173
174 use any::Any;
175 use cell::UnsafeCell;
176 use ffi::{CStr, CString};
177 use fmt;
178 use io;
179 use panic;
180 use panicking;
181 use str;
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};
188 use time::Duration;
189
190 ////////////////////////////////////////////////////////////////////////////////
191 // Thread-local storage
192 ////////////////////////////////////////////////////////////////////////////////
193
194 #[macro_use] mod local;
195
196 #[stable(feature = "rust1", since = "1.0.0")]
197 pub use self::local::{LocalKey, LocalKeyState};
198
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.
207
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;
213
214 ////////////////////////////////////////////////////////////////////////////////
215 // Builder
216 ////////////////////////////////////////////////////////////////////////////////
217
218 /// Thread configuration. Provides detailed control over the properties
219 /// and behavior of new threads.
220 ///
221 /// # Examples
222 ///
223 /// ```
224 /// use std::thread;
225 ///
226 /// let builder = thread::Builder::new();
227 ///
228 /// let handler = builder.spawn(|| {
229 ///     // thread code
230 /// }).unwrap();
231 ///
232 /// handler.join().unwrap();
233 /// ```
234 #[stable(feature = "rust1", since = "1.0.0")]
235 #[derive(Debug)]
236 pub struct Builder {
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>,
241 }
242
243 impl Builder {
244     /// Generates the base configuration for spawning a thread, from which
245     /// configuration methods can be chained.
246     ///
247     /// # Examples
248     ///
249     /// ```
250     /// use std::thread;
251     ///
252     /// let builder = thread::Builder::new()
253     ///                               .name("foo".into())
254     ///                               .stack_size(10);
255     ///
256     /// let handler = builder.spawn(|| {
257     ///     // thread code
258     /// }).unwrap();
259     ///
260     /// handler.join().unwrap();
261     /// ```
262     #[stable(feature = "rust1", since = "1.0.0")]
263     pub fn new() -> Builder {
264         Builder {
265             name: None,
266             stack_size: None,
267         }
268     }
269
270     /// Names the thread-to-be. Currently the name is used for identification
271     /// only in panic messages.
272     ///
273     /// # Examples
274     ///
275     /// ```
276     /// use std::thread;
277     ///
278     /// let builder = thread::Builder::new()
279     ///     .name("foo".into());
280     ///
281     /// let handler = builder.spawn(|| {
282     ///     assert_eq!(thread::current().name(), Some("foo"))
283     /// }).unwrap();
284     ///
285     /// handler.join().unwrap();
286     /// ```
287     #[stable(feature = "rust1", since = "1.0.0")]
288     pub fn name(mut self, name: String) -> Builder {
289         self.name = Some(name);
290         self
291     }
292
293     /// Sets the size of the stack (in bytes) for the new thread.
294     ///
295     /// The actual stack size may be greater than this value if
296     /// the platform specifies minimal stack size.
297     ///
298     /// # Examples
299     ///
300     /// ```
301     /// use std::thread;
302     ///
303     /// let builder = thread::Builder::new().stack_size(32 * 1024);
304     /// ```
305     #[stable(feature = "rust1", since = "1.0.0")]
306     pub fn stack_size(mut self, size: usize) -> Builder {
307         self.stack_size = Some(size);
308         self
309     }
310
311     /// Spawns a new thread, and returns a join handle for it.
312     ///
313     /// The child thread may outlive the parent (unless the parent thread
314     /// is the main thread; the whole process is terminated when the main
315     /// thread finishes). The join handle can be used to block on
316     /// termination of the child thread, including recovering its panics.
317     ///
318     /// # Errors
319     ///
320     /// Unlike the [`spawn`] free function, this method yields an
321     /// [`io::Result`] to capture any failure to create the thread at
322     /// the OS level.
323     ///
324     /// [`spawn`]: ../../std/thread/fn.spawn.html
325     /// [`io::Result`]: ../../std/io/type.Result.html
326     ///
327     /// # Examples
328     ///
329     /// ```
330     /// use std::thread;
331     ///
332     /// let builder = thread::Builder::new();
333     ///
334     /// let handler = builder.spawn(|| {
335     ///     // thread code
336     /// }).unwrap();
337     ///
338     /// handler.join().unwrap();
339     /// ```
340     #[stable(feature = "rust1", since = "1.0.0")]
341     pub fn spawn<F, T>(self, f: F) -> io::Result<JoinHandle<T>> where
342         F: FnOnce() -> T, F: Send + 'static, T: Send + 'static
343     {
344         let Builder { name, stack_size } = self;
345
346         let stack_size = stack_size.unwrap_or(util::min_stack());
347
348         let my_thread = Thread::new(name);
349         let their_thread = my_thread.clone();
350
351         let my_packet : Arc<UnsafeCell<Option<Result<T>>>>
352             = Arc::new(UnsafeCell::new(None));
353         let their_packet = my_packet.clone();
354
355         let main = move || {
356             if let Some(name) = their_thread.cname() {
357                 imp::Thread::set_name(name);
358             }
359             unsafe {
360                 thread_info::set(imp::guard::current(), their_thread);
361                 let try_result = panic::catch_unwind(panic::AssertUnwindSafe(f));
362                 *their_packet.get() = Some(try_result);
363             }
364         };
365
366         Ok(JoinHandle(JoinInner {
367             native: unsafe {
368                 Some(imp::Thread::new(stack_size, Box::new(main))?)
369             },
370             thread: my_thread,
371             packet: Packet(my_packet),
372         }))
373     }
374 }
375
376 ////////////////////////////////////////////////////////////////////////////////
377 // Free functions
378 ////////////////////////////////////////////////////////////////////////////////
379
380 /// Spawns a new thread, returning a [`JoinHandle`] for it.
381 ///
382 /// The join handle will implicitly *detach* the child thread upon being
383 /// dropped. In this case, the child thread may outlive the parent (unless
384 /// the parent thread is the main thread; the whole process is terminated when
385 /// the main thread finishes). Additionally, the join handle provides a [`join`]
386 /// method that can be used to join the child thread. If the child thread
387 /// panics, [`join`] will return an [`Err`] containing the argument given to
388 /// [`panic`].
389 ///
390 /// # Panics
391 ///
392 /// Panics if the OS fails to create a thread; use [`Builder::spawn`]
393 /// to recover from such errors.
394 ///
395 /// [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
396 /// [`join`]: ../../std/thread/struct.JoinHandle.html#method.join
397 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
398 /// [`panic`]: ../../std/macro.panic.html
399 /// [`Builder::spawn`]: ../../std/thread/struct.Builder.html#method.spawn
400 ///
401 /// # Examples
402 ///
403 /// ```
404 /// use std::thread;
405 ///
406 /// let handler = thread::spawn(|| {
407 ///     // thread code
408 /// });
409 ///
410 /// handler.join().unwrap();
411 /// ```
412 #[stable(feature = "rust1", since = "1.0.0")]
413 pub fn spawn<F, T>(f: F) -> JoinHandle<T> where
414     F: FnOnce() -> T, F: Send + 'static, T: Send + 'static
415 {
416     Builder::new().spawn(f).unwrap()
417 }
418
419 /// Gets a handle to the thread that invokes it.
420 ///
421 /// # Examples
422 ///
423 /// Getting a handle to the current thread with `thread::current()`:
424 ///
425 /// ```
426 /// use std::thread;
427 ///
428 /// let handler = thread::Builder::new()
429 ///     .name("named thread".into())
430 ///     .spawn(|| {
431 ///         let handle = thread::current();
432 ///         assert_eq!(handle.name(), Some("named thread"));
433 ///     })
434 ///     .unwrap();
435 ///
436 /// handler.join().unwrap();
437 /// ```
438 #[stable(feature = "rust1", since = "1.0.0")]
439 pub fn current() -> Thread {
440     thread_info::current_thread().expect("use of std::thread::current() is not \
441                                           possible after the thread's local \
442                                           data has been destroyed")
443 }
444
445 /// Cooperatively gives up a timeslice to the OS scheduler.
446 ///
447 /// # Examples
448 ///
449 /// ```
450 /// use std::thread;
451 ///
452 /// thread::yield_now();
453 /// ```
454 #[stable(feature = "rust1", since = "1.0.0")]
455 pub fn yield_now() {
456     imp::Thread::yield_now()
457 }
458
459 /// Determines whether the current thread is unwinding because of panic.
460 ///
461 /// # Examples
462 ///
463 /// ```should_panic
464 /// use std::thread;
465 ///
466 /// struct SomeStruct;
467 ///
468 /// impl Drop for SomeStruct {
469 ///     fn drop(&mut self) {
470 ///         if thread::panicking() {
471 ///             println!("dropped while unwinding");
472 ///         } else {
473 ///             println!("dropped while not unwinding");
474 ///         }
475 ///     }
476 /// }
477 ///
478 /// {
479 ///     print!("a: ");
480 ///     let a = SomeStruct;
481 /// }
482 ///
483 /// {
484 ///     print!("b: ");
485 ///     let b = SomeStruct;
486 ///     panic!()
487 /// }
488 /// ```
489 #[inline]
490 #[stable(feature = "rust1", since = "1.0.0")]
491 pub fn panicking() -> bool {
492     panicking::panicking()
493 }
494
495 /// Puts the current thread to sleep for the specified amount of time.
496 ///
497 /// The thread may sleep longer than the duration specified due to scheduling
498 /// specifics or platform-dependent functionality.
499 ///
500 /// # Platform behavior
501 ///
502 /// On Unix platforms this function will not return early due to a
503 /// signal being received or a spurious wakeup.
504 ///
505 /// # Examples
506 ///
507 /// ```no_run
508 /// use std::thread;
509 ///
510 /// // Let's sleep for 2 seconds:
511 /// thread::sleep_ms(2000);
512 /// ```
513 #[stable(feature = "rust1", since = "1.0.0")]
514 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::sleep`")]
515 pub fn sleep_ms(ms: u32) {
516     sleep(Duration::from_millis(ms as u64))
517 }
518
519 /// Puts the current thread to sleep for the specified amount of time.
520 ///
521 /// The thread may sleep longer than the duration specified due to scheduling
522 /// specifics or platform-dependent functionality.
523 ///
524 /// # Platform behavior
525 ///
526 /// On Unix platforms this function will not return early due to a
527 /// signal being received or a spurious wakeup. Platforms which do not support
528 /// nanosecond precision for sleeping will have `dur` rounded up to the nearest
529 /// granularity of time they can sleep for.
530 ///
531 /// # Examples
532 ///
533 /// ```no_run
534 /// use std::{thread, time};
535 ///
536 /// let ten_millis = time::Duration::from_millis(10);
537 /// let now = time::Instant::now();
538 ///
539 /// thread::sleep(ten_millis);
540 ///
541 /// assert!(now.elapsed() >= ten_millis);
542 /// ```
543 #[stable(feature = "thread_sleep", since = "1.4.0")]
544 pub fn sleep(dur: Duration) {
545     imp::Thread::sleep(dur)
546 }
547
548 /// Blocks unless or until the current thread's token is made available.
549 ///
550 /// Every thread is equipped with some basic low-level blocking support, via
551 /// the `park()` function and the [`unpark`][unpark] method. These can be
552 /// used as a more CPU-efficient implementation of a spinlock.
553 ///
554 /// [unpark]: struct.Thread.html#method.unpark
555 ///
556 /// The API is typically used by acquiring a handle to the current thread,
557 /// placing that handle in a shared data structure so that other threads can
558 /// find it, and then parking (in a loop with a check for the token actually
559 /// being acquired).
560 ///
561 /// A call to `park` does not guarantee that the thread will remain parked
562 /// forever, and callers should be prepared for this possibility.
563 ///
564 /// See the [module documentation][thread] for more detail.
565 ///
566 /// [thread]: index.html
567 //
568 // The implementation currently uses the trivial strategy of a Mutex+Condvar
569 // with wakeup flag, which does not actually allow spurious wakeups. In the
570 // future, this will be implemented in a more efficient way, perhaps along the lines of
571 //   http://cr.openjdk.java.net/~stefank/6989984.1/raw_files/new/src/os/linux/vm/os_linux.cpp
572 // or futuxes, and in either case may allow spurious wakeups.
573 #[stable(feature = "rust1", since = "1.0.0")]
574 pub fn park() {
575     let thread = current();
576     let mut guard = thread.inner.lock.lock().unwrap();
577     while !*guard {
578         guard = thread.inner.cvar.wait(guard).unwrap();
579     }
580     *guard = false;
581 }
582
583 /// Use [park_timeout].
584 ///
585 /// Blocks unless or until the current thread's token is made available or
586 /// the specified duration has been reached (may wake spuriously).
587 ///
588 /// The semantics of this function are equivalent to `park()` except that the
589 /// thread will be blocked for roughly no longer than `ms`. This method
590 /// should not be used for precise timing due to anomalies such as
591 /// preemption or platform differences that may not cause the maximum
592 /// amount of time waited to be precisely `ms` long.
593 ///
594 /// See the [module documentation][thread] for more detail.
595 ///
596 /// [thread]: index.html
597 /// [park_timeout]: fn.park_timeout.html
598 #[stable(feature = "rust1", since = "1.0.0")]
599 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::park_timeout`")]
600 pub fn park_timeout_ms(ms: u32) {
601     park_timeout(Duration::from_millis(ms as u64))
602 }
603
604 /// Blocks unless or until the current thread's token is made available or
605 /// the specified duration has been reached (may wake spuriously).
606 ///
607 /// The semantics of this function are equivalent to `park()` except that the
608 /// thread will be blocked for roughly no longer than `dur`. 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 `dur` long.
612 ///
613 /// See the module doc for more detail.
614 ///
615 /// # Platform behavior
616 ///
617 /// Platforms which do not support nanosecond precision for sleeping will have
618 /// `dur` rounded up to the nearest granularity of time they can sleep for.
619 ///
620 /// # Example
621 ///
622 /// Waiting for the complete expiration of the timeout:
623 ///
624 /// ```rust,no_run
625 /// use std::thread::park_timeout;
626 /// use std::time::{Instant, Duration};
627 ///
628 /// let timeout = Duration::from_secs(2);
629 /// let beginning_park = Instant::now();
630 /// park_timeout(timeout);
631 ///
632 /// while beginning_park.elapsed() < timeout {
633 ///     println!("restarting park_timeout after {:?}", beginning_park.elapsed());
634 ///     let timeout = timeout - beginning_park.elapsed();
635 ///     park_timeout(timeout);
636 /// }
637 /// ```
638 #[stable(feature = "park_timeout", since = "1.4.0")]
639 pub fn park_timeout(dur: Duration) {
640     let thread = current();
641     let mut guard = thread.inner.lock.lock().unwrap();
642     if !*guard {
643         let (g, _) = thread.inner.cvar.wait_timeout(guard, dur).unwrap();
644         guard = g;
645     }
646     *guard = false;
647 }
648
649 ////////////////////////////////////////////////////////////////////////////////
650 // ThreadId
651 ////////////////////////////////////////////////////////////////////////////////
652
653 /// A unique identifier for a running thread.
654 ///
655 /// A `ThreadId` is an opaque object that has a unique value for each thread
656 /// that creates one. `ThreadId`s are not guaranteed to correspond to a thread's
657 /// system-designated identifier.
658 ///
659 /// # Examples
660 ///
661 /// ```
662 /// #![feature(thread_id)]
663 ///
664 /// use std::thread;
665 ///
666 /// let other_thread = thread::spawn(|| {
667 ///     thread::current().id()
668 /// });
669 ///
670 /// let other_thread_id = other_thread.join().unwrap();
671 /// assert!(thread::current().id() != other_thread_id);
672 /// ```
673 #[unstable(feature = "thread_id", issue = "21507")]
674 #[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
675 pub struct ThreadId(u64);
676
677 impl ThreadId {
678     // Generate a new unique thread ID.
679     fn new() -> ThreadId {
680         static GUARD: mutex::Mutex = mutex::Mutex::new();
681         static mut COUNTER: u64 = 0;
682
683         unsafe {
684             GUARD.lock();
685
686             // If we somehow use up all our bits, panic so that we're not
687             // covering up subtle bugs of IDs being reused.
688             if COUNTER == ::u64::MAX {
689                 GUARD.unlock();
690                 panic!("failed to generate unique thread ID: bitspace exhausted");
691             }
692
693             let id = COUNTER;
694             COUNTER += 1;
695
696             GUARD.unlock();
697
698             ThreadId(id)
699         }
700     }
701 }
702
703 ////////////////////////////////////////////////////////////////////////////////
704 // Thread
705 ////////////////////////////////////////////////////////////////////////////////
706
707 /// The internal representation of a `Thread` handle
708 struct Inner {
709     name: Option<CString>,      // Guaranteed to be UTF-8
710     id: ThreadId,
711     lock: Mutex<bool>,          // true when there is a buffered unpark
712     cvar: Condvar,
713 }
714
715 #[derive(Clone)]
716 #[stable(feature = "rust1", since = "1.0.0")]
717 /// A handle to a thread.
718 ///
719 /// You can use it to identify a thread (by name, for example). Most of the
720 /// time, there is no need to directly create a `Thread` struct using the
721 /// constructor, instead you should use a function like `spawn` to create
722 /// new threads, see the docs of [`Builder`] and [`spawn`] for more.
723 ///
724 /// # Examples
725 ///
726 /// ```
727 /// use std::thread::Builder;
728 ///
729 /// for i in 0..5 {
730 ///     let thread_name = format!("thread_{}", i);
731 ///     Builder::new()
732 ///         .name(thread_name) // Now you can identify which thread panicked
733 ///                            // thanks to the handle's name
734 ///         .spawn(move || {
735 ///             if i == 3 {
736 ///                  panic!("I'm scared!!!");
737 ///             }
738 ///         })
739 ///         .unwrap();
740 /// }
741 /// ```
742 /// [`Builder`]: ../../std/thread/struct.Builder.html
743 /// [`spawn`]: ../../std/thread/fn.spawn.html
744
745 pub struct Thread {
746     inner: Arc<Inner>,
747 }
748
749 impl Thread {
750     // Used only internally to construct a thread object without spawning
751     pub(crate) fn new(name: Option<String>) -> Thread {
752         let cname = name.map(|n| {
753             CString::new(n).expect("thread name may not contain interior null bytes")
754         });
755         Thread {
756             inner: Arc::new(Inner {
757                 name: cname,
758                 id: ThreadId::new(),
759                 lock: Mutex::new(false),
760                 cvar: Condvar::new(),
761             })
762         }
763     }
764
765     /// Atomically makes the handle's token available if it is not already.
766     ///
767     /// See the module doc for more detail.
768     ///
769     /// # Examples
770     ///
771     /// ```
772     /// use std::thread;
773     ///
774     /// let handler = thread::Builder::new()
775     ///     .spawn(|| {
776     ///         let thread = thread::current();
777     ///         thread.unpark();
778     ///     })
779     ///     .unwrap();
780     ///
781     /// handler.join().unwrap();
782     /// ```
783     #[stable(feature = "rust1", since = "1.0.0")]
784     pub fn unpark(&self) {
785         let mut guard = self.inner.lock.lock().unwrap();
786         if !*guard {
787             *guard = true;
788             self.inner.cvar.notify_one();
789         }
790     }
791
792     /// Gets the thread's unique identifier.
793     ///
794     /// # Examples
795     ///
796     /// ```
797     /// #![feature(thread_id)]
798     ///
799     /// use std::thread;
800     ///
801     /// let other_thread = thread::spawn(|| {
802     ///     thread::current().id()
803     /// });
804     ///
805     /// let other_thread_id = other_thread.join().unwrap();
806     /// assert!(thread::current().id() != other_thread_id);
807     /// ```
808     #[unstable(feature = "thread_id", issue = "21507")]
809     pub fn id(&self) -> ThreadId {
810         self.inner.id
811     }
812
813     /// Gets the thread's name.
814     ///
815     /// # Examples
816     ///
817     /// Threads by default have no name specified:
818     ///
819     /// ```
820     /// use std::thread;
821     ///
822     /// let builder = thread::Builder::new();
823     ///
824     /// let handler = builder.spawn(|| {
825     ///     assert!(thread::current().name().is_none());
826     /// }).unwrap();
827     ///
828     /// handler.join().unwrap();
829     /// ```
830     ///
831     /// Thread with a specified name:
832     ///
833     /// ```
834     /// use std::thread;
835     ///
836     /// let builder = thread::Builder::new()
837     ///     .name("foo".into());
838     ///
839     /// let handler = builder.spawn(|| {
840     ///     assert_eq!(thread::current().name(), Some("foo"))
841     /// }).unwrap();
842     ///
843     /// handler.join().unwrap();
844     /// ```
845     #[stable(feature = "rust1", since = "1.0.0")]
846     pub fn name(&self) -> Option<&str> {
847         self.cname().map(|s| unsafe { str::from_utf8_unchecked(s.to_bytes()) } )
848     }
849
850     fn cname(&self) -> Option<&CStr> {
851         self.inner.name.as_ref().map(|s| &**s)
852     }
853 }
854
855 #[stable(feature = "rust1", since = "1.0.0")]
856 impl fmt::Debug for Thread {
857     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
858         fmt::Debug::fmt(&self.name(), f)
859     }
860 }
861
862 ////////////////////////////////////////////////////////////////////////////////
863 // JoinHandle
864 ////////////////////////////////////////////////////////////////////////////////
865
866 /// Indicates the manner in which a thread exited.
867 ///
868 /// A thread that completes without panicking is considered to exit successfully.
869 #[stable(feature = "rust1", since = "1.0.0")]
870 pub type Result<T> = ::result::Result<T, Box<Any + Send + 'static>>;
871
872 // This packet is used to communicate the return value between the child thread
873 // and the parent thread. Memory is shared through the `Arc` within and there's
874 // no need for a mutex here because synchronization happens with `join()` (the
875 // parent thread never reads this packet until the child has exited).
876 //
877 // This packet itself is then stored into a `JoinInner` which in turns is placed
878 // in `JoinHandle` and `JoinGuard`. Due to the usage of `UnsafeCell` we need to
879 // manually worry about impls like Send and Sync. The type `T` should
880 // already always be Send (otherwise the thread could not have been created) and
881 // this type is inherently Sync because no methods take &self. Regardless,
882 // however, we add inheriting impls for Send/Sync to this type to ensure it's
883 // Send/Sync and that future modifications will still appropriately classify it.
884 struct Packet<T>(Arc<UnsafeCell<Option<Result<T>>>>);
885
886 unsafe impl<T: Send> Send for Packet<T> {}
887 unsafe impl<T: Sync> Sync for Packet<T> {}
888
889 /// Inner representation for JoinHandle
890 struct JoinInner<T> {
891     native: Option<imp::Thread>,
892     thread: Thread,
893     packet: Packet<T>,
894 }
895
896 impl<T> JoinInner<T> {
897     fn join(&mut self) -> Result<T> {
898         self.native.take().unwrap().join();
899         unsafe {
900             (*self.packet.0.get()).take().unwrap()
901         }
902     }
903 }
904
905 /// An owned permission to join on a thread (block on its termination).
906 ///
907 /// A `JoinHandle` *detaches* the child thread when it is dropped.
908 ///
909 /// Due to platform restrictions, it is not possible to [`Clone`] this
910 /// handle: the ability to join a child thread is a uniquely-owned
911 /// permission.
912 ///
913 /// This `struct` is created by the [`thread::spawn`] function and the
914 /// [`thread::Builder::spawn`] method.
915 ///
916 /// # Examples
917 ///
918 /// Creation from [`thread::spawn`]:
919 ///
920 /// ```
921 /// use std::thread;
922 ///
923 /// let join_handle: thread::JoinHandle<_> = thread::spawn(|| {
924 ///     // some work here
925 /// });
926 /// ```
927 ///
928 /// Creation from [`thread::Builder::spawn`]:
929 ///
930 /// ```
931 /// use std::thread;
932 ///
933 /// let builder = thread::Builder::new();
934 ///
935 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
936 ///     // some work here
937 /// }).unwrap();
938 /// ```
939 ///
940 /// [`Clone`]: ../../std/clone/trait.Clone.html
941 /// [`thread::spawn`]: fn.spawn.html
942 /// [`thread::Builder::spawn`]: struct.Builder.html#method.spawn
943 #[stable(feature = "rust1", since = "1.0.0")]
944 pub struct JoinHandle<T>(JoinInner<T>);
945
946 impl<T> JoinHandle<T> {
947     /// Extracts a handle to the underlying thread.
948     ///
949     /// # Examples
950     ///
951     /// ```
952     /// #![feature(thread_id)]
953     ///
954     /// use std::thread;
955     ///
956     /// let builder = thread::Builder::new();
957     ///
958     /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
959     ///     // some work here
960     /// }).unwrap();
961     ///
962     /// let thread = join_handle.thread();
963     /// println!("thread id: {:?}", thread.id());
964     /// ```
965     #[stable(feature = "rust1", since = "1.0.0")]
966     pub fn thread(&self) -> &Thread {
967         &self.0.thread
968     }
969
970     /// Waits for the associated thread to finish.
971     ///
972     /// If the child thread panics, [`Err`] is returned with the parameter given
973     /// to [`panic`].
974     ///
975     /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
976     /// [`panic`]: ../../std/macro.panic.html
977     ///
978     /// # Examples
979     ///
980     /// ```
981     /// use std::thread;
982     ///
983     /// let builder = thread::Builder::new();
984     ///
985     /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
986     ///     // some work here
987     /// }).unwrap();
988     /// join_handle.join().expect("Couldn't join on the associated thread");
989     /// ```
990     #[stable(feature = "rust1", since = "1.0.0")]
991     pub fn join(mut self) -> Result<T> {
992         self.0.join()
993     }
994 }
995
996 impl<T> AsInner<imp::Thread> for JoinHandle<T> {
997     fn as_inner(&self) -> &imp::Thread { self.0.native.as_ref().unwrap() }
998 }
999
1000 impl<T> IntoInner<imp::Thread> for JoinHandle<T> {
1001     fn into_inner(self) -> imp::Thread { self.0.native.unwrap() }
1002 }
1003
1004 #[stable(feature = "std_debug", since = "1.16.0")]
1005 impl<T> fmt::Debug for JoinHandle<T> {
1006     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1007         f.pad("JoinHandle { .. }")
1008     }
1009 }
1010
1011 fn _assert_sync_and_send() {
1012     fn _assert_both<T: Send + Sync>() {}
1013     _assert_both::<JoinHandle<()>>();
1014     _assert_both::<Thread>();
1015 }
1016
1017 ////////////////////////////////////////////////////////////////////////////////
1018 // Tests
1019 ////////////////////////////////////////////////////////////////////////////////
1020
1021 #[cfg(all(test, not(target_os = "emscripten")))]
1022 mod tests {
1023     use any::Any;
1024     use sync::mpsc::{channel, Sender};
1025     use result;
1026     use super::{Builder};
1027     use thread;
1028     use time::Duration;
1029     use u32;
1030
1031     // !!! These tests are dangerous. If something is buggy, they will hang, !!!
1032     // !!! instead of exiting cleanly. This might wedge the buildbots.       !!!
1033
1034     #[test]
1035     fn test_unnamed_thread() {
1036         thread::spawn(move|| {
1037             assert!(thread::current().name().is_none());
1038         }).join().ok().unwrap();
1039     }
1040
1041     #[test]
1042     fn test_named_thread() {
1043         Builder::new().name("ada lovelace".to_string()).spawn(move|| {
1044             assert!(thread::current().name().unwrap() == "ada lovelace".to_string());
1045         }).unwrap().join().unwrap();
1046     }
1047
1048     #[test]
1049     #[should_panic]
1050     fn test_invalid_named_thread() {
1051         let _ = Builder::new().name("ada l\0velace".to_string()).spawn(|| {});
1052     }
1053
1054     #[test]
1055     fn test_run_basic() {
1056         let (tx, rx) = channel();
1057         thread::spawn(move|| {
1058             tx.send(()).unwrap();
1059         });
1060         rx.recv().unwrap();
1061     }
1062
1063     #[test]
1064     fn test_join_panic() {
1065         match thread::spawn(move|| {
1066             panic!()
1067         }).join() {
1068             result::Result::Err(_) => (),
1069             result::Result::Ok(()) => panic!()
1070         }
1071     }
1072
1073     #[test]
1074     fn test_spawn_sched() {
1075         let (tx, rx) = channel();
1076
1077         fn f(i: i32, tx: Sender<()>) {
1078             let tx = tx.clone();
1079             thread::spawn(move|| {
1080                 if i == 0 {
1081                     tx.send(()).unwrap();
1082                 } else {
1083                     f(i - 1, tx);
1084                 }
1085             });
1086
1087         }
1088         f(10, tx);
1089         rx.recv().unwrap();
1090     }
1091
1092     #[test]
1093     fn test_spawn_sched_childs_on_default_sched() {
1094         let (tx, rx) = channel();
1095
1096         thread::spawn(move|| {
1097             thread::spawn(move|| {
1098                 tx.send(()).unwrap();
1099             });
1100         });
1101
1102         rx.recv().unwrap();
1103     }
1104
1105     fn avoid_copying_the_body<F>(spawnfn: F) where F: FnOnce(Box<Fn() + Send>) {
1106         let (tx, rx) = channel();
1107
1108         let x: Box<_> = box 1;
1109         let x_in_parent = (&*x) as *const i32 as usize;
1110
1111         spawnfn(Box::new(move|| {
1112             let x_in_child = (&*x) as *const i32 as usize;
1113             tx.send(x_in_child).unwrap();
1114         }));
1115
1116         let x_in_child = rx.recv().unwrap();
1117         assert_eq!(x_in_parent, x_in_child);
1118     }
1119
1120     #[test]
1121     fn test_avoid_copying_the_body_spawn() {
1122         avoid_copying_the_body(|v| {
1123             thread::spawn(move || v());
1124         });
1125     }
1126
1127     #[test]
1128     fn test_avoid_copying_the_body_thread_spawn() {
1129         avoid_copying_the_body(|f| {
1130             thread::spawn(move|| {
1131                 f();
1132             });
1133         })
1134     }
1135
1136     #[test]
1137     fn test_avoid_copying_the_body_join() {
1138         avoid_copying_the_body(|f| {
1139             let _ = thread::spawn(move|| {
1140                 f()
1141             }).join();
1142         })
1143     }
1144
1145     #[test]
1146     fn test_child_doesnt_ref_parent() {
1147         // If the child refcounts the parent thread, this will stack overflow when
1148         // climbing the thread tree to dereference each ancestor. (See #1789)
1149         // (well, it would if the constant were 8000+ - I lowered it to be more
1150         // valgrind-friendly. try this at home, instead..!)
1151         const GENERATIONS: u32 = 16;
1152         fn child_no(x: u32) -> Box<Fn() + Send> {
1153             return Box::new(move|| {
1154                 if x < GENERATIONS {
1155                     thread::spawn(move|| child_no(x+1)());
1156                 }
1157             });
1158         }
1159         thread::spawn(|| child_no(0)());
1160     }
1161
1162     #[test]
1163     fn test_simple_newsched_spawn() {
1164         thread::spawn(move || {});
1165     }
1166
1167     #[test]
1168     fn test_try_panic_message_static_str() {
1169         match thread::spawn(move|| {
1170             panic!("static string");
1171         }).join() {
1172             Err(e) => {
1173                 type T = &'static str;
1174                 assert!(e.is::<T>());
1175                 assert_eq!(*e.downcast::<T>().unwrap(), "static string");
1176             }
1177             Ok(()) => panic!()
1178         }
1179     }
1180
1181     #[test]
1182     fn test_try_panic_message_owned_str() {
1183         match thread::spawn(move|| {
1184             panic!("owned string".to_string());
1185         }).join() {
1186             Err(e) => {
1187                 type T = String;
1188                 assert!(e.is::<T>());
1189                 assert_eq!(*e.downcast::<T>().unwrap(), "owned string".to_string());
1190             }
1191             Ok(()) => panic!()
1192         }
1193     }
1194
1195     #[test]
1196     fn test_try_panic_message_any() {
1197         match thread::spawn(move|| {
1198             panic!(box 413u16 as Box<Any + Send>);
1199         }).join() {
1200             Err(e) => {
1201                 type T = Box<Any + Send>;
1202                 assert!(e.is::<T>());
1203                 let any = e.downcast::<T>().unwrap();
1204                 assert!(any.is::<u16>());
1205                 assert_eq!(*any.downcast::<u16>().unwrap(), 413);
1206             }
1207             Ok(()) => panic!()
1208         }
1209     }
1210
1211     #[test]
1212     fn test_try_panic_message_unit_struct() {
1213         struct Juju;
1214
1215         match thread::spawn(move|| {
1216             panic!(Juju)
1217         }).join() {
1218             Err(ref e) if e.is::<Juju>() => {}
1219             Err(_) | Ok(()) => panic!()
1220         }
1221     }
1222
1223     #[test]
1224     fn test_park_timeout_unpark_before() {
1225         for _ in 0..10 {
1226             thread::current().unpark();
1227             thread::park_timeout(Duration::from_millis(u32::MAX as u64));
1228         }
1229     }
1230
1231     #[test]
1232     fn test_park_timeout_unpark_not_called() {
1233         for _ in 0..10 {
1234             thread::park_timeout(Duration::from_millis(10));
1235         }
1236     }
1237
1238     #[test]
1239     fn test_park_timeout_unpark_called_other_thread() {
1240         for _ in 0..10 {
1241             let th = thread::current();
1242
1243             let _guard = thread::spawn(move || {
1244                 super::sleep(Duration::from_millis(50));
1245                 th.unpark();
1246             });
1247
1248             thread::park_timeout(Duration::from_millis(u32::MAX as u64));
1249         }
1250     }
1251
1252     #[test]
1253     fn sleep_ms_smoke() {
1254         thread::sleep(Duration::from_millis(2));
1255     }
1256
1257     #[test]
1258     fn test_thread_id_equal() {
1259         assert!(thread::current().id() == thread::current().id());
1260     }
1261
1262     #[test]
1263     fn test_thread_id_not_equal() {
1264         let spawned_id = thread::spawn(|| thread::current().id()).join().unwrap();
1265         assert!(thread::current().id() != spawned_id);
1266     }
1267
1268     // NOTE: the corresponding test for stderr is in run-pass/thread-stderr, due
1269     // to the test harness apparently interfering with stderr configuration.
1270 }