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