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.
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.
13 //! ## The threading model
15 //! An executing Rust program consists of a collection of native OS threads,
16 //! each with their own stack and local state.
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).
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 //! panic may optionally be detected from a different thread. If
32 //! the main thread panics the application will exit with a non-zero
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), described below.
40 //! ## The `Thread` type
42 //! Already-running threads are represented via the `Thread` type, which you can
43 //! get in one of two ways:
45 //! * By spawning a new thread, e.g. using the `Thread::spawn` constructor;
46 //! * By requesting the current thread, using the `Thread::current` function.
48 //! Threads can be named, and provide some built-in support for low-level
49 //! synchronization described below.
51 //! The `Thread::current()` function is available even for threads not spawned
52 //! by the APIs of this module.
54 //! ## Spawning a thread
56 //! A new thread can be spawned using the `Thread::spawn` function:
59 //! use std::thread::Thread;
61 //! let thread = Thread::spawn(move || {
62 //! println!("Hello, World!");
63 //! // some computation here
67 //! The spawned thread is "detached" from the current thread, meaning that it
68 //! can outlive the thread that spawned it. (Note, however, that when the main
69 //! thread terminates all detached threads are terminated as well.) The returned
70 //! `Thread` handle can be used for low-level synchronization as described below.
74 //! Often a parent thread uses a child thread to perform some particular task,
75 //! and at some point must wait for the child to complete before continuing.
76 //! For this scenario, use the `scoped` constructor:
79 //! use std::thread::Thread;
81 //! let guard = Thread::scoped(move || {
82 //! println!("Hello, World!");
83 //! // some computation here
85 //! // do some other work in the meantime
86 //! let result = guard.join();
89 //! The `scoped` function doesn't return a `Thread` directly; instead, it
90 //! returns a *join guard* from which a `Thread` can be extracted. The join
91 //! guard is an RAII-style guard that will automatically join the child thread
92 //! (block until it terminates) when it is dropped. You can join the child
93 //! thread in advance by calling the `join` method on the guard, which will also
94 //! return the result produced by the thread. A handle to the thread itself is
95 //! available via the `thread` method on the join guard.
97 //! (Note: eventually, the `scoped` constructor will allow the parent and child
98 //! threads to data that lives on the parent thread's stack, but some language
99 //! changes are needed before this is possible.)
101 //! ## Configuring threads
103 //! A new thread can be configured before it is spawned via the `Builder` type,
104 //! which currently allows you to set the name, stack size, and writers for
105 //! `println!` and `panic!` for the child thread:
110 //! thread::Builder::new().name("child1".to_string()).spawn(move || {
111 //! println!("Hello, world!")
115 //! ## Blocking support: park and unpark
117 //! Every thread is equipped with some basic low-level blocking support, via the
118 //! `park` and `unpark` functions.
120 //! Conceptually, each `Thread` handle has an associated token, which is
121 //! initially not present:
123 //! * The `Thread::park()` function blocks the current thread unless or until
124 //! the token is available for its thread handle, at which point It atomically
125 //! consumes the token. It may also return *spuriously*, without consuming the
128 //! * The `unpark()` method on a `Thread` atomically makes the token available
129 //! if it wasn't already.
131 //! In other words, each `Thread` acts a bit like a semaphore with initial count
132 //! 0, except that the semaphore is *saturating* (the count cannot go above 1),
133 //! and can return spuriously.
135 //! The API is typically used by acquiring a handle to the current thread,
136 //! placing that handle in a shared data structure so that other threads can
137 //! find it, and then `park`ing. When some desired condition is met, another
138 //! thread calls `unpark` on the handle.
140 //! The motivation for this design is twofold:
142 //! * It avoids the need to allocate mutexes and condvars when building new
143 //! synchronization primitives; the threads already provide basic blocking/signaling.
145 //! * It can be implemented highly efficiently on many platforms.
151 use cell::UnsafeCell;
153 use marker::{Send, Sync};
154 use ops::{Drop, FnOnce};
155 use option::Option::{self, Some, None};
156 use result::Result::{Err, Ok};
157 use sync::{Mutex, Condvar, Arc};
160 use rt::{self, unwind};
161 use io::{Writer, stdio};
164 use sys::thread as imp;
165 use sys_common::{stack, thread_info};
167 /// Thread configuration. Provides detailed control over the properties
168 /// and behavior of new threads.
171 // A name for the thread-to-be, for identification in panic messages
172 name: Option<String>,
173 // The size of the stack for the spawned thread
174 stack_size: Option<uint>,
175 // Thread-local stdout
176 stdout: Option<Box<Writer + Send>>,
177 // Thread-local stderr
178 stderr: Option<Box<Writer + Send>>,
182 /// Generate the base configuration for spawning a thread, from which
183 /// configuration methods can be chained.
185 pub fn new() -> Builder {
194 /// Name the thread-to-be. Currently the name is used for identification
195 /// only in panic messages.
197 pub fn name(mut self, name: String) -> Builder {
198 self.name = Some(name);
202 /// Set the size of the stack for the new thread.
204 pub fn stack_size(mut self, size: uint) -> Builder {
205 self.stack_size = Some(size);
209 /// Redirect thread-local stdout.
210 #[experimental = "Will likely go away after proc removal"]
211 pub fn stdout(mut self, stdout: Box<Writer + Send>) -> Builder {
212 self.stdout = Some(stdout);
216 /// Redirect thread-local stderr.
217 #[experimental = "Will likely go away after proc removal"]
218 pub fn stderr(mut self, stderr: Box<Writer + Send>) -> Builder {
219 self.stderr = Some(stderr);
223 /// Spawn a new detached thread, and return a handle to it.
225 /// See `Thead::spawn` and the module doc for more details.
226 #[unstable = "may change with specifics of new Send semantics"]
227 pub fn spawn<F>(self, f: F) -> Thread where F: FnOnce(), F: Send + 'static {
228 let (native, thread) = self.spawn_inner(Thunk::new(f), Thunk::with_arg(|_| {}));
229 unsafe { imp::detach(native) };
233 /// Spawn a new child thread that must be joined within a given
234 /// scope, and return a `JoinGuard`.
236 /// See `Thead::scoped` and the module doc for more details.
237 #[unstable = "may change with specifics of new Send semantics"]
238 pub fn scoped<'a, T, F>(self, f: F) -> JoinGuard<'a, T> where
239 T: Send + 'a, F: FnOnce() -> T, F: Send + 'a
241 let my_packet = Packet(Arc::new(UnsafeCell::new(None)));
242 let their_packet = Packet(my_packet.0.clone());
243 let (native, thread) = self.spawn_inner(Thunk::new(f), Thunk::with_arg(move |: ret| unsafe {
244 *their_packet.0.get() = Some(ret);
255 fn spawn_inner<T: Send>(self, f: Thunk<(), T>, finish: Thunk<Result<T>, ()>)
256 -> (imp::rust_thread, Thread)
258 let Builder { name, stack_size, stdout, stderr } = self;
260 let stack_size = stack_size.unwrap_or(rt::min_stack());
261 let my_thread = Thread::new(name);
262 let their_thread = my_thread.clone();
264 // Spawning a new OS thread guarantees that __morestack will never get
265 // triggered, but we must manually set up the actual stack bounds once
266 // this function starts executing. This raises the lower limit by a bit
267 // because by the time that this function is executing we've already
268 // consumed at least a little bit of stack (we don't know the exact byte
269 // address at which our stack started).
270 let main = move |:| {
271 let something_around_the_top_of_the_stack = 1;
272 let addr = &something_around_the_top_of_the_stack as *const int;
273 let my_stack_top = addr as uint;
274 let my_stack_bottom = my_stack_top - stack_size + 1024;
276 stack::record_os_managed_stack_bounds(my_stack_bottom, my_stack_top);
279 (my_stack_bottom, my_stack_top),
280 unsafe { imp::guard::current() },
284 let mut output = None;
285 let f: Thunk<(), T> = if stdout.is_some() || stderr.is_some() {
286 Thunk::new(move |:| {
287 let _ = stdout.map(stdio::set_stdout);
288 let _ = stderr.map(stdio::set_stderr);
296 let ptr = &mut output;
298 // There are two primary reasons that general try/catch is
299 // unsafe. The first is that we do not support nested
300 // try/catch. The fact that this is happening in a newly-spawned
301 // thread suffices. The second is that unwinding while unwinding
302 // is not defined. We take care of that by having an
303 // 'unwinding' flag in the thread itself. For these reasons,
304 // this unsafety should be ok.
306 unwind::try(move || *ptr = Some(f.invoke(())))
309 finish.invoke(match (output, try_result) {
310 (Some(data), Ok(_)) => Ok(data),
311 (None, Err(cause)) => Err(cause),
316 (unsafe { imp::create(stack_size, Thunk::new(main)) }, my_thread)
321 name: Option<String>,
322 lock: Mutex<bool>, // true when there is a buffered unpark
326 unsafe impl Sync for Inner {}
330 /// A handle to a thread.
336 // Used only internally to construct a thread object without spawning
337 fn new(name: Option<String>) -> Thread {
339 inner: Arc::new(Inner {
341 lock: Mutex::new(false),
342 cvar: Condvar::new(),
347 /// Spawn a new detached thread, returning a handle to it.
349 /// The child thread may outlive the parent (unless the parent thread is the
350 /// main thread; the whole process is terminated when the main thread
351 /// finishes.) The thread handle can be used for low-level
352 /// synchronization. See the module documentation for additional details.
353 #[unstable = "may change with specifics of new Send semantics"]
354 pub fn spawn<F>(f: F) -> Thread where F: FnOnce(), F: Send + 'static {
355 Builder::new().spawn(f)
358 /// Spawn a new *scoped* thread, returning a `JoinGuard` for it.
360 /// The join guard can be used to explicitly join the child thread (via
361 /// `join`), returning `Result<T>`, or it will implicitly join the child
362 /// upon being dropped. Because the child thread may refer to data on the
363 /// current thread's stack (hence the "scoped" name), it cannot be detached;
364 /// it *must* be joined before the relevant stack frame is popped. See the
365 /// module documentation for additional details.
366 #[unstable = "may change with specifics of new Send semantics"]
367 pub fn scoped<'a, T, F>(f: F) -> JoinGuard<'a, T> where
368 T: Send + 'a, F: FnOnce() -> T, F: Send + 'a
370 Builder::new().scoped(f)
373 /// Gets a handle to the thread that invokes it.
375 pub fn current() -> Thread {
376 thread_info::current_thread()
379 /// Cooperatively give up a timeslice to the OS scheduler.
380 #[unstable = "name may change"]
382 unsafe { imp::yield_now() }
385 /// Determines whether the current thread is panicking.
388 pub fn panicking() -> bool {
392 /// Block unless or until the current thread's token is made available (may wake spuriously).
394 /// See the module doc for more detail.
396 // The implementation currently uses the trivial strategy of a Mutex+Condvar
397 // with wakeup flag, which does not actually allow spurious wakeups. In the
398 // future, this will be implemented in a more efficient way, perhaps along the lines of
399 // http://cr.openjdk.java.net/~stefank/6989984.1/raw_files/new/src/os/linux/vm/os_linux.cpp
400 // or futuxes, and in either case may allow spurious wakeups.
401 #[unstable = "recently introduced"]
403 let thread = Thread::current();
404 let mut guard = thread.inner.lock.lock().unwrap();
406 guard = thread.inner.cvar.wait(guard).unwrap();
411 /// Atomically makes the handle's token available if it is not already.
413 /// See the module doc for more detail.
414 #[unstable = "recently introduced"]
415 pub fn unpark(&self) {
416 let mut guard = self.inner.lock.lock().unwrap();
419 self.inner.cvar.notify_one();
423 /// Get the thread's name.
425 pub fn name(&self) -> Option<&str> {
426 self.inner.name.as_ref().map(|s| s.as_slice())
430 // a hack to get around privacy restrictions
431 impl thread_info::NewThread for Thread {
432 fn new(name: Option<String>) -> Thread { Thread::new(name) }
435 /// Indicates the manner in which a thread exited.
437 /// A thread that completes without panicking is considered to exit successfully.
439 pub type Result<T> = ::result::Result<T, Box<Any + Send>>;
441 struct Packet<T>(Arc<UnsafeCell<Option<Result<T>>>>);
443 unsafe impl<T:'static+Send> Send for Packet<T> {}
444 unsafe impl<T> Sync for Packet<T> {}
446 /// An RAII-style guard that will block until thread termination when dropped.
448 /// The type `T` is the return type for the thread's main function.
450 #[unstable = "may change with specifics of new Send semantics"]
451 pub struct JoinGuard<'a, T: 'a> {
452 native: imp::rust_thread,
459 unsafe impl<'a, T: Send + 'a> Sync for JoinGuard<'a, T> {}
461 impl<'a, T: Send + 'a> JoinGuard<'a, T> {
462 /// Extract a handle to the thread this guard will join on.
464 pub fn thread(&self) -> &Thread {
468 /// Wait for the associated thread to finish, returning the result of the thread's
471 /// If the child thread panics, `Err` is returned with the parameter given
474 pub fn join(mut self) -> Result<T> {
475 assert!(!self.joined);
476 unsafe { imp::join(self.native) };
479 (*self.packet.0.get()).take().unwrap()
484 impl<T: Send> JoinGuard<'static, T> {
485 /// Detaches the child thread, allowing it to outlive its parent.
486 #[experimental = "unsure whether this API imposes limitations elsewhere"]
487 pub fn detach(mut self) {
488 unsafe { imp::detach(self.native) };
489 self.joined = true; // avoid joining in the destructor
495 impl<'a, T: Send + 'a> Drop for JoinGuard<'a, T> {
498 unsafe { imp::join(self.native) };
508 use sync::mpsc::{channel, Sender};
511 use std::io::{ChanReader, ChanWriter};
512 use super::{Thread, Builder};
515 // !!! These tests are dangerous. If something is buggy, they will hang, !!!
516 // !!! instead of exiting cleanly. This might wedge the buildbots. !!!
519 fn test_unnamed_thread() {
520 Thread::scoped(move|| {
521 assert!(Thread::current().name().is_none());
522 }).join().map_err(|_| ()).unwrap();
526 fn test_named_thread() {
527 Builder::new().name("ada lovelace".to_string()).scoped(move|| {
528 assert!(Thread::current().name().unwrap() == "ada lovelace".to_string());
529 }).join().map_err(|_| ()).unwrap();
533 fn test_run_basic() {
534 let (tx, rx) = channel();
535 Thread::spawn(move|| {
536 tx.send(()).unwrap();
542 fn test_join_success() {
543 match Thread::scoped(move|| -> String {
544 "Success!".to_string()
545 }).join().as_ref().map(|s| s.as_slice()) {
546 result::Result::Ok("Success!") => (),
552 fn test_join_panic() {
553 match Thread::scoped(move|| {
556 result::Result::Err(_) => (),
557 result::Result::Ok(()) => panic!()
562 fn test_spawn_sched() {
565 let (tx, rx) = channel();
567 fn f(i: int, tx: Sender<()>) {
569 Thread::spawn(move|| {
571 tx.send(()).unwrap();
583 fn test_spawn_sched_childs_on_default_sched() {
584 let (tx, rx) = channel();
586 Thread::spawn(move|| {
587 Thread::spawn(move|| {
588 tx.send(()).unwrap();
595 fn avoid_copying_the_body<F>(spawnfn: F) where F: FnOnce(Thunk) {
596 let (tx, rx) = channel::<uint>();
599 let x_in_parent = (&*x) as *const int as uint;
601 spawnfn(Thunk::new(move|| {
602 let x_in_child = (&*x) as *const int as uint;
603 tx.send(x_in_child).unwrap();
606 let x_in_child = rx.recv().unwrap();
607 assert_eq!(x_in_parent, x_in_child);
611 fn test_avoid_copying_the_body_spawn() {
612 avoid_copying_the_body(|v| {
613 Thread::spawn(move || v.invoke(()));
618 fn test_avoid_copying_the_body_thread_spawn() {
619 avoid_copying_the_body(|f| {
620 Thread::spawn(move|| {
627 fn test_avoid_copying_the_body_join() {
628 avoid_copying_the_body(|f| {
629 let _ = Thread::scoped(move|| {
636 fn test_child_doesnt_ref_parent() {
637 // If the child refcounts the parent task, this will stack overflow when
638 // climbing the task tree to dereference each ancestor. (See #1789)
639 // (well, it would if the constant were 8000+ - I lowered it to be more
640 // valgrind-friendly. try this at home, instead..!)
641 static GENERATIONS: uint = 16;
642 fn child_no(x: uint) -> Thunk {
643 return Thunk::new(move|| {
645 Thread::spawn(move|| child_no(x+1).invoke(()));
649 Thread::spawn(|| child_no(0).invoke(()));
653 fn test_simple_newsched_spawn() {
654 Thread::spawn(move || {});
658 fn test_try_panic_message_static_str() {
659 match Thread::scoped(move|| {
660 panic!("static string");
663 type T = &'static str;
664 assert!(e.is::<T>());
665 assert_eq!(*e.downcast::<T>().unwrap(), "static string");
672 fn test_try_panic_message_owned_str() {
673 match Thread::scoped(move|| {
674 panic!("owned string".to_string());
678 assert!(e.is::<T>());
679 assert_eq!(*e.downcast::<T>().unwrap(), "owned string".to_string());
686 fn test_try_panic_message_any() {
687 match Thread::scoped(move|| {
688 panic!(box 413u16 as Box<Any + Send>);
691 type T = Box<Any + Send>;
692 assert!(e.is::<T>());
693 let any = e.downcast::<T>().unwrap();
694 assert!(any.is::<u16>());
695 assert_eq!(*any.downcast::<u16>().unwrap(), 413u16);
702 fn test_try_panic_message_unit_struct() {
705 match Thread::scoped(move|| {
708 Err(ref e) if e.is::<Juju>() => {}
709 Err(_) | Ok(()) => panic!()
715 let (tx, rx) = channel();
716 let mut reader = ChanReader::new(rx);
717 let stdout = ChanWriter::new(tx);
719 let r = Builder::new().stdout(box stdout as Box<Writer + Send>).scoped(move|| {
720 print!("Hello, world!");
724 let output = reader.read_to_string().unwrap();
725 assert_eq!(output, "Hello, world!".to_string());
728 // NOTE: the corresponding test for stderr is in run-pass/task-stderr, due
729 // to the test harness apparently interfering with stderr configuration.