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