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