]> git.lizzy.rs Git - rust.git/blob - src/libstd/thread.rs
Rollup merge of #21976 - mzabaluev:fix-copy-mut-lifetime, r=alexcrichton
[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. `Thread::park_timeout()` does the same, but allows specifying a
127 //!   maximum time to block the thread for.
128 //!
129 //! * The `unpark()` method on a `Thread` atomically makes the token available
130 //!   if it wasn't already.
131 //!
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.
135 //!
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.
140 //!
141 //! The motivation for this design is twofold:
142 //!
143 //! * It avoids the need to allocate mutexes and condvars when building new
144 //!   synchronization primitives; the threads already provide basic blocking/signaling.
145 //!
146 //! * It can be implemented highly efficiently on many platforms.
147
148 #![stable(feature = "rust1", since = "1.0.0")]
149
150 use any::Any;
151 use boxed::Box;
152 use cell::UnsafeCell;
153 use clone::Clone;
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};
159 use string::String;
160 use rt::{self, unwind};
161 use old_io::{Writer, stdio};
162 use thunk::Thunk;
163 use time::Duration;
164
165 use sys::thread as imp;
166 use sys_common::{stack, thread_info};
167
168 /// Thread configuration. Provides detailed control over the properties
169 /// and behavior of new threads.
170 #[stable(feature = "rust1", since = "1.0.0")]
171 pub struct Builder {
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>>,
180 }
181
182 impl Builder {
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 {
187         Builder {
188             name: None,
189             stack_size: None,
190             stdout: None,
191             stderr: None,
192         }
193     }
194
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);
200         self
201     }
202
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);
207         self
208     }
209
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);
215         self
216     }
217
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);
223         self
224     }
225
226     /// Spawn a new detached thread, and return a handle to it.
227     ///
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) };
234         thread
235     }
236
237     /// Spawn a new child thread that must be joined within a given
238     /// scope, and return a `JoinGuard`.
239     ///
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
245     {
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);
250         }));
251
252         JoinGuard {
253             native: native,
254             joined: false,
255             packet: my_packet,
256             thread: thread,
257         }
258     }
259
260     fn spawn_inner<T: Send>(self, f: Thunk<(), T>, finish: Thunk<Result<T>, ()>)
261                       -> (imp::rust_thread, Thread)
262     {
263         let Builder { name, stack_size, stdout, stderr } = self;
264
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();
268
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).
275         let main = move || {
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;
280             unsafe {
281                 stack::record_os_managed_stack_bounds(my_stack_bottom, my_stack_top);
282             }
283             thread_info::set(
284                 (my_stack_bottom, my_stack_top),
285                 unsafe { imp::guard::current() },
286                 their_thread
287             );
288
289             let mut output = None;
290             let f: Thunk<(), T> = if stdout.is_some() || stderr.is_some() {
291                 Thunk::new(move || {
292                     let _ = stdout.map(stdio::set_stdout);
293                     let _ = stderr.map(stdio::set_stderr);
294                     f.invoke(())
295                 })
296             } else {
297                 f
298             };
299
300             let try_result = {
301                 let ptr = &mut output;
302
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.
310                 unsafe {
311                     unwind::try(move || *ptr = Some(f.invoke(())))
312                 }
313             };
314             finish.invoke(match (output, try_result) {
315                 (Some(data), Ok(_)) => Ok(data),
316                 (None, Err(cause)) => Err(cause),
317                 _ => unreachable!()
318             });
319         };
320
321         (unsafe { imp::create(stack_size, Thunk::new(main)) }, my_thread)
322     }
323 }
324
325 struct Inner {
326     name: Option<String>,
327     lock: Mutex<bool>,          // true when there is a buffered unpark
328     cvar: Condvar,
329 }
330
331 unsafe impl Sync for Inner {}
332
333 #[derive(Clone)]
334 #[stable(feature = "rust1", since = "1.0.0")]
335 /// A handle to a thread.
336 pub struct Thread {
337     inner: Arc<Inner>,
338 }
339
340 impl Thread {
341     // Used only internally to construct a thread object without spawning
342     fn new(name: Option<String>) -> Thread {
343         Thread {
344             inner: Arc::new(Inner {
345                 name: name,
346                 lock: Mutex::new(false),
347                 cvar: Condvar::new(),
348             })
349         }
350     }
351
352     /// Spawn a new detached thread, returning a handle to it.
353     ///
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)
362     }
363
364     /// Spawn a new *scoped* thread, returning a `JoinGuard` for it.
365     ///
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
376     {
377         Builder::new().scoped(f)
378     }
379
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()
384     }
385
386     /// Cooperatively give up a timeslice to the OS scheduler.
387     #[unstable(feature = "std_misc", reason = "name may change")]
388     pub fn yield_now() {
389         unsafe { imp::yield_now() }
390     }
391
392     /// Determines whether the current thread is unwinding because of panic.
393     #[inline]
394     #[stable(feature = "rust1", since = "1.0.0")]
395     pub fn panicking() -> bool {
396         unwind::panicking()
397     }
398
399     /// Block unless or until the current thread's token is made available (may wake spuriously).
400     ///
401     /// See the module doc for more detail.
402     //
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")]
409     pub fn park() {
410         let thread = Thread::current();
411         let mut guard = thread.inner.lock.lock().unwrap();
412         while !*guard {
413             guard = thread.inner.cvar.wait(guard).unwrap();
414         }
415         *guard = false;
416     }
417
418     /// Block unless or until the current thread's token is made available or
419     /// the specified duration has been reached (may wake spuriously).
420     ///
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
426     ///
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();
432         if !*guard {
433             let (g, _) = thread.inner.cvar.wait_timeout(guard, dur).unwrap();
434             guard = g;
435         }
436         *guard = false;
437     }
438
439     /// Atomically makes the handle's token available if it is not already.
440     ///
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();
445         if !*guard {
446             *guard = true;
447             self.inner.cvar.notify_one();
448         }
449     }
450
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)
455     }
456 }
457
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) }
461 }
462
463 /// Indicates the manner in which a thread exited.
464 ///
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>>;
468
469 struct Packet<T>(Arc<UnsafeCell<Option<Result<T>>>>);
470
471 unsafe impl<T:'static+Send> Send for Packet<T> {}
472 unsafe impl<T> Sync for Packet<T> {}
473
474 /// An RAII-style guard that will block until thread termination when dropped.
475 ///
476 /// The type `T` is the return type for the thread's main function.
477 #[must_use]
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,
482     thread: Thread,
483     joined: bool,
484     packet: Packet<T>,
485 }
486
487 #[stable(feature = "rust1", since = "1.0.0")]
488 unsafe impl<'a, T: Send + 'a> Sync for JoinGuard<'a, T> {}
489
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 {
494         &self.thread
495     }
496
497     /// Wait for the associated thread to finish, returning the result of the thread's
498     /// calculation.
499     ///
500     /// If the child thread panics, `Err` is returned with the parameter given
501     /// to `panic`.
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) };
506         self.joined = true;
507         unsafe {
508             (*self.packet.0.get()).take().unwrap()
509         }
510     }
511 }
512
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
520     }
521 }
522
523 #[unsafe_destructor]
524 #[stable(feature = "rust1", since = "1.0.0")]
525 impl<'a, T: Send + 'a> Drop for JoinGuard<'a, T> {
526     fn drop(&mut self) {
527         if !self.joined {
528             unsafe { imp::join(self.native) };
529         }
530     }
531 }
532
533 #[cfg(test)]
534 mod test {
535     use prelude::v1::*;
536
537     use any::Any;
538     use sync::mpsc::{channel, Sender};
539     use boxed::BoxAny;
540     use result;
541     use std::old_io::{ChanReader, ChanWriter};
542     use super::{Thread, Builder};
543     use thunk::Thunk;
544     use time::Duration;
545
546     // !!! These tests are dangerous. If something is buggy, they will hang, !!!
547     // !!! instead of exiting cleanly. This might wedge the buildbots.       !!!
548
549     #[test]
550     fn test_unnamed_thread() {
551         Thread::scoped(move|| {
552             assert!(Thread::current().name().is_none());
553         }).join().ok().unwrap();
554     }
555
556     #[test]
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();
561     }
562
563     #[test]
564     fn test_run_basic() {
565         let (tx, rx) = channel();
566         Thread::spawn(move|| {
567             tx.send(()).unwrap();
568         });
569         rx.recv().unwrap();
570     }
571
572     #[test]
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!") => (),
578             _ => panic!()
579         }
580     }
581
582     #[test]
583     fn test_join_panic() {
584         match Thread::scoped(move|| {
585             panic!()
586         }).join() {
587             result::Result::Err(_) => (),
588             result::Result::Ok(()) => panic!()
589         }
590     }
591
592     #[test]
593     fn test_spawn_sched() {
594         use clone::Clone;
595
596         let (tx, rx) = channel();
597
598         fn f(i: int, tx: Sender<()>) {
599             let tx = tx.clone();
600             Thread::spawn(move|| {
601                 if i == 0 {
602                     tx.send(()).unwrap();
603                 } else {
604                     f(i - 1, tx);
605                 }
606             });
607
608         }
609         f(10, tx);
610         rx.recv().unwrap();
611     }
612
613     #[test]
614     fn test_spawn_sched_childs_on_default_sched() {
615         let (tx, rx) = channel();
616
617         Thread::spawn(move|| {
618             Thread::spawn(move|| {
619                 tx.send(()).unwrap();
620             });
621         });
622
623         rx.recv().unwrap();
624     }
625
626     fn avoid_copying_the_body<F>(spawnfn: F) where F: FnOnce(Thunk) {
627         let (tx, rx) = channel::<uint>();
628
629         let x = box 1;
630         let x_in_parent = (&*x) as *const int as uint;
631
632         spawnfn(Thunk::new(move|| {
633             let x_in_child = (&*x) as *const int as uint;
634             tx.send(x_in_child).unwrap();
635         }));
636
637         let x_in_child = rx.recv().unwrap();
638         assert_eq!(x_in_parent, x_in_child);
639     }
640
641     #[test]
642     fn test_avoid_copying_the_body_spawn() {
643         avoid_copying_the_body(|v| {
644             Thread::spawn(move || v.invoke(()));
645         });
646     }
647
648     #[test]
649     fn test_avoid_copying_the_body_thread_spawn() {
650         avoid_copying_the_body(|f| {
651             Thread::spawn(move|| {
652                 f.invoke(());
653             });
654         })
655     }
656
657     #[test]
658     fn test_avoid_copying_the_body_join() {
659         avoid_copying_the_body(|f| {
660             let _ = Thread::scoped(move|| {
661                 f.invoke(())
662             }).join();
663         })
664     }
665
666     #[test]
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|| {
675                 if x < GENERATIONS {
676                     Thread::spawn(move|| child_no(x+1).invoke(()));
677                 }
678             });
679         }
680         Thread::spawn(|| child_no(0).invoke(()));
681     }
682
683     #[test]
684     fn test_simple_newsched_spawn() {
685         Thread::spawn(move || {});
686     }
687
688     #[test]
689     fn test_try_panic_message_static_str() {
690         match Thread::scoped(move|| {
691             panic!("static string");
692         }).join() {
693             Err(e) => {
694                 type T = &'static str;
695                 assert!(e.is::<T>());
696                 assert_eq!(*e.downcast::<T>().ok().unwrap(), "static string");
697             }
698             Ok(()) => panic!()
699         }
700     }
701
702     #[test]
703     fn test_try_panic_message_owned_str() {
704         match Thread::scoped(move|| {
705             panic!("owned string".to_string());
706         }).join() {
707             Err(e) => {
708                 type T = String;
709                 assert!(e.is::<T>());
710                 assert_eq!(*e.downcast::<T>().ok().unwrap(), "owned string".to_string());
711             }
712             Ok(()) => panic!()
713         }
714     }
715
716     #[test]
717     fn test_try_panic_message_any() {
718         match Thread::scoped(move|| {
719             panic!(box 413u16 as Box<Any + Send>);
720         }).join() {
721             Err(e) => {
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);
727             }
728             Ok(()) => panic!()
729         }
730     }
731
732     #[test]
733     fn test_try_panic_message_unit_struct() {
734         struct Juju;
735
736         match Thread::scoped(move|| {
737             panic!(Juju)
738         }).join() {
739             Err(ref e) if e.is::<Juju>() => {}
740             Err(_) | Ok(()) => panic!()
741         }
742     }
743
744     #[test]
745     fn test_stdout() {
746         let (tx, rx) = channel();
747         let mut reader = ChanReader::new(rx);
748         let stdout = ChanWriter::new(tx);
749
750         let r = Builder::new().stdout(box stdout as Box<Writer + Send>).scoped(move|| {
751             print!("Hello, world!");
752         }).join();
753         assert!(r.is_ok());
754
755         let output = reader.read_to_string().unwrap();
756         assert_eq!(output, "Hello, world!".to_string());
757     }
758
759     #[test]
760     fn test_park_timeout_unpark_before() {
761         for _ in 0..10 {
762             Thread::current().unpark();
763             Thread::park_timeout(Duration::seconds(10_000_000));
764         }
765     }
766
767     #[test]
768     fn test_park_timeout_unpark_not_called() {
769         for _ in 0..10 {
770             Thread::park_timeout(Duration::milliseconds(10));
771         }
772     }
773
774     #[test]
775     fn test_park_timeout_unpark_called_other_thread() {
776         use std::old_io;
777
778         for _ in 0..10 {
779             let th = Thread::current();
780
781             let _guard = Thread::scoped(move || {
782                 old_io::timer::sleep(Duration::milliseconds(50));
783                 th.unpark();
784             });
785
786             Thread::park_timeout(Duration::seconds(10_000_000));
787         }
788     }
789
790     // NOTE: the corresponding test for stderr is in run-pass/task-stderr, due
791     // to the test harness apparently interfering with stderr configuration.
792 }