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. Threads can be named, and
17 //! provide some built-in support for low-level synchronization.
19 //! Communication between threads can be done through
20 //! [channels](../../std/sync/mpsc/index.html), Rust's message-passing
21 //! types, along with [other forms of thread
22 //! synchronization](../../std/sync/index.html) and shared-memory data
23 //! structures. In particular, types that are guaranteed to be
24 //! threadsafe are easily shared between threads using the
25 //! atomically-reference-counted container,
26 //! [`Arc`](../../std/sync/struct.Arc.html).
28 //! Fatal logic errors in Rust cause *thread panic*, during which
29 //! a thread will unwind the stack, running destructors and freeing
30 //! owned resources. Thread panic is unrecoverable from within
31 //! the panicking thread (i.e. there is no 'try/catch' in Rust), but
32 //! the panic may optionally be detected from a different thread. If
33 //! the main thread panics, the application will exit with a non-zero
36 //! When the main thread of a Rust program terminates, the entire program shuts
37 //! down, even if other threads are still running. However, this module provides
38 //! convenient facilities for automatically waiting for the termination of a
39 //! child thread (i.e., join).
41 //! ## Spawning a thread
43 //! A new thread can be spawned using the `thread::spawn` function:
48 //! thread::spawn(move || {
53 //! In this example, the spawned thread is "detached" from the current
54 //! thread. This means that it can outlive its parent (the thread that spawned
55 //! it), unless this parent is the main thread.
57 //! The parent thread can also wait on the completion of the child
58 //! thread; a call to `spawn` produces a `JoinHandle`, which provides
59 //! a `join` method for waiting:
64 //! let child = thread::spawn(move || {
68 //! let res = child.join();
71 //! The `join` method returns a `Result` containing `Ok` of the final
72 //! value produced by the child thread, or `Err` of the value given to
73 //! a call to `panic!` if the child panicked.
75 //! ## Configuring threads
77 //! A new thread can be configured before it is spawned via the `Builder` type,
78 //! which currently allows you to set the name and stack size for the child thread:
81 //! # #![allow(unused_must_use)]
84 //! thread::Builder::new().name("child1".to_string()).spawn(move || {
85 //! println!("Hello, world!");
89 //! ## The `Thread` type
91 //! Threads are represented via the `Thread` type, which you can get in one of
94 //! * By spawning a new thread, e.g. using the `thread::spawn` function, and
95 //! calling `thread()` on the `JoinHandle`.
96 //! * By requesting the current thread, using the `thread::current` function.
98 //! The `thread::current()` function is available even for threads not spawned
99 //! by the APIs of this module.
101 //! ## Blocking support: park and unpark
103 //! Every thread is equipped with some basic low-level blocking support, via the
104 //! `thread::park()` function and `thread::Thread::unpark()` method. `park()`
105 //! blocks the current thread, which can then be resumed from another thread by
106 //! calling the `unpark()` method on the blocked thread's handle.
108 //! Conceptually, each `Thread` handle has an associated token, which is
109 //! initially not present:
111 //! * The `thread::park()` function blocks the current thread unless or until
112 //! the token is available for its thread handle, at which point it atomically
113 //! consumes the token. It may also return *spuriously*, without consuming the
114 //! token. `thread::park_timeout()` does the same, but allows specifying a
115 //! maximum time to block the thread for.
117 //! * The `unpark()` method on a `Thread` atomically makes the token available
118 //! if it wasn't already.
120 //! In other words, each `Thread` acts a bit like a semaphore with initial count
121 //! 0, except that the semaphore is *saturating* (the count cannot go above 1),
122 //! and can return spuriously.
124 //! The API is typically used by acquiring a handle to the current thread,
125 //! placing that handle in a shared data structure so that other threads can
126 //! find it, and then `park`ing. When some desired condition is met, another
127 //! thread calls `unpark` on the handle.
129 //! The motivation for this design is twofold:
131 //! * It avoids the need to allocate mutexes and condvars when building new
132 //! synchronization primitives; the threads already provide basic blocking/signaling.
134 //! * It can be implemented very efficiently on many platforms.
136 //! ## Thread-local storage
138 //! This module also provides an implementation of thread local storage for Rust
139 //! programs. Thread local storage is a method of storing data into a global
140 //! variable which each thread in the program will have its own copy of.
141 //! Threads do not share this data, so accesses do not need to be synchronized.
143 //! At a high level, this module provides two variants of storage:
145 //! * Owned thread-local storage. This is a type of thread local key which
146 //! owns the value that it contains, and will destroy the value when the
147 //! thread exits. This variant is created with the `thread_local!` macro and
148 //! can contain any value which is `'static` (no borrowed pointers).
150 //! * Scoped thread-local storage. This type of key is used to store a reference
151 //! to a value into local storage temporarily for the scope of a function
152 //! call. There are no restrictions on what types of values can be placed
155 //! Both forms of thread local storage provide an accessor function, `with`,
156 //! which will yield a shared reference to the value to the specified
157 //! closure. Thread-local keys only allow shared access to values as there is no
158 //! way to guarantee uniqueness if a mutable borrow was allowed. Most values
159 //! will want to make use of some form of **interior mutability** through the
160 //! `Cell` or `RefCell` types.
162 #![stable(feature = "rust1", since = "1.0.0")]
167 use cell
::UnsafeCell
;
168 use ffi
::{CStr, CString}
;
174 use sync
::{Mutex, Condvar, Arc}
;
175 use sys
::thread
as imp
;
176 use sys_common
::thread_info
;
177 use sys_common
::util
;
178 use sys_common
::{AsInner, IntoInner}
;
181 ////////////////////////////////////////////////////////////////////////////////
182 // Thread-local storage
183 ////////////////////////////////////////////////////////////////////////////////
185 #[macro_use] mod local;
187 #[stable(feature = "rust1", since = "1.0.0")]
188 pub use self::local
::{LocalKey, LocalKeyState}
;
190 #[unstable(feature = "libstd_thread_internals", issue = "0")]
191 #[cfg(target_thread_local)]
192 #[doc(hidden)] pub use self::local::elf::Key as __ElfLocalKeyInner;
193 #[unstable(feature = "libstd_thread_internals", issue = "0")]
194 #[doc(hidden)] pub use self::local::os::Key as __OsLocalKeyInner;
196 ////////////////////////////////////////////////////////////////////////////////
198 ////////////////////////////////////////////////////////////////////////////////
200 /// Thread configuration. Provides detailed control over the properties
201 /// and behavior of new threads.
202 #[stable(feature = "rust1", since = "1.0.0")]
204 // A name for the thread-to-be, for identification in panic messages
205 name
: Option
<String
>,
206 // The size of the stack for the spawned thread
207 stack_size
: Option
<usize>,
211 /// Generates the base configuration for spawning a thread, from which
212 /// configuration methods can be chained.
213 #[stable(feature = "rust1", since = "1.0.0")]
214 pub fn new() -> Builder
{
221 /// Names the thread-to-be. Currently the name is used for identification
222 /// only in panic messages.
229 /// let builder = thread::Builder::new()
230 /// .name("foo".into());
232 /// let handler = builder.spawn(|| {
233 /// assert_eq!(thread::current().name(), Some("foo"))
236 /// handler.join().unwrap();
238 #[stable(feature = "rust1", since = "1.0.0")]
239 pub fn name(mut self, name
: String
) -> Builder
{
240 self.name
= Some(name
);
244 /// Sets the size of the stack for the new thread.
245 #[stable(feature = "rust1", since = "1.0.0")]
246 pub fn stack_size(mut self, size
: usize) -> Builder
{
247 self.stack_size
= Some(size
);
251 /// Spawns a new thread, and returns a join handle for it.
253 /// The child thread may outlive the parent (unless the parent thread
254 /// is the main thread; the whole process is terminated when the main
255 /// thread finishes). The join handle can be used to block on
256 /// termination of the child thread, including recovering its panics.
260 /// Unlike the `spawn` free function, this method yields an
261 /// `io::Result` to capture any failure to create the thread at
263 #[stable(feature = "rust1", since = "1.0.0")]
264 pub fn spawn
<F
, T
>(self, f
: F
) -> io
::Result
<JoinHandle
<T
>> where
265 F
: FnOnce() -> T
, F
: Send
+ '
static, T
: Send
+ '
static
267 let Builder { name, stack_size }
= self;
269 let stack_size
= stack_size
.unwrap_or(util
::min_stack());
271 let my_thread
= Thread
::new(name
);
272 let their_thread
= my_thread
.clone();
274 let my_packet
: Arc
<UnsafeCell
<Option
<Result
<T
>>>>
275 = Arc
::new(UnsafeCell
::new(None
));
276 let their_packet
= my_packet
.clone();
279 if let Some(name
) = their_thread
.cname() {
280 imp
::Thread
::set_name(name
);
283 thread_info
::set(imp
::guard
::current(), their_thread
);
284 let try_result
= panic
::catch_unwind(panic
::AssertUnwindSafe(f
));
285 *their_packet
.get() = Some(try_result
);
289 Ok(JoinHandle(JoinInner
{
291 Some(imp
::Thread
::new(stack_size
, Box
::new(main
))?
)
294 packet
: Packet(my_packet
),
299 ////////////////////////////////////////////////////////////////////////////////
301 ////////////////////////////////////////////////////////////////////////////////
303 /// Spawns a new thread, returning a `JoinHandle` for it.
305 /// The join handle will implicitly *detach* the child thread upon being
306 /// dropped. In this case, the child thread may outlive the parent (unless
307 /// the parent thread is the main thread; the whole process is terminated when
308 /// the main thread finishes.) Additionally, the join handle provides a `join`
309 /// method that can be used to join the child thread. If the child thread
310 /// panics, `join` will return an `Err` containing the argument given to
315 /// Panics if the OS fails to create a thread; use `Builder::spawn`
316 /// to recover from such errors.
317 #[stable(feature = "rust1", since = "1.0.0")]
318 pub fn spawn
<F
, T
>(f
: F
) -> JoinHandle
<T
> where
319 F
: FnOnce() -> T
, F
: Send
+ '
static, T
: Send
+ '
static
321 Builder
::new().spawn(f
).unwrap()
324 /// Gets a handle to the thread that invokes it.
325 #[stable(feature = "rust1", since = "1.0.0")]
326 pub fn current() -> Thread
{
327 thread_info
::current_thread().expect("use of std::thread::current() is not \
328 possible after the thread's local \
329 data has been destroyed")
332 /// Cooperatively gives up a timeslice to the OS scheduler.
333 #[stable(feature = "rust1", since = "1.0.0")]
335 imp
::Thread
::yield_now()
338 /// Determines whether the current thread is unwinding because of panic.
342 /// ```rust,should_panic
345 /// struct SomeStruct;
347 /// impl Drop for SomeStruct {
348 /// fn drop(&mut self) {
349 /// if thread::panicking() {
350 /// println!("dropped while unwinding");
352 /// println!("dropped while not unwinding");
359 /// let a = SomeStruct;
364 /// let b = SomeStruct;
369 #[stable(feature = "rust1", since = "1.0.0")]
370 pub fn panicking() -> bool
{
371 panicking
::panicking()
374 /// Puts the current thread to sleep for the specified amount of time.
376 /// The thread may sleep longer than the duration specified due to scheduling
377 /// specifics or platform-dependent functionality. Note that on unix platforms
378 /// this function will not return early due to a signal being received or a
380 #[stable(feature = "rust1", since = "1.0.0")]
381 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::sleep`")]
382 pub fn sleep_ms(ms
: u32) {
383 sleep(Duration
::from_millis(ms
as u64))
386 /// Puts the current thread to sleep for the specified amount of time.
388 /// The thread may sleep longer than the duration specified due to scheduling
389 /// specifics or platform-dependent functionality.
391 /// # Platform behavior
393 /// On Unix platforms this function will not return early due to a
394 /// signal being received or a spurious wakeup. Platforms which do not support
395 /// nanosecond precision for sleeping will have `dur` rounded up to the nearest
396 /// granularity of time they can sleep for.
401 /// use std::{thread, time};
403 /// let ten_millis = time::Duration::from_millis(10);
404 /// let now = time::Instant::now();
406 /// thread::sleep(ten_millis);
408 /// assert!(now.elapsed() >= ten_millis);
410 #[stable(feature = "thread_sleep", since = "1.4.0")]
411 pub fn sleep(dur
: Duration
) {
412 imp
::Thread
::sleep(dur
)
415 /// Blocks unless or until the current thread's token is made available.
417 /// Every thread is equipped with some basic low-level blocking support, via
418 /// the `park()` function and the [`unpark()`][unpark] method. These can be
419 /// used as a more CPU-efficient implementation of a spinlock.
421 /// [unpark]: struct.Thread.html#method.unpark
423 /// The API is typically used by acquiring a handle to the current thread,
424 /// placing that handle in a shared data structure so that other threads can
425 /// find it, and then parking (in a loop with a check for the token actually
428 /// A call to `park` does not guarantee that the thread will remain parked
429 /// forever, and callers should be prepared for this possibility.
431 /// See the [module documentation][thread] for more detail.
433 /// [thread]: index.html
435 // The implementation currently uses the trivial strategy of a Mutex+Condvar
436 // with wakeup flag, which does not actually allow spurious wakeups. In the
437 // future, this will be implemented in a more efficient way, perhaps along the lines of
438 // http://cr.openjdk.java.net/~stefank/6989984.1/raw_files/new/src/os/linux/vm/os_linux.cpp
439 // or futuxes, and in either case may allow spurious wakeups.
440 #[stable(feature = "rust1", since = "1.0.0")]
442 let thread
= current();
443 let mut guard
= thread
.inner
.lock
.lock().unwrap();
445 guard
= thread
.inner
.cvar
.wait(guard
).unwrap();
450 /// Blocks unless or until the current thread's token is made available or
451 /// the specified duration has been reached (may wake spuriously).
453 /// The semantics of this function are equivalent to `park()` except that the
454 /// thread will be blocked for roughly no longer than `ms`. This method
455 /// should not be used for precise timing due to anomalies such as
456 /// preemption or platform differences that may not cause the maximum
457 /// amount of time waited to be precisely `ms` long.
459 /// See the module doc for more detail.
460 #[stable(feature = "rust1", since = "1.0.0")]
461 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::park_timeout`")]
462 pub fn park_timeout_ms(ms
: u32) {
463 park_timeout(Duration
::from_millis(ms
as u64))
466 /// Blocks unless or until the current thread's token is made available or
467 /// the specified duration has been reached (may wake spuriously).
469 /// The semantics of this function are equivalent to `park()` except that the
470 /// thread will be blocked for roughly no longer than `dur`. This method
471 /// should not be used for precise timing due to anomalies such as
472 /// preemption or platform differences that may not cause the maximum
473 /// amount of time waited to be precisely `dur` long.
475 /// See the module doc for more detail.
477 /// # Platform behavior
479 /// Platforms which do not support nanosecond precision for sleeping will have
480 /// `dur` rounded up to the nearest granularity of time they can sleep for.
481 #[stable(feature = "park_timeout", since = "1.4.0")]
482 pub fn park_timeout(dur
: Duration
) {
483 let thread
= current();
484 let mut guard
= thread
.inner
.lock
.lock().unwrap();
486 let (g
, _
) = thread
.inner
.cvar
.wait_timeout(guard
, dur
).unwrap();
492 ////////////////////////////////////////////////////////////////////////////////
494 ////////////////////////////////////////////////////////////////////////////////
496 /// The internal representation of a `Thread` handle
498 name
: Option
<CString
>, // Guaranteed to be UTF-8
499 lock
: Mutex
<bool
>, // true when there is a buffered unpark
504 #[stable(feature = "rust1", since = "1.0.0")]
505 /// A handle to a thread.
511 // Used only internally to construct a thread object without spawning
512 fn new(name
: Option
<String
>) -> Thread
{
513 let cname
= name
.map(|n
| {
514 CString
::new(n
).expect("thread name may not contain interior null bytes")
517 inner
: Arc
::new(Inner
{
519 lock
: Mutex
::new(false),
520 cvar
: Condvar
::new(),
525 /// Atomically makes the handle's token available if it is not already.
527 /// See the module doc for more detail.
528 #[stable(feature = "rust1", since = "1.0.0")]
529 pub fn unpark(&self) {
530 let mut guard
= self.inner
.lock
.lock().unwrap();
533 self.inner
.cvar
.notify_one();
537 /// Gets the thread's name.
541 /// Threads by default have no name specified:
546 /// let builder = thread::Builder::new();
548 /// let handler = builder.spawn(|| {
549 /// assert!(thread::current().name().is_none());
552 /// handler.join().unwrap();
555 /// Thread with a specified name:
560 /// let builder = thread::Builder::new()
561 /// .name("foo".into());
563 /// let handler = builder.spawn(|| {
564 /// assert_eq!(thread::current().name(), Some("foo"))
567 /// handler.join().unwrap();
569 #[stable(feature = "rust1", since = "1.0.0")]
570 pub fn name(&self) -> Option
<&str> {
571 self.cname().map(|s
| unsafe { str::from_utf8_unchecked(s.to_bytes()) }
)
574 fn cname(&self) -> Option
<&CStr
> {
575 self.inner
.name
.as_ref().map(|s
| &**s
)
579 #[stable(feature = "rust1", since = "1.0.0")]
580 impl fmt
::Debug
for Thread
{
581 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
582 fmt
::Debug
::fmt(&self.name(), f
)
586 // a hack to get around privacy restrictions
587 impl thread_info
::NewThread
for Thread
{
588 fn new(name
: Option
<String
>) -> Thread { Thread::new(name) }
591 ////////////////////////////////////////////////////////////////////////////////
593 ////////////////////////////////////////////////////////////////////////////////
595 /// Indicates the manner in which a thread exited.
597 /// A thread that completes without panicking is considered to exit successfully.
598 #[stable(feature = "rust1", since = "1.0.0")]
599 pub type Result
<T
> = ::result
::Result
<T
, Box
<Any
+ Send
+ '
static>>;
601 // This packet is used to communicate the return value between the child thread
602 // and the parent thread. Memory is shared through the `Arc` within and there's
603 // no need for a mutex here because synchronization happens with `join()` (the
604 // parent thread never reads this packet until the child has exited).
606 // This packet itself is then stored into a `JoinInner` which in turns is placed
607 // in `JoinHandle` and `JoinGuard`. Due to the usage of `UnsafeCell` we need to
608 // manually worry about impls like Send and Sync. The type `T` should
609 // already always be Send (otherwise the thread could not have been created) and
610 // this type is inherently Sync because no methods take &self. Regardless,
611 // however, we add inheriting impls for Send/Sync to this type to ensure it's
612 // Send/Sync and that future modifications will still appropriately classify it.
613 struct Packet
<T
>(Arc
<UnsafeCell
<Option
<Result
<T
>>>>);
615 unsafe impl<T
: Send
> Send
for Packet
<T
> {}
616 unsafe impl<T
: Sync
> Sync
for Packet
<T
> {}
618 /// Inner representation for JoinHandle
619 struct JoinInner
<T
> {
620 native
: Option
<imp
::Thread
>,
625 impl<T
> JoinInner
<T
> {
626 fn join(&mut self) -> Result
<T
> {
627 self.native
.take().unwrap().join();
629 (*self.packet
.0.get()).take().unwrap()
634 /// An owned permission to join on a thread (block on its termination).
636 /// A `JoinHandle` *detaches* the child thread when it is dropped.
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 /// This `struct` is created by the [`thread::spawn`] function and the
643 /// [`thread::Builder::spawn`] method.
647 /// Creation from [`thread::spawn`]:
652 /// let join_handle: thread::JoinHandle<_> = thread::spawn(|| {
653 /// // some work here
657 /// Creation from [`thread::Builder::spawn`]:
662 /// let builder = thread::Builder::new();
664 /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| {
665 /// // some work here
669 /// [`thread::spawn`]: fn.spawn.html
670 /// [`thread::Builder::spawn`]: struct.Builder.html#method.spawn
671 #[stable(feature = "rust1", since = "1.0.0")]
672 pub struct JoinHandle
<T
>(JoinInner
<T
>);
674 impl<T
> JoinHandle
<T
> {
675 /// Extracts a handle to the underlying thread
676 #[stable(feature = "rust1", since = "1.0.0")]
677 pub fn thread(&self) -> &Thread
{
681 /// Waits for the associated thread to finish.
683 /// If the child thread panics, `Err` is returned with the parameter given
685 #[stable(feature = "rust1", since = "1.0.0")]
686 pub fn join(mut self) -> Result
<T
> {
691 impl<T
> AsInner
<imp
::Thread
> for JoinHandle
<T
> {
692 fn as_inner(&self) -> &imp
::Thread { self.0.native.as_ref().unwrap() }
695 impl<T
> IntoInner
<imp
::Thread
> for JoinHandle
<T
> {
696 fn into_inner(self) -> imp
::Thread { self.0.native.unwrap() }
699 fn _assert_sync_and_send() {
700 fn _assert_both
<T
: Send
+ Sync
>() {}
701 _assert_both
::<JoinHandle
<()>>();
702 _assert_both
::<Thread
>();
705 ////////////////////////////////////////////////////////////////////////////////
707 ////////////////////////////////////////////////////////////////////////////////
714 use sync
::mpsc
::{channel, Sender}
;
716 use super::{Builder}
;
721 // !!! These tests are dangerous. If something is buggy, they will hang, !!!
722 // !!! instead of exiting cleanly. This might wedge the buildbots. !!!
725 fn test_unnamed_thread() {
726 thread
::spawn(move|| {
727 assert
!(thread
::current().name().is_none());
728 }).join().ok().unwrap();
732 fn test_named_thread() {
733 Builder
::new().name("ada lovelace".to_string()).spawn(move|| {
734 assert
!(thread
::current().name().unwrap() == "ada lovelace".to_string());
735 }).unwrap().join().unwrap();
740 fn test_invalid_named_thread() {
741 let _
= Builder
::new().name("ada l\0velace".to_string()).spawn(|| {}
);
745 fn test_run_basic() {
746 let (tx
, rx
) = channel();
747 thread
::spawn(move|| {
748 tx
.send(()).unwrap();
754 fn test_join_panic() {
755 match thread
::spawn(move|| {
758 result
::Result
::Err(_
) => (),
759 result
::Result
::Ok(()) => panic
!()
764 fn test_spawn_sched() {
767 let (tx
, rx
) = channel();
769 fn f(i
: i32, tx
: Sender
<()>) {
771 thread
::spawn(move|| {
773 tx
.send(()).unwrap();
785 fn test_spawn_sched_childs_on_default_sched() {
786 let (tx
, rx
) = channel();
788 thread
::spawn(move|| {
789 thread
::spawn(move|| {
790 tx
.send(()).unwrap();
797 fn avoid_copying_the_body
<F
>(spawnfn
: F
) where F
: FnOnce(Box
<Fn() + Send
>) {
798 let (tx
, rx
) = channel();
800 let x
: Box
<_
> = box 1;
801 let x_in_parent
= (&*x
) as *const i32 as usize;
803 spawnfn(Box
::new(move|| {
804 let x_in_child
= (&*x
) as *const i32 as usize;
805 tx
.send(x_in_child
).unwrap();
808 let x_in_child
= rx
.recv().unwrap();
809 assert_eq
!(x_in_parent
, x_in_child
);
813 fn test_avoid_copying_the_body_spawn() {
814 avoid_copying_the_body(|v
| {
815 thread
::spawn(move || v());
820 fn test_avoid_copying_the_body_thread_spawn() {
821 avoid_copying_the_body(|f
| {
822 thread
::spawn(move|| {
829 fn test_avoid_copying_the_body_join() {
830 avoid_copying_the_body(|f
| {
831 let _
= thread
::spawn(move|| {
838 fn test_child_doesnt_ref_parent() {
839 // If the child refcounts the parent thread, this will stack overflow when
840 // climbing the thread tree to dereference each ancestor. (See #1789)
841 // (well, it would if the constant were 8000+ - I lowered it to be more
842 // valgrind-friendly. try this at home, instead..!)
843 const GENERATIONS
: u32 = 16;
844 fn child_no(x
: u32) -> Box
<Fn() + Send
> {
845 return Box
::new(move|| {
847 thread
::spawn(move|| child_no(x
+1)());
851 thread
::spawn(|| child_no(0)());
855 fn test_simple_newsched_spawn() {
856 thread
::spawn(move || {}
);
860 fn test_try_panic_message_static_str() {
861 match thread
::spawn(move|| {
862 panic
!("static string");
865 type T
= &'
static str;
866 assert
!(e
.is
::<T
>());
867 assert_eq
!(*e
.downcast
::<T
>().unwrap(), "static string");
874 fn test_try_panic_message_owned_str() {
875 match thread
::spawn(move|| {
876 panic
!("owned string".to_string());
880 assert
!(e
.is
::<T
>());
881 assert_eq
!(*e
.downcast
::<T
>().unwrap(), "owned string".to_string());
888 fn test_try_panic_message_any() {
889 match thread
::spawn(move|| {
890 panic
!(box 413u16 as Box
<Any
+ Send
>);
893 type T
= Box
<Any
+ Send
>;
894 assert
!(e
.is
::<T
>());
895 let any
= e
.downcast
::<T
>().unwrap();
896 assert
!(any
.is
::<u16>());
897 assert_eq
!(*any
.downcast
::<u16>().unwrap(), 413);
904 fn test_try_panic_message_unit_struct() {
907 match thread
::spawn(move|| {
910 Err(ref e
) if e
.is
::<Juju
>() => {}
911 Err(_
) | Ok(()) => panic
!()
916 fn test_park_timeout_unpark_before() {
918 thread
::current().unpark();
919 thread
::park_timeout(Duration
::from_millis(u32::MAX
as u64));
924 fn test_park_timeout_unpark_not_called() {
926 thread
::park_timeout(Duration
::from_millis(10));
931 fn test_park_timeout_unpark_called_other_thread() {
933 let th
= thread
::current();
935 let _guard
= thread
::spawn(move || {
936 super::sleep(Duration
::from_millis(50));
940 thread
::park_timeout(Duration
::from_millis(u32::MAX
as u64));
945 fn sleep_ms_smoke() {
946 thread
::sleep(Duration
::from_millis(2));
949 // NOTE: the corresponding test for stderr is in run-pass/thread-stderr, due
950 // to the test harness apparently interfering with stderr configuration.