]> git.proxmox.com Git - rustc.git/blob - src/libstd/thread/mod.rs
New upstream version 1.13.0+dfsg1
[rustc.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](../../std/sync/mpsc/index.html), Rust's message-passing
21 //! types, along with [other forms of thread
22 //! synchronization](../../std/sync/index.html) and shared-memory data
23 //! structures. In particular, types that are guaranteed to be
24 //! threadsafe are easily shared between threads using the
25 //! atomically-reference-counted container,
26 //! [`Arc`](../../std/sync/struct.Arc.html).
27 //!
28 //! Fatal logic errors in Rust cause *thread panic*, during which
29 //! a thread will unwind the stack, running destructors and freeing
30 //! owned resources. Thread panic is unrecoverable from within
31 //! the panicking thread (i.e. there is no 'try/catch' in Rust), but
32 //! the panic may optionally be detected from a different thread. If
33 //! the main thread panics, the application will exit with a non-zero
34 //! exit code.
35 //!
36 //! When the main thread of a Rust program terminates, the entire program shuts
37 //! down, even if other threads are still running. However, this module provides
38 //! convenient facilities for automatically waiting for the termination of a
39 //! child thread (i.e., join).
40 //!
41 //! ## Spawning a thread
42 //!
43 //! A new thread can be spawned using the `thread::spawn` function:
44 //!
45 //! ```rust
46 //! use std::thread;
47 //!
48 //! thread::spawn(move || {
49 //! // some work here
50 //! });
51 //! ```
52 //!
53 //! In this example, the spawned thread is "detached" from the current
54 //! thread. This means that it can outlive its parent (the thread that spawned
55 //! it), unless this parent is the main thread.
56 //!
57 //! The parent thread can also wait on the completion of the child
58 //! thread; a call to `spawn` produces a `JoinHandle`, which provides
59 //! a `join` method for waiting:
60 //!
61 //! ```rust
62 //! use std::thread;
63 //!
64 //! let child = thread::spawn(move || {
65 //! // some work here
66 //! });
67 //! // some work here
68 //! let res = child.join();
69 //! ```
70 //!
71 //! The `join` method returns a `Result` containing `Ok` of the final
72 //! value produced by the child thread, or `Err` of the value given to
73 //! a call to `panic!` if the child panicked.
74 //!
75 //! ## Configuring threads
76 //!
77 //! A new thread can be configured before it is spawned via the `Builder` type,
78 //! which currently allows you to set the name and stack size for the child thread:
79 //!
80 //! ```rust
81 //! # #![allow(unused_must_use)]
82 //! use std::thread;
83 //!
84 //! thread::Builder::new().name("child1".to_string()).spawn(move || {
85 //! println!("Hello, world!");
86 //! });
87 //! ```
88 //!
89 //! ## The `Thread` type
90 //!
91 //! Threads are represented via the `Thread` type, which you can get in one of
92 //! two ways:
93 //!
94 //! * By spawning a new thread, e.g. using the `thread::spawn` function, and
95 //! calling `thread()` on the `JoinHandle`.
96 //! * By requesting the current thread, using the `thread::current` function.
97 //!
98 //! The `thread::current()` function is available even for threads not spawned
99 //! by the APIs of this module.
100 //!
101 //! ## Blocking support: park and unpark
102 //!
103 //! Every thread is equipped with some basic low-level blocking support, via the
104 //! `thread::park()` function and `thread::Thread::unpark()` method. `park()`
105 //! blocks the current thread, which can then be resumed from another thread by
106 //! calling the `unpark()` method on the blocked thread's handle.
107 //!
108 //! Conceptually, each `Thread` handle has an associated token, which is
109 //! initially not present:
110 //!
111 //! * The `thread::park()` function blocks the current thread unless or until
112 //! the token is available for its thread handle, at which point it atomically
113 //! consumes the token. It may also return *spuriously*, without consuming the
114 //! token. `thread::park_timeout()` does the same, but allows specifying a
115 //! maximum time to block the thread for.
116 //!
117 //! * The `unpark()` method on a `Thread` atomically makes the token available
118 //! if it wasn't already.
119 //!
120 //! In other words, each `Thread` acts a bit like a semaphore with initial count
121 //! 0, except that the semaphore is *saturating* (the count cannot go above 1),
122 //! and can return spuriously.
123 //!
124 //! The API is typically used by acquiring a handle to the current thread,
125 //! placing that handle in a shared data structure so that other threads can
126 //! find it, and then `park`ing. When some desired condition is met, another
127 //! thread calls `unpark` on the handle.
128 //!
129 //! The motivation for this design is twofold:
130 //!
131 //! * It avoids the need to allocate mutexes and condvars when building new
132 //! synchronization primitives; the threads already provide basic blocking/signaling.
133 //!
134 //! * It can be implemented very efficiently on many platforms.
135 //!
136 //! ## Thread-local storage
137 //!
138 //! This module also provides an implementation of thread-local storage for Rust
139 //! programs. Thread-local storage is a method of storing data into a global
140 //! variable that each thread in the program will have its own copy of.
141 //! Threads do not share this data, so accesses do not need to be synchronized.
142 //!
143 //! A thread-local key owns the value it contains and will destroy the value when the
144 //! thread exits. It is created with the [`thread_local!`] macro and can contain any
145 //! value that is `'static` (no borrowed pointers). It provides an accessor function,
146 //! [`with`], that yields a shared reference to the value to the specified
147 //! closure. Thread-local keys allow only shared access to values, as there would be no
148 //! way to guarantee uniqueness if mutable borrows were allowed. Most values
149 //! will want to make use of some form of **interior mutability** through the
150 //! [`Cell`] or [`RefCell`] types.
151 //!
152 //! [`Cell`]: ../cell/struct.Cell.html
153 //! [`RefCell`]: ../cell/struct.RefCell.html
154 //! [`thread_local!`]: ../macro.thread_local!.html
155 //! [`with`]: struct.LocalKey.html#method.with
156
157 #![stable(feature = "rust1", since = "1.0.0")]
158
159 use any::Any;
160 use cell::UnsafeCell;
161 use ffi::{CStr, CString};
162 use fmt;
163 use io;
164 use panic;
165 use panicking;
166 use str;
167 use sync::{Mutex, Condvar, Arc};
168 use sys::thread as imp;
169 use sys_common::thread_info;
170 use sys_common::util;
171 use sys_common::{AsInner, IntoInner};
172 use time::Duration;
173
174 ////////////////////////////////////////////////////////////////////////////////
175 // Thread-local storage
176 ////////////////////////////////////////////////////////////////////////////////
177
178 #[macro_use] mod local;
179
180 #[stable(feature = "rust1", since = "1.0.0")]
181 pub use self::local::{LocalKey, LocalKeyState};
182
183 #[unstable(feature = "libstd_thread_internals", issue = "0")]
184 #[cfg(target_thread_local)]
185 #[doc(hidden)] pub use self::local::elf::Key as __ElfLocalKeyInner;
186 #[unstable(feature = "libstd_thread_internals", issue = "0")]
187 #[doc(hidden)] pub use self::local::os::Key as __OsLocalKeyInner;
188
189 ////////////////////////////////////////////////////////////////////////////////
190 // Builder
191 ////////////////////////////////////////////////////////////////////////////////
192
193 /// Thread configuration. Provides detailed control over the properties
194 /// and behavior of new threads.
195 #[stable(feature = "rust1", since = "1.0.0")]
196 pub struct Builder {
197 // A name for the thread-to-be, for identification in panic messages
198 name: Option<String>,
199 // The size of the stack for the spawned thread
200 stack_size: Option<usize>,
201 }
202
203 impl Builder {
204 /// Generates the base configuration for spawning a thread, from which
205 /// configuration methods can be chained.
206 #[stable(feature = "rust1", since = "1.0.0")]
207 pub fn new() -> Builder {
208 Builder {
209 name: None,
210 stack_size: None,
211 }
212 }
213
214 /// Names the thread-to-be. Currently the name is used for identification
215 /// only in panic messages.
216 ///
217 /// # Examples
218 ///
219 /// ```rust
220 /// use std::thread;
221 ///
222 /// let builder = thread::Builder::new()
223 /// .name("foo".into());
224 ///
225 /// let handler = builder.spawn(|| {
226 /// assert_eq!(thread::current().name(), Some("foo"))
227 /// }).unwrap();
228 ///
229 /// handler.join().unwrap();
230 /// ```
231 #[stable(feature = "rust1", since = "1.0.0")]
232 pub fn name(mut self, name: String) -> Builder {
233 self.name = Some(name);
234 self
235 }
236
237 /// Sets the size of the stack for the new thread.
238 #[stable(feature = "rust1", since = "1.0.0")]
239 pub fn stack_size(mut self, size: usize) -> Builder {
240 self.stack_size = Some(size);
241 self
242 }
243
244 /// Spawns a new thread, and returns a join handle for it.
245 ///
246 /// The child thread may outlive the parent (unless the parent thread
247 /// is the main thread; the whole process is terminated when the main
248 /// thread finishes). The join handle can be used to block on
249 /// termination of the child thread, including recovering its panics.
250 ///
251 /// # Errors
252 ///
253 /// Unlike the `spawn` free function, this method yields an
254 /// `io::Result` to capture any failure to create the thread at
255 /// the OS level.
256 #[stable(feature = "rust1", since = "1.0.0")]
257 pub fn spawn<F, T>(self, f: F) -> io::Result<JoinHandle<T>> where
258 F: FnOnce() -> T, F: Send + 'static, T: Send + 'static
259 {
260 let Builder { name, stack_size } = self;
261
262 let stack_size = stack_size.unwrap_or(util::min_stack());
263
264 let my_thread = Thread::new(name);
265 let their_thread = my_thread.clone();
266
267 let my_packet : Arc<UnsafeCell<Option<Result<T>>>>
268 = Arc::new(UnsafeCell::new(None));
269 let their_packet = my_packet.clone();
270
271 let main = move || {
272 if let Some(name) = their_thread.cname() {
273 imp::Thread::set_name(name);
274 }
275 unsafe {
276 thread_info::set(imp::guard::current(), their_thread);
277 let try_result = panic::catch_unwind(panic::AssertUnwindSafe(f));
278 *their_packet.get() = Some(try_result);
279 }
280 };
281
282 Ok(JoinHandle(JoinInner {
283 native: unsafe {
284 Some(imp::Thread::new(stack_size, Box::new(main))?)
285 },
286 thread: my_thread,
287 packet: Packet(my_packet),
288 }))
289 }
290 }
291
292 ////////////////////////////////////////////////////////////////////////////////
293 // Free functions
294 ////////////////////////////////////////////////////////////////////////////////
295
296 /// Spawns a new thread, returning a `JoinHandle` for it.
297 ///
298 /// The join handle will implicitly *detach* the child thread upon being
299 /// dropped. In this case, the child thread may outlive the parent (unless
300 /// the parent thread is the main thread; the whole process is terminated when
301 /// the main thread finishes.) Additionally, the join handle provides a `join`
302 /// method that can be used to join the child thread. If the child thread
303 /// panics, `join` will return an `Err` containing the argument given to
304 /// `panic`.
305 ///
306 /// # Panics
307 ///
308 /// Panics if the OS fails to create a thread; use `Builder::spawn`
309 /// to recover from such errors.
310 #[stable(feature = "rust1", since = "1.0.0")]
311 pub fn spawn<F, T>(f: F) -> JoinHandle<T> where
312 F: FnOnce() -> T, F: Send + 'static, T: Send + 'static
313 {
314 Builder::new().spawn(f).unwrap()
315 }
316
317 /// Gets a handle to the thread that invokes it.
318 ///
319 /// #Examples
320 ///
321 /// Getting a handle to the current thread with `thread::current()`:
322 ///
323 /// ```
324 /// use std::thread;
325 ///
326 /// let handler = thread::Builder::new()
327 /// .name("named thread".into())
328 /// .spawn(|| {
329 /// let handle = thread::current();
330 /// assert_eq!(handle.name(), Some("named thread"));
331 /// })
332 /// .unwrap();
333 ///
334 /// handler.join().unwrap();
335 /// ```
336 #[stable(feature = "rust1", since = "1.0.0")]
337 pub fn current() -> Thread {
338 thread_info::current_thread().expect("use of std::thread::current() is not \
339 possible after the thread's local \
340 data has been destroyed")
341 }
342
343 /// Cooperatively gives up a timeslice to the OS scheduler.
344 #[stable(feature = "rust1", since = "1.0.0")]
345 pub fn yield_now() {
346 imp::Thread::yield_now()
347 }
348
349 /// Determines whether the current thread is unwinding because of panic.
350 ///
351 /// # Examples
352 ///
353 /// ```rust,should_panic
354 /// use std::thread;
355 ///
356 /// struct SomeStruct;
357 ///
358 /// impl Drop for SomeStruct {
359 /// fn drop(&mut self) {
360 /// if thread::panicking() {
361 /// println!("dropped while unwinding");
362 /// } else {
363 /// println!("dropped while not unwinding");
364 /// }
365 /// }
366 /// }
367 ///
368 /// {
369 /// print!("a: ");
370 /// let a = SomeStruct;
371 /// }
372 ///
373 /// {
374 /// print!("b: ");
375 /// let b = SomeStruct;
376 /// panic!()
377 /// }
378 /// ```
379 #[inline]
380 #[stable(feature = "rust1", since = "1.0.0")]
381 pub fn panicking() -> bool {
382 panicking::panicking()
383 }
384
385 /// Puts the current thread to sleep for the specified amount of time.
386 ///
387 /// The thread may sleep longer than the duration specified due to scheduling
388 /// specifics or platform-dependent functionality. Note that on unix platforms
389 /// this function will not return early due to a signal being received or a
390 /// spurious wakeup.
391 #[stable(feature = "rust1", since = "1.0.0")]
392 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::sleep`")]
393 pub fn sleep_ms(ms: u32) {
394 sleep(Duration::from_millis(ms as u64))
395 }
396
397 /// Puts the current thread to sleep for the specified amount of time.
398 ///
399 /// The thread may sleep longer than the duration specified due to scheduling
400 /// specifics or platform-dependent functionality.
401 ///
402 /// # Platform behavior
403 ///
404 /// On Unix platforms this function will not return early due to a
405 /// signal being received or a spurious wakeup. Platforms which do not support
406 /// nanosecond precision for sleeping will have `dur` rounded up to the nearest
407 /// granularity of time they can sleep for.
408 ///
409 /// # Examples
410 ///
411 /// ```rust,no_run
412 /// use std::{thread, time};
413 ///
414 /// let ten_millis = time::Duration::from_millis(10);
415 /// let now = time::Instant::now();
416 ///
417 /// thread::sleep(ten_millis);
418 ///
419 /// assert!(now.elapsed() >= ten_millis);
420 /// ```
421 #[stable(feature = "thread_sleep", since = "1.4.0")]
422 pub fn sleep(dur: Duration) {
423 imp::Thread::sleep(dur)
424 }
425
426 /// Blocks unless or until the current thread's token is made available.
427 ///
428 /// Every thread is equipped with some basic low-level blocking support, via
429 /// the `park()` function and the [`unpark()`][unpark] method. These can be
430 /// used as a more CPU-efficient implementation of a spinlock.
431 ///
432 /// [unpark]: struct.Thread.html#method.unpark
433 ///
434 /// The API is typically used by acquiring a handle to the current thread,
435 /// placing that handle in a shared data structure so that other threads can
436 /// find it, and then parking (in a loop with a check for the token actually
437 /// being acquired).
438 ///
439 /// A call to `park` does not guarantee that the thread will remain parked
440 /// forever, and callers should be prepared for this possibility.
441 ///
442 /// See the [module documentation][thread] for more detail.
443 ///
444 /// [thread]: index.html
445 //
446 // The implementation currently uses the trivial strategy of a Mutex+Condvar
447 // with wakeup flag, which does not actually allow spurious wakeups. In the
448 // future, this will be implemented in a more efficient way, perhaps along the lines of
449 // http://cr.openjdk.java.net/~stefank/6989984.1/raw_files/new/src/os/linux/vm/os_linux.cpp
450 // or futuxes, and in either case may allow spurious wakeups.
451 #[stable(feature = "rust1", since = "1.0.0")]
452 pub fn park() {
453 let thread = current();
454 let mut guard = thread.inner.lock.lock().unwrap();
455 while !*guard {
456 guard = thread.inner.cvar.wait(guard).unwrap();
457 }
458 *guard = false;
459 }
460
461 /// Use [park_timeout].
462 ///
463 /// Blocks unless or until the current thread's token is made available or
464 /// the specified duration has been reached (may wake spuriously).
465 ///
466 /// The semantics of this function are equivalent to `park()` except that the
467 /// thread will be blocked for roughly no longer than `ms`. This method
468 /// should not be used for precise timing due to anomalies such as
469 /// preemption or platform differences that may not cause the maximum
470 /// amount of time waited to be precisely `ms` long.
471 ///
472 /// See the [module documentation][thread] for more detail.
473 ///
474 /// [thread]: index.html
475 /// [park_timeout]: fn.park_timeout.html
476 #[stable(feature = "rust1", since = "1.0.0")]
477 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::park_timeout`")]
478 pub fn park_timeout_ms(ms: u32) {
479 park_timeout(Duration::from_millis(ms as u64))
480 }
481
482 /// Blocks unless or until the current thread's token is made available or
483 /// the specified duration has been reached (may wake spuriously).
484 ///
485 /// The semantics of this function are equivalent to `park()` except that the
486 /// thread will be blocked for roughly no longer than `dur`. This method
487 /// should not be used for precise timing due to anomalies such as
488 /// preemption or platform differences that may not cause the maximum
489 /// amount of time waited to be precisely `dur` long.
490 ///
491 /// See the module doc for more detail.
492 ///
493 /// # Platform behavior
494 ///
495 /// Platforms which do not support nanosecond precision for sleeping will have
496 /// `dur` rounded up to the nearest granularity of time they can sleep for.
497 ///
498 /// # Example
499 ///
500 /// Waiting for the complete expiration of the timeout:
501 ///
502 /// ```rust,no_run
503 /// use std::thread::park_timeout;
504 /// use std::time::{Instant, Duration};
505 ///
506 /// let timeout = Duration::from_secs(2);
507 /// let beginning_park = Instant::now();
508 /// park_timeout(timeout);
509 ///
510 /// while beginning_park.elapsed() < timeout {
511 /// println!("restarting park_timeout after {:?}", beginning_park.elapsed());
512 /// let timeout = timeout - beginning_park.elapsed();
513 /// park_timeout(timeout);
514 /// }
515 /// ```
516 #[stable(feature = "park_timeout", since = "1.4.0")]
517 pub fn park_timeout(dur: Duration) {
518 let thread = current();
519 let mut guard = thread.inner.lock.lock().unwrap();
520 if !*guard {
521 let (g, _) = thread.inner.cvar.wait_timeout(guard, dur).unwrap();
522 guard = g;
523 }
524 *guard = false;
525 }
526
527 ////////////////////////////////////////////////////////////////////////////////
528 // Thread
529 ////////////////////////////////////////////////////////////////////////////////
530
531 /// The internal representation of a `Thread` handle
532 struct Inner {
533 name: Option<CString>, // Guaranteed to be UTF-8
534 lock: Mutex<bool>, // true when there is a buffered unpark
535 cvar: Condvar,
536 }
537
538 #[derive(Clone)]
539 #[stable(feature = "rust1", since = "1.0.0")]
540 /// A handle to a thread.
541 pub struct Thread {
542 inner: Arc<Inner>,
543 }
544
545 impl Thread {
546 // Used only internally to construct a thread object without spawning
547 fn new(name: Option<String>) -> Thread {
548 let cname = name.map(|n| {
549 CString::new(n).expect("thread name may not contain interior null bytes")
550 });
551 Thread {
552 inner: Arc::new(Inner {
553 name: cname,
554 lock: Mutex::new(false),
555 cvar: Condvar::new(),
556 })
557 }
558 }
559
560 /// Atomically makes the handle's token available if it is not already.
561 ///
562 /// See the module doc for more detail.
563 #[stable(feature = "rust1", since = "1.0.0")]
564 pub fn unpark(&self) {
565 let mut guard = self.inner.lock.lock().unwrap();
566 if !*guard {
567 *guard = true;
568 self.inner.cvar.notify_one();
569 }
570 }
571
572 /// Gets the thread's name.
573 ///
574 /// # Examples
575 ///
576 /// Threads by default have no name specified:
577 ///
578 /// ```
579 /// use std::thread;
580 ///
581 /// let builder = thread::Builder::new();
582 ///
583 /// let handler = builder.spawn(|| {
584 /// assert!(thread::current().name().is_none());
585 /// }).unwrap();
586 ///
587 /// handler.join().unwrap();
588 /// ```
589 ///
590 /// Thread with a specified name:
591 ///
592 /// ```
593 /// use std::thread;
594 ///
595 /// let builder = thread::Builder::new()
596 /// .name("foo".into());
597 ///
598 /// let handler = builder.spawn(|| {
599 /// assert_eq!(thread::current().name(), Some("foo"))
600 /// }).unwrap();
601 ///
602 /// handler.join().unwrap();
603 /// ```
604 #[stable(feature = "rust1", since = "1.0.0")]
605 pub fn name(&self) -> Option<&str> {
606 self.cname().map(|s| unsafe { str::from_utf8_unchecked(s.to_bytes()) } )
607 }
608
609 fn cname(&self) -> Option<&CStr> {
610 self.inner.name.as_ref().map(|s| &**s)
611 }
612 }
613
614 #[stable(feature = "rust1", since = "1.0.0")]
615 impl fmt::Debug for Thread {
616 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
617 fmt::Debug::fmt(&self.name(), f)
618 }
619 }
620
621 // a hack to get around privacy restrictions
622 impl thread_info::NewThread for Thread {
623 fn new(name: Option<String>) -> Thread { Thread::new(name) }
624 }
625
626 ////////////////////////////////////////////////////////////////////////////////
627 // JoinHandle
628 ////////////////////////////////////////////////////////////////////////////////
629
630 /// Indicates the manner in which a thread exited.
631 ///
632 /// A thread that completes without panicking is considered to exit successfully.
633 #[stable(feature = "rust1", since = "1.0.0")]
634 pub type Result<T> = ::result::Result<T, Box<Any + Send + 'static>>;
635
636 // This packet is used to communicate the return value between the child thread
637 // and the parent thread. Memory is shared through the `Arc` within and there's
638 // no need for a mutex here because synchronization happens with `join()` (the
639 // parent thread never reads this packet until the child has exited).
640 //
641 // This packet itself is then stored into a `JoinInner` which in turns is placed
642 // in `JoinHandle` and `JoinGuard`. Due to the usage of `UnsafeCell` we need to
643 // manually worry about impls like Send and Sync. The type `T` should
644 // already always be Send (otherwise the thread could not have been created) and
645 // this type is inherently Sync because no methods take &self. Regardless,
646 // however, we add inheriting impls for Send/Sync to this type to ensure it's
647 // Send/Sync and that future modifications will still appropriately classify it.
648 struct Packet<T>(Arc<UnsafeCell<Option<Result<T>>>>);
649
650 unsafe impl<T: Send> Send for Packet<T> {}
651 unsafe impl<T: Sync> Sync for Packet<T> {}
652
653 /// Inner representation for JoinHandle
654 struct JoinInner<T> {
655 native: Option<imp::Thread>,
656 thread: Thread,
657 packet: Packet<T>,
658 }
659
660 impl<T> JoinInner<T> {
661 fn join(&mut self) -> Result<T> {
662 self.native.take().unwrap().join();
663 unsafe {
664 (*self.packet.0.get()).take().unwrap()
665 }
666 }
667 }
668
669 /// An owned permission to join on a thread (block on its termination).
670 ///
671 /// A `JoinHandle` *detaches* the child thread when it is dropped.
672 ///
673 /// Due to platform restrictions, it is not possible to `Clone` this
674 /// handle: the ability to join a child thread is a uniquely-owned
675 /// permission.
676 ///
677 /// This `struct` is created by the [`thread::spawn`] function and the
678 /// [`thread::Builder::spawn`] method.
679 ///
680 /// # Examples
681 ///
682 /// Creation from [`thread::spawn`]:
683 ///
684 /// ```rust
685 /// use std::thread;
686 ///
687 /// let join_handle: thread::JoinHandle<_> = thread::spawn(|| {
688 /// // some work here
689 /// });
690 /// ```
691 ///
692 /// Creation from [`thread::Builder::spawn`]:
693 ///
694 /// ```rust
695 /// use std::thread;
696 ///
697 /// let builder = thread::Builder::new();
698 ///
699 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
700 /// // some work here
701 /// }).unwrap();
702 /// ```
703 ///
704 /// [`thread::spawn`]: fn.spawn.html
705 /// [`thread::Builder::spawn`]: struct.Builder.html#method.spawn
706 #[stable(feature = "rust1", since = "1.0.0")]
707 pub struct JoinHandle<T>(JoinInner<T>);
708
709 impl<T> JoinHandle<T> {
710 /// Extracts a handle to the underlying thread
711 #[stable(feature = "rust1", since = "1.0.0")]
712 pub fn thread(&self) -> &Thread {
713 &self.0.thread
714 }
715
716 /// Waits for the associated thread to finish.
717 ///
718 /// If the child thread panics, `Err` is returned with the parameter given
719 /// to `panic`.
720 #[stable(feature = "rust1", since = "1.0.0")]
721 pub fn join(mut self) -> Result<T> {
722 self.0.join()
723 }
724 }
725
726 impl<T> AsInner<imp::Thread> for JoinHandle<T> {
727 fn as_inner(&self) -> &imp::Thread { self.0.native.as_ref().unwrap() }
728 }
729
730 impl<T> IntoInner<imp::Thread> for JoinHandle<T> {
731 fn into_inner(self) -> imp::Thread { self.0.native.unwrap() }
732 }
733
734 fn _assert_sync_and_send() {
735 fn _assert_both<T: Send + Sync>() {}
736 _assert_both::<JoinHandle<()>>();
737 _assert_both::<Thread>();
738 }
739
740 ////////////////////////////////////////////////////////////////////////////////
741 // Tests
742 ////////////////////////////////////////////////////////////////////////////////
743
744 #[cfg(test)]
745 mod tests {
746 use any::Any;
747 use sync::mpsc::{channel, Sender};
748 use result;
749 use super::{Builder};
750 use thread;
751 use time::Duration;
752 use u32;
753
754 // !!! These tests are dangerous. If something is buggy, they will hang, !!!
755 // !!! instead of exiting cleanly. This might wedge the buildbots. !!!
756
757 #[test]
758 fn test_unnamed_thread() {
759 thread::spawn(move|| {
760 assert!(thread::current().name().is_none());
761 }).join().ok().unwrap();
762 }
763
764 #[test]
765 fn test_named_thread() {
766 Builder::new().name("ada lovelace".to_string()).spawn(move|| {
767 assert!(thread::current().name().unwrap() == "ada lovelace".to_string());
768 }).unwrap().join().unwrap();
769 }
770
771 #[test]
772 #[should_panic]
773 fn test_invalid_named_thread() {
774 let _ = Builder::new().name("ada l\0velace".to_string()).spawn(|| {});
775 }
776
777 #[test]
778 fn test_run_basic() {
779 let (tx, rx) = channel();
780 thread::spawn(move|| {
781 tx.send(()).unwrap();
782 });
783 rx.recv().unwrap();
784 }
785
786 #[test]
787 fn test_join_panic() {
788 match thread::spawn(move|| {
789 panic!()
790 }).join() {
791 result::Result::Err(_) => (),
792 result::Result::Ok(()) => panic!()
793 }
794 }
795
796 #[test]
797 fn test_spawn_sched() {
798 let (tx, rx) = channel();
799
800 fn f(i: i32, tx: Sender<()>) {
801 let tx = tx.clone();
802 thread::spawn(move|| {
803 if i == 0 {
804 tx.send(()).unwrap();
805 } else {
806 f(i - 1, tx);
807 }
808 });
809
810 }
811 f(10, tx);
812 rx.recv().unwrap();
813 }
814
815 #[test]
816 fn test_spawn_sched_childs_on_default_sched() {
817 let (tx, rx) = channel();
818
819 thread::spawn(move|| {
820 thread::spawn(move|| {
821 tx.send(()).unwrap();
822 });
823 });
824
825 rx.recv().unwrap();
826 }
827
828 fn avoid_copying_the_body<F>(spawnfn: F) where F: FnOnce(Box<Fn() + Send>) {
829 let (tx, rx) = channel();
830
831 let x: Box<_> = box 1;
832 let x_in_parent = (&*x) as *const i32 as usize;
833
834 spawnfn(Box::new(move|| {
835 let x_in_child = (&*x) as *const i32 as usize;
836 tx.send(x_in_child).unwrap();
837 }));
838
839 let x_in_child = rx.recv().unwrap();
840 assert_eq!(x_in_parent, x_in_child);
841 }
842
843 #[test]
844 fn test_avoid_copying_the_body_spawn() {
845 avoid_copying_the_body(|v| {
846 thread::spawn(move || v());
847 });
848 }
849
850 #[test]
851 fn test_avoid_copying_the_body_thread_spawn() {
852 avoid_copying_the_body(|f| {
853 thread::spawn(move|| {
854 f();
855 });
856 })
857 }
858
859 #[test]
860 fn test_avoid_copying_the_body_join() {
861 avoid_copying_the_body(|f| {
862 let _ = thread::spawn(move|| {
863 f()
864 }).join();
865 })
866 }
867
868 #[test]
869 fn test_child_doesnt_ref_parent() {
870 // If the child refcounts the parent thread, this will stack overflow when
871 // climbing the thread tree to dereference each ancestor. (See #1789)
872 // (well, it would if the constant were 8000+ - I lowered it to be more
873 // valgrind-friendly. try this at home, instead..!)
874 const GENERATIONS: u32 = 16;
875 fn child_no(x: u32) -> Box<Fn() + Send> {
876 return Box::new(move|| {
877 if x < GENERATIONS {
878 thread::spawn(move|| child_no(x+1)());
879 }
880 });
881 }
882 thread::spawn(|| child_no(0)());
883 }
884
885 #[test]
886 fn test_simple_newsched_spawn() {
887 thread::spawn(move || {});
888 }
889
890 #[test]
891 fn test_try_panic_message_static_str() {
892 match thread::spawn(move|| {
893 panic!("static string");
894 }).join() {
895 Err(e) => {
896 type T = &'static str;
897 assert!(e.is::<T>());
898 assert_eq!(*e.downcast::<T>().unwrap(), "static string");
899 }
900 Ok(()) => panic!()
901 }
902 }
903
904 #[test]
905 fn test_try_panic_message_owned_str() {
906 match thread::spawn(move|| {
907 panic!("owned string".to_string());
908 }).join() {
909 Err(e) => {
910 type T = String;
911 assert!(e.is::<T>());
912 assert_eq!(*e.downcast::<T>().unwrap(), "owned string".to_string());
913 }
914 Ok(()) => panic!()
915 }
916 }
917
918 #[test]
919 fn test_try_panic_message_any() {
920 match thread::spawn(move|| {
921 panic!(box 413u16 as Box<Any + Send>);
922 }).join() {
923 Err(e) => {
924 type T = Box<Any + Send>;
925 assert!(e.is::<T>());
926 let any = e.downcast::<T>().unwrap();
927 assert!(any.is::<u16>());
928 assert_eq!(*any.downcast::<u16>().unwrap(), 413);
929 }
930 Ok(()) => panic!()
931 }
932 }
933
934 #[test]
935 fn test_try_panic_message_unit_struct() {
936 struct Juju;
937
938 match thread::spawn(move|| {
939 panic!(Juju)
940 }).join() {
941 Err(ref e) if e.is::<Juju>() => {}
942 Err(_) | Ok(()) => panic!()
943 }
944 }
945
946 #[test]
947 fn test_park_timeout_unpark_before() {
948 for _ in 0..10 {
949 thread::current().unpark();
950 thread::park_timeout(Duration::from_millis(u32::MAX as u64));
951 }
952 }
953
954 #[test]
955 fn test_park_timeout_unpark_not_called() {
956 for _ in 0..10 {
957 thread::park_timeout(Duration::from_millis(10));
958 }
959 }
960
961 #[test]
962 fn test_park_timeout_unpark_called_other_thread() {
963 for _ in 0..10 {
964 let th = thread::current();
965
966 let _guard = thread::spawn(move || {
967 super::sleep(Duration::from_millis(50));
968 th.unpark();
969 });
970
971 thread::park_timeout(Duration::from_millis(u32::MAX as u64));
972 }
973 }
974
975 #[test]
976 fn sleep_ms_smoke() {
977 thread::sleep(Duration::from_millis(2));
978 }
979
980 // NOTE: the corresponding test for stderr is in run-pass/thread-stderr, due
981 // to the test harness apparently interfering with stderr configuration.
982 }