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