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
126 //! token. `Thread::park_timeout()` does the same, but allows specifying a
127 //! maximum time to block the thread for.
129 //! * The `unpark()` method on a `Thread` atomically makes the token available
130 //! if it wasn't already.
132 //! In other words, each `Thread` acts a bit like a semaphore with initial count
133 //! 0, except that the semaphore is *saturating* (the count cannot go above 1),
134 //! and can return spuriously.
136 //! The API is typically used by acquiring a handle to the current thread,
137 //! placing that handle in a shared data structure so that other threads can
138 //! find it, and then `park`ing. When some desired condition is met, another
139 //! thread calls `unpark` on the handle.
141 //! The motivation for this design is twofold:
143 //! * It avoids the need to allocate mutexes and condvars when building new
144 //! synchronization primitives; the threads already provide basic blocking/signaling.
146 //! * It can be implemented highly efficiently on many platforms.
148 #![stable(feature = "rust1", since = "1.0.0")]
152 use cell::UnsafeCell;
154 use marker::{Send, Sync};
155 use ops::{Drop, FnOnce};
156 use option::Option::{self, Some, None};
157 use result::Result::{Err, Ok};
158 use sync::{Mutex, Condvar, Arc};
160 use rt::{self, unwind};
161 use old_io::{Writer, stdio};
165 use sys::thread as imp;
166 use sys_common::{stack, thread_info};
168 /// Thread configuration. Provides detailed control over the properties
169 /// and behavior of new threads.
170 #[stable(feature = "rust1", since = "1.0.0")]
172 // A name for the thread-to-be, for identification in panic messages
173 name: Option<String>,
174 // The size of the stack for the spawned thread
175 stack_size: Option<uint>,
176 // Thread-local stdout
177 stdout: Option<Box<Writer + Send>>,
178 // Thread-local stderr
179 stderr: Option<Box<Writer + Send>>,
183 /// Generate the base configuration for spawning a thread, from which
184 /// configuration methods can be chained.
185 #[stable(feature = "rust1", since = "1.0.0")]
186 pub fn new() -> Builder {
195 /// Name the thread-to-be. Currently the name is used for identification
196 /// only in panic messages.
197 #[stable(feature = "rust1", since = "1.0.0")]
198 pub fn name(mut self, name: String) -> Builder {
199 self.name = Some(name);
203 /// Set the size of the stack for the new thread.
204 #[stable(feature = "rust1", since = "1.0.0")]
205 pub fn stack_size(mut self, size: uint) -> Builder {
206 self.stack_size = Some(size);
210 /// Redirect thread-local stdout.
211 #[unstable(feature = "std_misc",
212 reason = "Will likely go away after proc removal")]
213 pub fn stdout(mut self, stdout: Box<Writer + Send>) -> Builder {
214 self.stdout = Some(stdout);
218 /// Redirect thread-local stderr.
219 #[unstable(feature = "std_misc",
220 reason = "Will likely go away after proc removal")]
221 pub fn stderr(mut self, stderr: Box<Writer + Send>) -> Builder {
222 self.stderr = Some(stderr);
226 /// Spawn a new detached thread, and return a handle to it.
228 /// See `Thead::spawn` and the module doc for more details.
229 #[unstable(feature = "std_misc",
230 reason = "may change with specifics of new Send semantics")]
231 pub fn spawn<F>(self, f: F) -> Thread where F: FnOnce(), F: Send + 'static {
232 let (native, thread) = self.spawn_inner(Thunk::new(f), Thunk::with_arg(|_| {}));
233 unsafe { imp::detach(native) };
237 /// Spawn a new child thread that must be joined within a given
238 /// scope, and return a `JoinGuard`.
240 /// See `Thead::scoped` and the module doc for more details.
241 #[unstable(feature = "std_misc",
242 reason = "may change with specifics of new Send semantics")]
243 pub fn scoped<'a, T, F>(self, f: F) -> JoinGuard<'a, T> where
244 T: Send + 'a, F: FnOnce() -> T, F: Send + 'a
246 let my_packet = Packet(Arc::new(UnsafeCell::new(None)));
247 let their_packet = Packet(my_packet.0.clone());
248 let (native, thread) = self.spawn_inner(Thunk::new(f), Thunk::with_arg(move |ret| unsafe {
249 *their_packet.0.get() = Some(ret);
260 fn spawn_inner<T: Send>(self, f: Thunk<(), T>, finish: Thunk<Result<T>, ()>)
261 -> (imp::rust_thread, Thread)
263 let Builder { name, stack_size, stdout, stderr } = self;
265 let stack_size = stack_size.unwrap_or(rt::min_stack());
266 let my_thread = Thread::new(name);
267 let their_thread = my_thread.clone();
269 // Spawning a new OS thread guarantees that __morestack will never get
270 // triggered, but we must manually set up the actual stack bounds once
271 // this function starts executing. This raises the lower limit by a bit
272 // because by the time that this function is executing we've already
273 // consumed at least a little bit of stack (we don't know the exact byte
274 // address at which our stack started).
276 let something_around_the_top_of_the_stack = 1;
277 let addr = &something_around_the_top_of_the_stack as *const int;
278 let my_stack_top = addr as uint;
279 let my_stack_bottom = my_stack_top - stack_size + 1024;
281 stack::record_os_managed_stack_bounds(my_stack_bottom, my_stack_top);
284 (my_stack_bottom, my_stack_top),
285 unsafe { imp::guard::current() },
289 let mut output = None;
290 let f: Thunk<(), T> = if stdout.is_some() || stderr.is_some() {
292 let _ = stdout.map(stdio::set_stdout);
293 let _ = stderr.map(stdio::set_stderr);
301 let ptr = &mut output;
303 // There are two primary reasons that general try/catch is
304 // unsafe. The first is that we do not support nested
305 // try/catch. The fact that this is happening in a newly-spawned
306 // thread suffices. The second is that unwinding while unwinding
307 // is not defined. We take care of that by having an
308 // 'unwinding' flag in the thread itself. For these reasons,
309 // this unsafety should be ok.
311 unwind::try(move || *ptr = Some(f.invoke(())))
314 finish.invoke(match (output, try_result) {
315 (Some(data), Ok(_)) => Ok(data),
316 (None, Err(cause)) => Err(cause),
321 (unsafe { imp::create(stack_size, Thunk::new(main)) }, my_thread)
326 name: Option<String>,
327 lock: Mutex<bool>, // true when there is a buffered unpark
331 unsafe impl Sync for Inner {}
334 #[stable(feature = "rust1", since = "1.0.0")]
335 /// A handle to a thread.
341 // Used only internally to construct a thread object without spawning
342 fn new(name: Option<String>) -> Thread {
344 inner: Arc::new(Inner {
346 lock: Mutex::new(false),
347 cvar: Condvar::new(),
352 /// Spawn a new detached thread, returning a handle to it.
354 /// The child thread may outlive the parent (unless the parent thread is the
355 /// main thread; the whole process is terminated when the main thread
356 /// finishes.) The thread handle can be used for low-level
357 /// synchronization. See the module documentation for additional details.
358 #[unstable(feature = "std_misc",
359 reason = "may change with specifics of new Send semantics")]
360 pub fn spawn<F>(f: F) -> Thread where F: FnOnce(), F: Send + 'static {
361 Builder::new().spawn(f)
364 /// Spawn a new *scoped* thread, returning a `JoinGuard` for it.
366 /// The join guard can be used to explicitly join the child thread (via
367 /// `join`), returning `Result<T>`, or it will implicitly join the child
368 /// upon being dropped. Because the child thread may refer to data on the
369 /// current thread's stack (hence the "scoped" name), it cannot be detached;
370 /// it *must* be joined before the relevant stack frame is popped. See the
371 /// module documentation for additional details.
372 #[unstable(feature = "std_misc",
373 reason = "may change with specifics of new Send semantics")]
374 pub fn scoped<'a, T, F>(f: F) -> JoinGuard<'a, T> where
375 T: Send + 'a, F: FnOnce() -> T, F: Send + 'a
377 Builder::new().scoped(f)
380 /// Gets a handle to the thread that invokes it.
381 #[stable(feature = "rust1", since = "1.0.0")]
382 pub fn current() -> Thread {
383 thread_info::current_thread()
386 /// Cooperatively give up a timeslice to the OS scheduler.
387 #[unstable(feature = "std_misc", reason = "name may change")]
389 unsafe { imp::yield_now() }
392 /// Determines whether the current thread is unwinding because of panic.
394 #[stable(feature = "rust1", since = "1.0.0")]
395 pub fn panicking() -> bool {
399 /// Block unless or until the current thread's token is made available (may wake spuriously).
401 /// See the module doc for more detail.
403 // The implementation currently uses the trivial strategy of a Mutex+Condvar
404 // with wakeup flag, which does not actually allow spurious wakeups. In the
405 // future, this will be implemented in a more efficient way, perhaps along the lines of
406 // http://cr.openjdk.java.net/~stefank/6989984.1/raw_files/new/src/os/linux/vm/os_linux.cpp
407 // or futuxes, and in either case may allow spurious wakeups.
408 #[unstable(feature = "std_misc", reason = "recently introduced")]
410 let thread = Thread::current();
411 let mut guard = thread.inner.lock.lock().unwrap();
413 guard = thread.inner.cvar.wait(guard).unwrap();
418 /// Block unless or until the current thread's token is made available or
419 /// the specified duration has been reached (may wake spuriously).
421 /// The semantics of this function are equivalent to `park()` except that the
422 /// thread will be blocked for roughly no longer than dur. This method
423 /// should not be used for precise timing due to anomalies such as
424 /// preemption or platform differences that may not cause the maximum
425 /// amount of time waited to be precisely dur
427 /// See the module doc for more detail.
428 #[unstable(feature = "std_misc", reason = "recently introduced")]
429 pub fn park_timeout(dur: Duration) {
430 let thread = Thread::current();
431 let mut guard = thread.inner.lock.lock().unwrap();
433 let (g, _) = thread.inner.cvar.wait_timeout(guard, dur).unwrap();
439 /// Atomically makes the handle's token available if it is not already.
441 /// See the module doc for more detail.
442 #[unstable(feature = "std_misc", reason = "recently introduced")]
443 pub fn unpark(&self) {
444 let mut guard = self.inner.lock.lock().unwrap();
447 self.inner.cvar.notify_one();
451 /// Get the thread's name.
452 #[stable(feature = "rust1", since = "1.0.0")]
453 pub fn name(&self) -> Option<&str> {
454 self.inner.name.as_ref().map(|s| &**s)
458 // a hack to get around privacy restrictions
459 impl thread_info::NewThread for Thread {
460 fn new(name: Option<String>) -> Thread { Thread::new(name) }
463 /// Indicates the manner in which a thread exited.
465 /// A thread that completes without panicking is considered to exit successfully.
466 #[stable(feature = "rust1", since = "1.0.0")]
467 pub type Result<T> = ::result::Result<T, Box<Any + Send>>;
469 struct Packet<T>(Arc<UnsafeCell<Option<Result<T>>>>);
471 unsafe impl<T:'static+Send> Send for Packet<T> {}
472 unsafe impl<T> Sync for Packet<T> {}
474 /// An RAII-style guard that will block until thread termination when dropped.
476 /// The type `T` is the return type for the thread's main function.
478 #[unstable(feature = "std_misc",
479 reason = "may change with specifics of new Send semantics")]
480 pub struct JoinGuard<'a, T: 'a> {
481 native: imp::rust_thread,
487 #[stable(feature = "rust1", since = "1.0.0")]
488 unsafe impl<'a, T: Send + 'a> Sync for JoinGuard<'a, T> {}
490 impl<'a, T: Send + 'a> JoinGuard<'a, T> {
491 /// Extract a handle to the thread this guard will join on.
492 #[stable(feature = "rust1", since = "1.0.0")]
493 pub fn thread(&self) -> &Thread {
497 /// Wait for the associated thread to finish, returning the result of the thread's
500 /// If the child thread panics, `Err` is returned with the parameter given
502 #[stable(feature = "rust1", since = "1.0.0")]
503 pub fn join(mut self) -> Result<T> {
504 assert!(!self.joined);
505 unsafe { imp::join(self.native) };
508 (*self.packet.0.get()).take().unwrap()
513 impl<T: Send> JoinGuard<'static, T> {
514 /// Detaches the child thread, allowing it to outlive its parent.
515 #[unstable(feature = "std_misc",
516 reason = "unsure whether this API imposes limitations elsewhere")]
517 pub fn detach(mut self) {
518 unsafe { imp::detach(self.native) };
519 self.joined = true; // avoid joining in the destructor
524 #[stable(feature = "rust1", since = "1.0.0")]
525 impl<'a, T: Send + 'a> Drop for JoinGuard<'a, T> {
528 unsafe { imp::join(self.native) };
538 use sync::mpsc::{channel, Sender};
541 use std::old_io::{ChanReader, ChanWriter};
542 use super::{Thread, Builder};
546 // !!! These tests are dangerous. If something is buggy, they will hang, !!!
547 // !!! instead of exiting cleanly. This might wedge the buildbots. !!!
550 fn test_unnamed_thread() {
551 Thread::scoped(move|| {
552 assert!(Thread::current().name().is_none());
553 }).join().ok().unwrap();
557 fn test_named_thread() {
558 Builder::new().name("ada lovelace".to_string()).scoped(move|| {
559 assert!(Thread::current().name().unwrap() == "ada lovelace".to_string());
560 }).join().ok().unwrap();
564 fn test_run_basic() {
565 let (tx, rx) = channel();
566 Thread::spawn(move|| {
567 tx.send(()).unwrap();
573 fn test_join_success() {
574 match Thread::scoped(move|| -> String {
575 "Success!".to_string()
576 }).join().as_ref().map(|s| &**s) {
577 result::Result::Ok("Success!") => (),
583 fn test_join_panic() {
584 match Thread::scoped(move|| {
587 result::Result::Err(_) => (),
588 result::Result::Ok(()) => panic!()
593 fn test_spawn_sched() {
596 let (tx, rx) = channel();
598 fn f(i: int, tx: Sender<()>) {
600 Thread::spawn(move|| {
602 tx.send(()).unwrap();
614 fn test_spawn_sched_childs_on_default_sched() {
615 let (tx, rx) = channel();
617 Thread::spawn(move|| {
618 Thread::spawn(move|| {
619 tx.send(()).unwrap();
626 fn avoid_copying_the_body<F>(spawnfn: F) where F: FnOnce(Thunk) {
627 let (tx, rx) = channel::<uint>();
630 let x_in_parent = (&*x) as *const int as uint;
632 spawnfn(Thunk::new(move|| {
633 let x_in_child = (&*x) as *const int as uint;
634 tx.send(x_in_child).unwrap();
637 let x_in_child = rx.recv().unwrap();
638 assert_eq!(x_in_parent, x_in_child);
642 fn test_avoid_copying_the_body_spawn() {
643 avoid_copying_the_body(|v| {
644 Thread::spawn(move || v.invoke(()));
649 fn test_avoid_copying_the_body_thread_spawn() {
650 avoid_copying_the_body(|f| {
651 Thread::spawn(move|| {
658 fn test_avoid_copying_the_body_join() {
659 avoid_copying_the_body(|f| {
660 let _ = Thread::scoped(move|| {
667 fn test_child_doesnt_ref_parent() {
668 // If the child refcounts the parent task, this will stack overflow when
669 // climbing the task tree to dereference each ancestor. (See #1789)
670 // (well, it would if the constant were 8000+ - I lowered it to be more
671 // valgrind-friendly. try this at home, instead..!)
672 static GENERATIONS: uint = 16;
673 fn child_no(x: uint) -> Thunk {
674 return Thunk::new(move|| {
676 Thread::spawn(move|| child_no(x+1).invoke(()));
680 Thread::spawn(|| child_no(0).invoke(()));
684 fn test_simple_newsched_spawn() {
685 Thread::spawn(move || {});
689 fn test_try_panic_message_static_str() {
690 match Thread::scoped(move|| {
691 panic!("static string");
694 type T = &'static str;
695 assert!(e.is::<T>());
696 assert_eq!(*e.downcast::<T>().ok().unwrap(), "static string");
703 fn test_try_panic_message_owned_str() {
704 match Thread::scoped(move|| {
705 panic!("owned string".to_string());
709 assert!(e.is::<T>());
710 assert_eq!(*e.downcast::<T>().ok().unwrap(), "owned string".to_string());
717 fn test_try_panic_message_any() {
718 match Thread::scoped(move|| {
719 panic!(box 413u16 as Box<Any + Send>);
722 type T = Box<Any + Send>;
723 assert!(e.is::<T>());
724 let any = e.downcast::<T>().ok().unwrap();
725 assert!(any.is::<u16>());
726 assert_eq!(*any.downcast::<u16>().ok().unwrap(), 413u16);
733 fn test_try_panic_message_unit_struct() {
736 match Thread::scoped(move|| {
739 Err(ref e) if e.is::<Juju>() => {}
740 Err(_) | Ok(()) => panic!()
746 let (tx, rx) = channel();
747 let mut reader = ChanReader::new(rx);
748 let stdout = ChanWriter::new(tx);
750 let r = Builder::new().stdout(box stdout as Box<Writer + Send>).scoped(move|| {
751 print!("Hello, world!");
755 let output = reader.read_to_string().unwrap();
756 assert_eq!(output, "Hello, world!".to_string());
760 fn test_park_timeout_unpark_before() {
762 Thread::current().unpark();
763 Thread::park_timeout(Duration::seconds(10_000_000));
768 fn test_park_timeout_unpark_not_called() {
770 Thread::park_timeout(Duration::milliseconds(10));
775 fn test_park_timeout_unpark_called_other_thread() {
779 let th = Thread::current();
781 let _guard = Thread::scoped(move || {
782 old_io::timer::sleep(Duration::milliseconds(50));
786 Thread::park_timeout(Duration::seconds(10_000_000));
790 // NOTE: the corresponding test for stderr is in run-pass/task-stderr, due
791 // to the test harness apparently interfering with stderr configuration.