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