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