]> git.lizzy.rs Git - rust.git/blob - src/libstd/thread.rs
rollup merge of #21702: nikomatsakis/issue-21636
[rust.git] / src / libstd / thread.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Native threads
12 //!
13 //! ## The threading model
14 //!
15 //! An executing Rust program consists of a collection of native OS threads,
16 //! each with their own stack and local state.
17 //!
18 //! Communication between threads can be done through
19 //! [channels](../../std/sync/mpsc/index.html), Rust's message-passing
20 //! types, along with [other forms of thread
21 //! synchronization](../../std/sync/index.html) and shared-memory data
22 //! structures. In particular, types that are guaranteed to be
23 //! threadsafe are easily shared between threads using the
24 //! atomically-reference-counted container,
25 //! [`Arc`](../../std/sync/struct.Arc.html).
26 //!
27 //! Fatal logic errors in Rust cause *thread panic*, during which
28 //! a thread will unwind the stack, running destructors and freeing
29 //! owned resources. Thread panic is unrecoverable from within
30 //! the panicking thread (i.e. there is no 'try/catch' in Rust), but
31 //! panic may optionally be detected from a different thread. If
32 //! the main thread panics the application will exit with a non-zero
33 //! exit code.
34 //!
35 //! When the main thread of a Rust program terminates, the entire program shuts
36 //! down, even if other threads are still running. However, this module provides
37 //! convenient facilities for automatically waiting for the termination of a
38 //! child thread (i.e., join), described below.
39 //!
40 //! ## The `Thread` type
41 //!
42 //! Already-running threads are represented via the `Thread` type, which you can
43 //! get in one of two ways:
44 //!
45 //! * By spawning a new thread, e.g. using the `Thread::spawn` constructor;
46 //! * By requesting the current thread, using the `Thread::current` function.
47 //!
48 //! Threads can be named, and provide some built-in support for low-level
49 //! synchronization described below.
50 //!
51 //! The `Thread::current()` function is available even for threads not spawned
52 //! by the APIs of this module.
53 //!
54 //! ## Spawning a thread
55 //!
56 //! A new thread can be spawned using the `Thread::spawn` function:
57 //!
58 //! ```rust
59 //! use std::thread::Thread;
60 //!
61 //! let thread = Thread::spawn(move || {
62 //!     println!("Hello, World!");
63 //!     // some computation here
64 //! });
65 //! ```
66 //!
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.
71 //!
72 //! ## Scoped threads
73 //!
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:
77 //!
78 //! ```rust
79 //! use std::thread::Thread;
80 //!
81 //! let guard = Thread::scoped(move || {
82 //!     println!("Hello, World!");
83 //!     // some computation here
84 //! });
85 //! // do some other work in the meantime
86 //! let result = guard.join();
87 //! ```
88 //!
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.
96 //!
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.)
100 //!
101 //! ## Configuring threads
102 //!
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:
106 //!
107 //! ```rust
108 //! use std::thread;
109 //!
110 //! thread::Builder::new().name("child1".to_string()).spawn(move || {
111 //!     println!("Hello, world!")
112 //! });
113 //! ```
114 //!
115 //! ## Blocking support: park and unpark
116 //!
117 //! Every thread is equipped with some basic low-level blocking support, via the
118 //! `park` and `unpark` functions.
119 //!
120 //! Conceptually, each `Thread` handle has an associated token, which is
121 //! initially not present:
122 //!
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.
127 //!
128 //! * The `unpark()` method on a `Thread` atomically makes the token available
129 //!   if it wasn't already.
130 //!
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.
134 //!
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.
139 //!
140 //! The motivation for this design is twofold:
141 //!
142 //! * It avoids the need to allocate mutexes and condvars when building new
143 //!   synchronization primitives; the threads already provide basic blocking/signaling.
144 //!
145 //! * It can be implemented highly efficiently on many platforms.
146
147 #![stable(feature = "rust1", since = "1.0.0")]
148
149 use any::Any;
150 use boxed::Box;
151 use cell::UnsafeCell;
152 use clone::Clone;
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};
158 use str::Str;
159 use string::String;
160 use rt::{self, unwind};
161 use old_io::{Writer, stdio};
162 use thunk::Thunk;
163
164 use sys::thread as imp;
165 use sys_common::{stack, thread_info};
166
167 /// Thread configuration. Provides detailed control over the properties
168 /// and behavior of new threads.
169 #[stable(feature = "rust1", since = "1.0.0")]
170 pub struct Builder {
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>>,
179 }
180
181 impl Builder {
182     /// Generate the base configuration for spawning a thread, from which
183     /// configuration methods can be chained.
184     #[stable(feature = "rust1", since = "1.0.0")]
185     pub fn new() -> Builder {
186         Builder {
187             name: None,
188             stack_size: None,
189             stdout: None,
190             stderr: None,
191         }
192     }
193
194     /// Name the thread-to-be. Currently the name is used for identification
195     /// only in panic messages.
196     #[stable(feature = "rust1", since = "1.0.0")]
197     pub fn name(mut self, name: String) -> Builder {
198         self.name = Some(name);
199         self
200     }
201
202     /// Set the size of the stack for the new thread.
203     #[stable(feature = "rust1", since = "1.0.0")]
204     pub fn stack_size(mut self, size: uint) -> Builder {
205         self.stack_size = Some(size);
206         self
207     }
208
209     /// Redirect thread-local stdout.
210     #[unstable(feature = "std_misc",
211                reason = "Will likely go away after proc removal")]
212     pub fn stdout(mut self, stdout: Box<Writer + Send>) -> Builder {
213         self.stdout = Some(stdout);
214         self
215     }
216
217     /// Redirect thread-local stderr.
218     #[unstable(feature = "std_misc",
219                reason = "Will likely go away after proc removal")]
220     pub fn stderr(mut self, stderr: Box<Writer + Send>) -> Builder {
221         self.stderr = Some(stderr);
222         self
223     }
224
225     /// Spawn a new detached thread, and return a handle to it.
226     ///
227     /// See `Thead::spawn` and the module doc for more details.
228     #[unstable(feature = "std_misc",
229                reason = "may change with specifics of new Send semantics")]
230     pub fn spawn<F>(self, f: F) -> Thread where F: FnOnce(), F: Send + 'static {
231         let (native, thread) = self.spawn_inner(Thunk::new(f), Thunk::with_arg(|_| {}));
232         unsafe { imp::detach(native) };
233         thread
234     }
235
236     /// Spawn a new child thread that must be joined within a given
237     /// scope, and return a `JoinGuard`.
238     ///
239     /// See `Thead::scoped` and the module doc for more details.
240     #[unstable(feature = "std_misc",
241                reason = "may change with specifics of new Send semantics")]
242     pub fn scoped<'a, T, F>(self, f: F) -> JoinGuard<'a, T> where
243         T: Send + 'a, F: FnOnce() -> T, F: Send + 'a
244     {
245         let my_packet = Packet(Arc::new(UnsafeCell::new(None)));
246         let their_packet = Packet(my_packet.0.clone());
247         let (native, thread) = self.spawn_inner(Thunk::new(f), Thunk::with_arg(move |: ret| unsafe {
248             *their_packet.0.get() = Some(ret);
249         }));
250
251         JoinGuard {
252             native: native,
253             joined: false,
254             packet: my_packet,
255             thread: thread,
256         }
257     }
258
259     fn spawn_inner<T: Send>(self, f: Thunk<(), T>, finish: Thunk<Result<T>, ()>)
260                       -> (imp::rust_thread, Thread)
261     {
262         let Builder { name, stack_size, stdout, stderr } = self;
263
264         let stack_size = stack_size.unwrap_or(rt::min_stack());
265         let my_thread = Thread::new(name);
266         let their_thread = my_thread.clone();
267
268         // Spawning a new OS thread guarantees that __morestack will never get
269         // triggered, but we must manually set up the actual stack bounds once
270         // this function starts executing. This raises the lower limit by a bit
271         // because by the time that this function is executing we've already
272         // consumed at least a little bit of stack (we don't know the exact byte
273         // address at which our stack started).
274         let main = move |:| {
275             let something_around_the_top_of_the_stack = 1;
276             let addr = &something_around_the_top_of_the_stack as *const int;
277             let my_stack_top = addr as uint;
278             let my_stack_bottom = my_stack_top - stack_size + 1024;
279             unsafe {
280                 stack::record_os_managed_stack_bounds(my_stack_bottom, my_stack_top);
281             }
282             thread_info::set(
283                 (my_stack_bottom, my_stack_top),
284                 unsafe { imp::guard::current() },
285                 their_thread
286             );
287
288             let mut output = None;
289             let f: Thunk<(), T> = if stdout.is_some() || stderr.is_some() {
290                 Thunk::new(move |:| {
291                     let _ = stdout.map(stdio::set_stdout);
292                     let _ = stderr.map(stdio::set_stderr);
293                     f.invoke(())
294                 })
295             } else {
296                 f
297             };
298
299             let try_result = {
300                 let ptr = &mut output;
301
302                 // There are two primary reasons that general try/catch is
303                 // unsafe. The first is that we do not support nested
304                 // try/catch. The fact that this is happening in a newly-spawned
305                 // thread suffices. The second is that unwinding while unwinding
306                 // is not defined.  We take care of that by having an
307                 // 'unwinding' flag in the thread itself. For these reasons,
308                 // this unsafety should be ok.
309                 unsafe {
310                     unwind::try(move || *ptr = Some(f.invoke(())))
311                 }
312             };
313             finish.invoke(match (output, try_result) {
314                 (Some(data), Ok(_)) => Ok(data),
315                 (None, Err(cause)) => Err(cause),
316                 _ => unreachable!()
317             });
318         };
319
320         (unsafe { imp::create(stack_size, Thunk::new(main)) }, my_thread)
321     }
322 }
323
324 struct Inner {
325     name: Option<String>,
326     lock: Mutex<bool>,          // true when there is a buffered unpark
327     cvar: Condvar,
328 }
329
330 unsafe impl Sync for Inner {}
331
332 #[derive(Clone)]
333 #[stable(feature = "rust1", since = "1.0.0")]
334 /// A handle to a thread.
335 pub struct Thread {
336     inner: Arc<Inner>,
337 }
338
339 impl Thread {
340     // Used only internally to construct a thread object without spawning
341     fn new(name: Option<String>) -> Thread {
342         Thread {
343             inner: Arc::new(Inner {
344                 name: name,
345                 lock: Mutex::new(false),
346                 cvar: Condvar::new(),
347             })
348         }
349     }
350
351     /// Spawn a new detached thread, returning a handle to it.
352     ///
353     /// The child thread may outlive the parent (unless the parent thread is the
354     /// main thread; the whole process is terminated when the main thread
355     /// finishes.) The thread handle can be used for low-level
356     /// synchronization. See the module documentation for additional details.
357     #[unstable(feature = "std_misc",
358                reason = "may change with specifics of new Send semantics")]
359     pub fn spawn<F>(f: F) -> Thread where F: FnOnce(), F: Send + 'static {
360         Builder::new().spawn(f)
361     }
362
363     /// Spawn a new *scoped* thread, returning a `JoinGuard` for it.
364     ///
365     /// The join guard can be used to explicitly join the child thread (via
366     /// `join`), returning `Result<T>`, or it will implicitly join the child
367     /// upon being dropped. Because the child thread may refer to data on the
368     /// current thread's stack (hence the "scoped" name), it cannot be detached;
369     /// it *must* be joined before the relevant stack frame is popped. See the
370     /// module documentation for additional details.
371     #[unstable(feature = "std_misc",
372                reason = "may change with specifics of new Send semantics")]
373     pub fn scoped<'a, T, F>(f: F) -> JoinGuard<'a, T> where
374         T: Send + 'a, F: FnOnce() -> T, F: Send + 'a
375     {
376         Builder::new().scoped(f)
377     }
378
379     /// Gets a handle to the thread that invokes it.
380     #[stable(feature = "rust1", since = "1.0.0")]
381     pub fn current() -> Thread {
382         thread_info::current_thread()
383     }
384
385     /// Cooperatively give up a timeslice to the OS scheduler.
386     #[unstable(feature = "std_misc", reason = "name may change")]
387     pub fn yield_now() {
388         unsafe { imp::yield_now() }
389     }
390
391     /// Determines whether the current thread is unwinding because of panic.
392     #[inline]
393     #[stable(feature = "rust1", since = "1.0.0")]
394     pub fn panicking() -> bool {
395         unwind::panicking()
396     }
397
398     /// Block unless or until the current thread's token is made available (may wake spuriously).
399     ///
400     /// See the module doc for more detail.
401     //
402     // The implementation currently uses the trivial strategy of a Mutex+Condvar
403     // with wakeup flag, which does not actually allow spurious wakeups. In the
404     // future, this will be implemented in a more efficient way, perhaps along the lines of
405     //   http://cr.openjdk.java.net/~stefank/6989984.1/raw_files/new/src/os/linux/vm/os_linux.cpp
406     // or futuxes, and in either case may allow spurious wakeups.
407     #[unstable(feature = "std_misc", reason = "recently introduced")]
408     pub fn park() {
409         let thread = Thread::current();
410         let mut guard = thread.inner.lock.lock().unwrap();
411         while !*guard {
412             guard = thread.inner.cvar.wait(guard).unwrap();
413         }
414         *guard = false;
415     }
416
417     /// Atomically makes the handle's token available if it is not already.
418     ///
419     /// See the module doc for more detail.
420     #[unstable(feature = "std_misc", reason = "recently introduced")]
421     pub fn unpark(&self) {
422         let mut guard = self.inner.lock.lock().unwrap();
423         if !*guard {
424             *guard = true;
425             self.inner.cvar.notify_one();
426         }
427     }
428
429     /// Get the thread's name.
430     #[stable(feature = "rust1", since = "1.0.0")]
431     pub fn name(&self) -> Option<&str> {
432         self.inner.name.as_ref().map(|s| s.as_slice())
433     }
434 }
435
436 // a hack to get around privacy restrictions
437 impl thread_info::NewThread for Thread {
438     fn new(name: Option<String>) -> Thread { Thread::new(name) }
439 }
440
441 /// Indicates the manner in which a thread exited.
442 ///
443 /// A thread that completes without panicking is considered to exit successfully.
444 #[stable(feature = "rust1", since = "1.0.0")]
445 pub type Result<T> = ::result::Result<T, Box<Any + Send>>;
446
447 struct Packet<T>(Arc<UnsafeCell<Option<Result<T>>>>);
448
449 unsafe impl<T:'static+Send> Send for Packet<T> {}
450 unsafe impl<T> Sync for Packet<T> {}
451
452 /// An RAII-style guard that will block until thread termination when dropped.
453 ///
454 /// The type `T` is the return type for the thread's main function.
455 #[must_use]
456 #[unstable(feature = "std_misc",
457            reason = "may change with specifics of new Send semantics")]
458 pub struct JoinGuard<'a, T: 'a> {
459     native: imp::rust_thread,
460     thread: Thread,
461     joined: bool,
462     packet: Packet<T>,
463 }
464
465 #[stable(feature = "rust1", since = "1.0.0")]
466 unsafe impl<'a, T: Send + 'a> Sync for JoinGuard<'a, T> {}
467
468 impl<'a, T: Send + 'a> JoinGuard<'a, T> {
469     /// Extract a handle to the thread this guard will join on.
470     #[stable(feature = "rust1", since = "1.0.0")]
471     pub fn thread(&self) -> &Thread {
472         &self.thread
473     }
474
475     /// Wait for the associated thread to finish, returning the result of the thread's
476     /// calculation.
477     ///
478     /// If the child thread panics, `Err` is returned with the parameter given
479     /// to `panic`.
480     #[stable(feature = "rust1", since = "1.0.0")]
481     pub fn join(mut self) -> Result<T> {
482         assert!(!self.joined);
483         unsafe { imp::join(self.native) };
484         self.joined = true;
485         unsafe {
486             (*self.packet.0.get()).take().unwrap()
487         }
488     }
489 }
490
491 impl<T: Send> JoinGuard<'static, T> {
492     /// Detaches the child thread, allowing it to outlive its parent.
493     #[unstable(feature = "std_misc",
494                reason = "unsure whether this API imposes limitations elsewhere")]
495     pub fn detach(mut self) {
496         unsafe { imp::detach(self.native) };
497         self.joined = true; // avoid joining in the destructor
498     }
499 }
500
501 #[unsafe_destructor]
502 #[stable(feature = "rust1", since = "1.0.0")]
503 impl<'a, T: Send + 'a> Drop for JoinGuard<'a, T> {
504     fn drop(&mut self) {
505         if !self.joined {
506             unsafe { imp::join(self.native) };
507         }
508     }
509 }
510
511 #[cfg(test)]
512 mod test {
513     use prelude::v1::*;
514
515     use any::Any;
516     use sync::mpsc::{channel, Sender};
517     use boxed::BoxAny;
518     use result;
519     use std::old_io::{ChanReader, ChanWriter};
520     use super::{Thread, Builder};
521     use thunk::Thunk;
522
523     // !!! These tests are dangerous. If something is buggy, they will hang, !!!
524     // !!! instead of exiting cleanly. This might wedge the buildbots.       !!!
525
526     #[test]
527     fn test_unnamed_thread() {
528         Thread::scoped(move|| {
529             assert!(Thread::current().name().is_none());
530         }).join().ok().unwrap();
531     }
532
533     #[test]
534     fn test_named_thread() {
535         Builder::new().name("ada lovelace".to_string()).scoped(move|| {
536             assert!(Thread::current().name().unwrap() == "ada lovelace".to_string());
537         }).join().ok().unwrap();
538     }
539
540     #[test]
541     fn test_run_basic() {
542         let (tx, rx) = channel();
543         Thread::spawn(move|| {
544             tx.send(()).unwrap();
545         });
546         rx.recv().unwrap();
547     }
548
549     #[test]
550     fn test_join_success() {
551         match Thread::scoped(move|| -> String {
552             "Success!".to_string()
553         }).join().as_ref().map(|s| s.as_slice()) {
554             result::Result::Ok("Success!") => (),
555             _ => panic!()
556         }
557     }
558
559     #[test]
560     fn test_join_panic() {
561         match Thread::scoped(move|| {
562             panic!()
563         }).join() {
564             result::Result::Err(_) => (),
565             result::Result::Ok(()) => panic!()
566         }
567     }
568
569     #[test]
570     fn test_spawn_sched() {
571         use clone::Clone;
572
573         let (tx, rx) = channel();
574
575         fn f(i: int, tx: Sender<()>) {
576             let tx = tx.clone();
577             Thread::spawn(move|| {
578                 if i == 0 {
579                     tx.send(()).unwrap();
580                 } else {
581                     f(i - 1, tx);
582                 }
583             });
584
585         }
586         f(10, tx);
587         rx.recv().unwrap();
588     }
589
590     #[test]
591     fn test_spawn_sched_childs_on_default_sched() {
592         let (tx, rx) = channel();
593
594         Thread::spawn(move|| {
595             Thread::spawn(move|| {
596                 tx.send(()).unwrap();
597             });
598         });
599
600         rx.recv().unwrap();
601     }
602
603     fn avoid_copying_the_body<F>(spawnfn: F) where F: FnOnce(Thunk) {
604         let (tx, rx) = channel::<uint>();
605
606         let x = box 1;
607         let x_in_parent = (&*x) as *const int as uint;
608
609         spawnfn(Thunk::new(move|| {
610             let x_in_child = (&*x) as *const int as uint;
611             tx.send(x_in_child).unwrap();
612         }));
613
614         let x_in_child = rx.recv().unwrap();
615         assert_eq!(x_in_parent, x_in_child);
616     }
617
618     #[test]
619     fn test_avoid_copying_the_body_spawn() {
620         avoid_copying_the_body(|v| {
621             Thread::spawn(move || v.invoke(()));
622         });
623     }
624
625     #[test]
626     fn test_avoid_copying_the_body_thread_spawn() {
627         avoid_copying_the_body(|f| {
628             Thread::spawn(move|| {
629                 f.invoke(());
630             });
631         })
632     }
633
634     #[test]
635     fn test_avoid_copying_the_body_join() {
636         avoid_copying_the_body(|f| {
637             let _ = Thread::scoped(move|| {
638                 f.invoke(())
639             }).join();
640         })
641     }
642
643     #[test]
644     fn test_child_doesnt_ref_parent() {
645         // If the child refcounts the parent task, this will stack overflow when
646         // climbing the task tree to dereference each ancestor. (See #1789)
647         // (well, it would if the constant were 8000+ - I lowered it to be more
648         // valgrind-friendly. try this at home, instead..!)
649         static GENERATIONS: uint = 16;
650         fn child_no(x: uint) -> Thunk {
651             return Thunk::new(move|| {
652                 if x < GENERATIONS {
653                     Thread::spawn(move|| child_no(x+1).invoke(()));
654                 }
655             });
656         }
657         Thread::spawn(|| child_no(0).invoke(()));
658     }
659
660     #[test]
661     fn test_simple_newsched_spawn() {
662         Thread::spawn(move || {});
663     }
664
665     #[test]
666     fn test_try_panic_message_static_str() {
667         match Thread::scoped(move|| {
668             panic!("static string");
669         }).join() {
670             Err(e) => {
671                 type T = &'static str;
672                 assert!(e.is::<T>());
673                 assert_eq!(*e.downcast::<T>().ok().unwrap(), "static string");
674             }
675             Ok(()) => panic!()
676         }
677     }
678
679     #[test]
680     fn test_try_panic_message_owned_str() {
681         match Thread::scoped(move|| {
682             panic!("owned string".to_string());
683         }).join() {
684             Err(e) => {
685                 type T = String;
686                 assert!(e.is::<T>());
687                 assert_eq!(*e.downcast::<T>().ok().unwrap(), "owned string".to_string());
688             }
689             Ok(()) => panic!()
690         }
691     }
692
693     #[test]
694     fn test_try_panic_message_any() {
695         match Thread::scoped(move|| {
696             panic!(box 413u16 as Box<Any + Send>);
697         }).join() {
698             Err(e) => {
699                 type T = Box<Any + Send>;
700                 assert!(e.is::<T>());
701                 let any = e.downcast::<T>().ok().unwrap();
702                 assert!(any.is::<u16>());
703                 assert_eq!(*any.downcast::<u16>().ok().unwrap(), 413u16);
704             }
705             Ok(()) => panic!()
706         }
707     }
708
709     #[test]
710     fn test_try_panic_message_unit_struct() {
711         struct Juju;
712
713         match Thread::scoped(move|| {
714             panic!(Juju)
715         }).join() {
716             Err(ref e) if e.is::<Juju>() => {}
717             Err(_) | Ok(()) => panic!()
718         }
719     }
720
721     #[test]
722     fn test_stdout() {
723         let (tx, rx) = channel();
724         let mut reader = ChanReader::new(rx);
725         let stdout = ChanWriter::new(tx);
726
727         let r = Builder::new().stdout(box stdout as Box<Writer + Send>).scoped(move|| {
728             print!("Hello, world!");
729         }).join();
730         assert!(r.is_ok());
731
732         let output = reader.read_to_string().unwrap();
733         assert_eq!(output, "Hello, world!".to_string());
734     }
735
736     // NOTE: the corresponding test for stderr is in run-pass/task-stderr, due
737     // to the test harness apparently interfering with stderr configuration.
738 }