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:
61 //! thread::spawn(move || {
62 //! println!("Hello, World!");
63 //! // some computation here
67 //! In this example, the spawned thread is "detached" from the current
68 //! thread, meaning that it can outlive the thread that spawned
69 //! it. (Note, however, that when the main thread terminates all
70 //! detached threads are terminated as well.)
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:
81 //! let guard = thread::scoped(move || {
82 //! println!("Hello, World!");
83 //! // some computation here
85 //! // do some other work in the meantime
86 //! let output = guard.join();
89 //! The `scoped` function doesn't return a `Thread` directly; instead,
90 //! it returns a *join guard*. The join guard is an RAII-style guard
91 //! that will automatically join the child thread (block until it
92 //! terminates) when it is dropped. You can join the child thread in
93 //! 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
95 //! itself is 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")]
153 use cell::UnsafeCell;
158 use rt::{self, unwind};
159 use sync::{Mutex, Condvar, Arc};
163 use sys::thread as imp;
164 use sys_common::{stack, thread_info};
166 /// Thread configuration. Provides detailed control over the properties
167 /// and behavior of new threads.
168 #[stable(feature = "rust1", since = "1.0.0")]
170 // A name for the thread-to-be, for identification in panic messages
171 name: Option<String>,
172 // The size of the stack for the spawned thread
173 stack_size: Option<uint>,
174 // Thread-local stdout
175 stdout: Option<Box<Writer + Send + 'static>>,
176 // Thread-local stderr
177 stderr: Option<Box<Writer + Send + 'static>>,
181 /// Generate the base configuration for spawning a thread, from which
182 /// configuration methods can be chained.
183 #[stable(feature = "rust1", since = "1.0.0")]
184 pub fn new() -> Builder {
193 /// Name the thread-to-be. Currently the name is used for identification
194 /// only in panic messages.
195 #[stable(feature = "rust1", since = "1.0.0")]
196 pub fn name(mut self, name: String) -> Builder {
197 self.name = Some(name);
201 /// Set the size of the stack for the new thread.
202 #[stable(feature = "rust1", since = "1.0.0")]
203 pub fn stack_size(mut self, size: uint) -> Builder {
204 self.stack_size = Some(size);
208 /// Redirect thread-local stdout.
209 #[unstable(feature = "std_misc",
210 reason = "Will likely go away after proc removal")]
211 pub fn stdout(mut self, stdout: Box<Writer + Send + 'static>) -> Builder {
212 self.stdout = Some(stdout);
216 /// Redirect thread-local stderr.
217 #[unstable(feature = "std_misc",
218 reason = "Will likely go away after proc removal")]
219 pub fn stderr(mut self, stderr: Box<Writer + Send + 'static>) -> Builder {
220 self.stderr = Some(stderr);
224 /// Spawn a new thread, and return a join handle for it.
226 /// The child thread may outlive the parent (unless the parent thread
227 /// is the main thread; the whole process is terminated when the main
228 /// thread finishes.) The join handle can be used to block on
229 /// termination of the child thread, including recovering its panics.
233 /// Unlike the `spawn` free function, this method yields an
234 /// `io::Result` to capture any failure to create the thread at
236 #[stable(feature = "rust1", since = "1.0.0")]
237 pub fn spawn<F>(self, f: F) -> io::Result<JoinHandle> where
238 F: FnOnce(), F: Send + 'static
240 self.spawn_inner(Thunk::new(f)).map(|i| JoinHandle(i))
243 /// Spawn a new child thread that must be joined within a given
244 /// scope, and return a `JoinGuard`.
246 /// The join guard can be used to explicitly join the child thread (via
247 /// `join`), returning `Result<T>`, or it will implicitly join the child
248 /// upon being dropped. Because the child thread may refer to data on the
249 /// current thread's stack (hence the "scoped" name), it cannot be detached;
250 /// it *must* be joined before the relevant stack frame is popped. See the
251 /// module documentation for additional details.
255 /// Unlike the `scoped` free function, this method yields an
256 /// `io::Result` to capture any failure to create the thread at
258 #[stable(feature = "rust1", since = "1.0.0")]
259 pub fn scoped<'a, T, F>(self, f: F) -> io::Result<JoinGuard<'a, T>> where
260 T: Send + 'a, F: FnOnce() -> T, F: Send + 'a
262 self.spawn_inner(Thunk::new(f)).map(|inner| {
263 JoinGuard { inner: inner, _marker: marker::CovariantType }
267 fn spawn_inner<T: Send>(self, f: Thunk<(), T>) -> io::Result<JoinInner<T>> {
268 let Builder { name, stack_size, stdout, stderr } = self;
270 let stack_size = stack_size.unwrap_or(rt::min_stack());
272 let my_thread = Thread::new(name);
273 let their_thread = my_thread.clone();
275 let my_packet = Packet(Arc::new(UnsafeCell::new(None)));
276 let their_packet = Packet(my_packet.0.clone());
278 // Spawning a new OS thread guarantees that __morestack will never get
279 // triggered, but we must manually set up the actual stack bounds once
280 // this function starts executing. This raises the lower limit by a bit
281 // because by the time that this function is executing we've already
282 // consumed at least a little bit of stack (we don't know the exact byte
283 // address at which our stack started).
285 let something_around_the_top_of_the_stack = 1;
286 let addr = &something_around_the_top_of_the_stack as *const int;
287 let my_stack_top = addr as uint;
288 let my_stack_bottom = my_stack_top - stack_size + 1024;
290 stack::record_os_managed_stack_bounds(my_stack_bottom, my_stack_top);
292 match their_thread.name() {
293 Some(name) => unsafe { imp::set_name(name.as_slice()); },
297 (my_stack_bottom, my_stack_top),
298 unsafe { imp::guard::current() },
302 let mut output = None;
303 let f: Thunk<(), T> = if stdout.is_some() || stderr.is_some() {
305 let _ = stdout.map(stdio::set_stdout);
306 let _ = stderr.map(stdio::set_stderr);
314 let ptr = &mut output;
316 // There are two primary reasons that general try/catch is
317 // unsafe. The first is that we do not support nested
318 // try/catch. The fact that this is happening in a newly-spawned
319 // thread suffices. The second is that unwinding while unwinding
320 // is not defined. We take care of that by having an
321 // 'unwinding' flag in the thread itself. For these reasons,
322 // this unsafety should be ok.
324 unwind::try(move || *ptr = Some(f.invoke(())))
328 *their_packet.0.get() = Some(match (output, try_result) {
329 (Some(data), Ok(_)) => Ok(data),
330 (None, Err(cause)) => Err(cause),
337 native: try!(unsafe { imp::create(stack_size, Thunk::new(main)) }),
345 /// Spawn a new, returning a join handle for it.
347 /// The child thread may outlive the parent (unless the parent thread
348 /// is the main thread; the whole process is terminated when the main
349 /// thread finishes.) The join handle can be used to block on
350 /// termination of the child thread, including recovering its panics.
354 /// Panicks if the OS fails to create a thread; use `Builder::spawn`
355 /// to recover from such errors.
356 #[stable(feature = "rust1", since = "1.0.0")]
357 pub fn spawn<F>(f: F) -> JoinHandle where F: FnOnce(), F: Send + 'static {
358 Builder::new().spawn(f).unwrap()
361 /// Spawn a new *scoped* thread, returning a `JoinGuard` for it.
363 /// The join guard can be used to explicitly join the child thread (via
364 /// `join`), returning `Result<T>`, or it will implicitly join the child
365 /// upon being dropped. Because the child thread may refer to data on the
366 /// current thread's stack (hence the "scoped" name), it cannot be detached;
367 /// it *must* be joined before the relevant stack frame is popped. See the
368 /// module documentation for additional details.
372 /// Panicks if the OS fails to create a thread; use `Builder::scoped`
373 /// to recover from such errors.
374 #[stable(feature = "rust1", since = "1.0.0")]
375 pub fn scoped<'a, T, F>(f: F) -> JoinGuard<'a, T> where
376 T: Send + 'a, F: FnOnce() -> T, F: Send + 'a
378 Builder::new().scoped(f).unwrap()
381 /// Gets a handle to the thread that invokes it.
382 #[stable(feature = "rust1", since = "1.0.0")]
383 pub fn current() -> Thread {
384 thread_info::current_thread()
387 /// Cooperatively give up a timeslice to the OS scheduler.
388 #[stable(feature = "rust1", since = "1.0.0")]
390 unsafe { imp::yield_now() }
393 /// Determines whether the current thread is unwinding because of panic.
395 #[stable(feature = "rust1", since = "1.0.0")]
396 pub fn panicking() -> bool {
400 /// Block unless or until the current thread's token is made available (may wake spuriously).
402 /// See the module doc for more detail.
404 // The implementation currently uses the trivial strategy of a Mutex+Condvar
405 // with wakeup flag, which does not actually allow spurious wakeups. In the
406 // future, this will be implemented in a more efficient way, perhaps along the lines of
407 // http://cr.openjdk.java.net/~stefank/6989984.1/raw_files/new/src/os/linux/vm/os_linux.cpp
408 // or futuxes, and in either case may allow spurious wakeups.
409 #[stable(feature = "rust1", since = "1.0.0")]
411 let thread = current();
412 let mut guard = thread.inner.lock.lock().unwrap();
414 guard = thread.inner.cvar.wait(guard).unwrap();
419 /// Block unless or until the current thread's token is made available or
420 /// the specified duration has been reached (may wake spuriously).
422 /// The semantics of this function are equivalent to `park()` except that the
423 /// thread will be blocked for roughly no longer than dur. This method
424 /// should not be used for precise timing due to anomalies such as
425 /// preemption or platform differences that may not cause the maximum
426 /// amount of time waited to be precisely dur
428 /// See the module doc for more detail.
429 #[unstable(feature = "std_misc", reason = "recently introduced, depends on Duration")]
430 pub fn park_timeout(dur: Duration) {
431 let thread = current();
432 let mut guard = thread.inner.lock.lock().unwrap();
434 let (g, _) = thread.inner.cvar.wait_timeout(guard, dur).unwrap();
440 /// The internal representation of a `Thread` handle
442 name: Option<String>,
443 lock: Mutex<bool>, // true when there is a buffered unpark
447 unsafe impl Sync for Inner {}
450 #[stable(feature = "rust1", since = "1.0.0")]
451 /// A handle to a thread.
457 // Used only internally to construct a thread object without spawning
458 fn new(name: Option<String>) -> Thread {
460 inner: Arc::new(Inner {
462 lock: Mutex::new(false),
463 cvar: Condvar::new(),
468 /// Deprecated: use module-level free fucntion.
469 #[deprecated(since = "1.0.0", reason = "use module-level free fucntion")]
470 #[unstable(feature = "std_misc",
471 reason = "may change with specifics of new Send semantics")]
472 pub fn spawn<F>(f: F) -> Thread where F: FnOnce(), F: Send + 'static {
473 Builder::new().spawn(f).unwrap().thread().clone()
476 /// Deprecated: use module-level free fucntion.
477 #[deprecated(since = "1.0.0", reason = "use module-level free fucntion")]
478 #[unstable(feature = "std_misc",
479 reason = "may change with specifics of new Send semantics")]
480 pub fn scoped<'a, T, F>(f: F) -> JoinGuard<'a, T> where
481 T: Send + 'a, F: FnOnce() -> T, F: Send + 'a
483 Builder::new().scoped(f).unwrap()
486 /// Deprecated: use module-level free fucntion.
487 #[deprecated(since = "1.0.0", reason = "use module-level free fucntion")]
488 #[stable(feature = "rust1", since = "1.0.0")]
489 pub fn current() -> Thread {
490 thread_info::current_thread()
493 /// Deprecated: use module-level free fucntion.
494 #[deprecated(since = "1.0.0", reason = "use module-level free fucntion")]
495 #[unstable(feature = "std_misc", reason = "name may change")]
497 unsafe { imp::yield_now() }
500 /// Deprecated: use module-level free fucntion.
501 #[deprecated(since = "1.0.0", reason = "use module-level free fucntion")]
503 #[stable(feature = "rust1", since = "1.0.0")]
504 pub fn panicking() -> bool {
508 /// Deprecated: use module-level free fucntion.
509 #[deprecated(since = "1.0.0", reason = "use module-level free fucntion")]
510 #[unstable(feature = "std_misc", reason = "recently introduced")]
512 let thread = current();
513 let mut guard = thread.inner.lock.lock().unwrap();
515 guard = thread.inner.cvar.wait(guard).unwrap();
520 /// Deprecated: use module-level free fucntion.
521 #[deprecated(since = "1.0.0", reason = "use module-level free fucntion")]
522 #[unstable(feature = "std_misc", reason = "recently introduced")]
523 pub fn park_timeout(dur: Duration) {
524 let thread = current();
525 let mut guard = thread.inner.lock.lock().unwrap();
527 let (g, _) = thread.inner.cvar.wait_timeout(guard, dur).unwrap();
533 /// Atomically makes the handle's token available if it is not already.
535 /// See the module doc for more detail.
536 #[stable(feature = "rust1", since = "1.0.0")]
537 pub fn unpark(&self) {
538 let mut guard = self.inner.lock.lock().unwrap();
541 self.inner.cvar.notify_one();
545 /// Get the thread's name.
546 #[stable(feature = "rust1", since = "1.0.0")]
547 pub fn name(&self) -> Option<&str> {
548 self.inner.name.as_ref().map(|s| &**s)
552 #[stable(feature = "rust1", since = "1.0.0")]
553 impl fmt::Debug for Thread {
554 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
555 fmt::Debug::fmt(&self.name(), f)
559 // a hack to get around privacy restrictions
560 impl thread_info::NewThread for Thread {
561 fn new(name: Option<String>) -> Thread { Thread::new(name) }
564 /// Indicates the manner in which a thread exited.
566 /// A thread that completes without panicking is considered to exit successfully.
567 #[stable(feature = "rust1", since = "1.0.0")]
568 pub type Result<T> = ::result::Result<T, Box<Any + Send + 'static>>;
570 struct Packet<T>(Arc<UnsafeCell<Option<Result<T>>>>);
572 unsafe impl<T:Send> Send for Packet<T> {}
573 unsafe impl<T> Sync for Packet<T> {}
575 /// Inner representation for JoinHandle and JoinGuard
576 struct JoinInner<T> {
577 native: imp::rust_thread,
583 impl<T> JoinInner<T> {
584 fn join(&mut self) -> Result<T> {
585 assert!(!self.joined);
586 unsafe { imp::join(self.native) };
589 (*self.packet.0.get()).take().unwrap()
594 /// An owned permission to join on a thread (block on its termination).
596 /// Unlike a `JoinGuard`, a `JoinHandle` *detaches* the child thread
597 /// when it is dropped, rather than automatically joining on drop.
599 /// Due to platform restrictions, it is not possible to `Clone` this
600 /// handle: the ability to join a child thread is a uniquely-owned
602 #[stable(feature = "rust1", since = "1.0.0")]
603 pub struct JoinHandle(JoinInner<()>);
606 /// Extract a handle to the underlying thread
607 #[stable(feature = "rust1", since = "1.0.0")]
608 pub fn thread(&self) -> &Thread {
612 /// Wait for the associated thread to finish.
614 /// If the child thread panics, `Err` is returned with the parameter given
616 #[stable(feature = "rust1", since = "1.0.0")]
617 pub fn join(mut self) -> Result<()> {
622 #[stable(feature = "rust1", since = "1.0.0")]
623 impl Drop for JoinHandle {
626 unsafe { imp::detach(self.0.native) }
631 /// An RAII-style guard that will block until thread termination when dropped.
633 /// The type `T` is the return type for the thread's main function.
635 /// Joining on drop is necessary to ensure memory safety when stack
636 /// data is shared between a parent and child thread.
638 /// Due to platform restrictions, it is not possible to `Clone` this
639 /// handle: the ability to join a child thread is a uniquely-owned
642 #[stable(feature = "rust1", since = "1.0.0")]
643 pub struct JoinGuard<'a, T: 'a> {
645 _marker: marker::CovariantType<&'a T>,
648 #[stable(feature = "rust1", since = "1.0.0")]
649 unsafe impl<'a, T: Send + 'a> Sync for JoinGuard<'a, T> {}
651 impl<'a, T: Send + 'a> JoinGuard<'a, T> {
652 /// Extract a handle to the thread this guard will join on.
653 #[stable(feature = "rust1", since = "1.0.0")]
654 pub fn thread(&self) -> &Thread {
658 /// Wait for the associated thread to finish, returning the result of the thread's
663 /// Panics on the child thread are propagated by panicking the parent.
664 #[stable(feature = "rust1", since = "1.0.0")]
665 pub fn join(mut self) -> T {
666 match self.inner.join() {
668 Err(_) => panic!("child thread {:?} panicked", self.thread()),
673 #[stable(feature = "rust1", since = "1.0.0")]
674 impl<T: Send> JoinGuard<'static, T> {
675 /// Detaches the child thread, allowing it to outlive its parent.
676 #[deprecated(since = "1.0.0", reason = "use spawn instead")]
677 #[unstable(feature = "std_misc")]
678 pub fn detach(mut self) {
679 unsafe { imp::detach(self.inner.native) };
680 self.inner.joined = true; // avoid joining in the destructor
685 #[stable(feature = "rust1", since = "1.0.0")]
686 impl<'a, T: Send + 'a> Drop for JoinGuard<'a, T> {
688 if !self.inner.joined {
689 if self.inner.join().is_err() {
690 panic!("child thread {:?} panicked", self.thread());
701 use sync::mpsc::{channel, Sender};
704 use std::old_io::{ChanReader, ChanWriter};
705 use super::{Thread, Builder};
710 // !!! These tests are dangerous. If something is buggy, they will hang, !!!
711 // !!! instead of exiting cleanly. This might wedge the buildbots. !!!
714 fn test_unnamed_thread() {
715 thread::spawn(move|| {
716 assert!(thread::current().name().is_none());
717 }).join().ok().unwrap();
721 fn test_named_thread() {
722 Builder::new().name("ada lovelace".to_string()).scoped(move|| {
723 assert!(thread::current().name().unwrap() == "ada lovelace".to_string());
728 fn test_run_basic() {
729 let (tx, rx) = channel();
730 thread::spawn(move|| {
731 tx.send(()).unwrap();
737 fn test_join_success() {
738 assert!(thread::scoped(move|| -> String {
739 "Success!".to_string()
740 }).join() == "Success!");
744 fn test_join_panic() {
745 match thread::spawn(move|| {
748 result::Result::Err(_) => (),
749 result::Result::Ok(()) => panic!()
754 fn test_scoped_success() {
755 let res = thread::scoped(move|| -> String {
756 "Success!".to_string()
758 assert!(res == "Success!");
763 fn test_scoped_panic() {
764 thread::scoped(|| panic!()).join();
769 fn test_scoped_implicit_panic() {
770 thread::scoped(|| panic!());
774 fn test_spawn_sched() {
777 let (tx, rx) = channel();
779 fn f(i: int, tx: Sender<()>) {
781 thread::spawn(move|| {
783 tx.send(()).unwrap();
795 fn test_spawn_sched_childs_on_default_sched() {
796 let (tx, rx) = channel();
798 thread::spawn(move|| {
799 thread::spawn(move|| {
800 tx.send(()).unwrap();
807 fn avoid_copying_the_body<F>(spawnfn: F) where F: FnOnce(Thunk<'static>) {
808 let (tx, rx) = channel::<uint>();
811 let x_in_parent = (&*x) as *const int as uint;
813 spawnfn(Thunk::new(move|| {
814 let x_in_child = (&*x) as *const int as uint;
815 tx.send(x_in_child).unwrap();
818 let x_in_child = rx.recv().unwrap();
819 assert_eq!(x_in_parent, x_in_child);
823 fn test_avoid_copying_the_body_spawn() {
824 avoid_copying_the_body(|v| {
825 thread::spawn(move || v.invoke(()));
830 fn test_avoid_copying_the_body_thread_spawn() {
831 avoid_copying_the_body(|f| {
832 thread::spawn(move|| {
839 fn test_avoid_copying_the_body_join() {
840 avoid_copying_the_body(|f| {
841 let _ = thread::spawn(move|| {
848 fn test_child_doesnt_ref_parent() {
849 // If the child refcounts the parent task, this will stack overflow when
850 // climbing the task tree to dereference each ancestor. (See #1789)
851 // (well, it would if the constant were 8000+ - I lowered it to be more
852 // valgrind-friendly. try this at home, instead..!)
853 static GENERATIONS: uint = 16;
854 fn child_no(x: uint) -> Thunk<'static> {
855 return Thunk::new(move|| {
857 thread::spawn(move|| child_no(x+1).invoke(()));
861 thread::spawn(|| child_no(0).invoke(()));
865 fn test_simple_newsched_spawn() {
866 thread::spawn(move || {});
870 fn test_try_panic_message_static_str() {
871 match thread::spawn(move|| {
872 panic!("static string");
875 type T = &'static str;
876 assert!(e.is::<T>());
877 assert_eq!(*e.downcast::<T>().ok().unwrap(), "static string");
884 fn test_try_panic_message_owned_str() {
885 match thread::spawn(move|| {
886 panic!("owned string".to_string());
890 assert!(e.is::<T>());
891 assert_eq!(*e.downcast::<T>().ok().unwrap(), "owned string".to_string());
898 fn test_try_panic_message_any() {
899 match thread::spawn(move|| {
900 panic!(box 413u16 as Box<Any + Send>);
903 type T = Box<Any + Send>;
904 assert!(e.is::<T>());
905 let any = e.downcast::<T>().ok().unwrap();
906 assert!(any.is::<u16>());
907 assert_eq!(*any.downcast::<u16>().ok().unwrap(), 413u16);
914 fn test_try_panic_message_unit_struct() {
917 match thread::spawn(move|| {
920 Err(ref e) if e.is::<Juju>() => {}
921 Err(_) | Ok(()) => panic!()
927 let (tx, rx) = channel();
928 let mut reader = ChanReader::new(rx);
929 let stdout = ChanWriter::new(tx);
931 Builder::new().stdout(box stdout as Box<Writer + Send>).scoped(move|| {
932 print!("Hello, world!");
935 let output = reader.read_to_string().unwrap();
936 assert_eq!(output, "Hello, world!".to_string());
940 fn test_park_timeout_unpark_before() {
942 thread::current().unpark();
943 thread::park_timeout(Duration::seconds(10_000_000));
948 fn test_park_timeout_unpark_not_called() {
950 thread::park_timeout(Duration::milliseconds(10));
955 fn test_park_timeout_unpark_called_other_thread() {
959 let th = thread::current();
961 let _guard = thread::spawn(move || {
962 old_io::timer::sleep(Duration::milliseconds(50));
966 thread::park_timeout(Duration::seconds(10_000_000));
970 // NOTE: the corresponding test for stderr is in run-pass/task-stderr, due
971 // to the test harness apparently interfering with stderr configuration.