]> git.lizzy.rs Git - rust.git/blob - src/libstd/thread.rs
rollup merge of #20353: alexcrichton/snapshots
[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/comm/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 guard = Thread::spawn(move || {
62 //!     println!("Hello, World!");
63 //!     // some computation here
64 //! });
65 //! let result = guard.join();
66 //! ```
67 //!
68 //! The `spawn` function doesn't return a `Thread` directly; instead, it returns
69 //! a *join guard* from which a `Thread` can be extracted. The join guard is an
70 //! RAII-style guard that will automatically join the child thread (block until
71 //! it terminates) when it is dropped. You can join the child thread in advance
72 //! by calling the `join` method on the guard, which will also return the result
73 //! produced by the thread.
74 //!
75 //! If you instead wish to *detach* the child thread, allowing it to outlive its
76 //! parent, you can use the `detach` method on the guard,
77 //!
78 //! A handle to the thread itself is available via the `thread` method on the
79 //! join guard.
80 //!
81 //! ## Configuring threads
82 //!
83 //! A new thread can be configured before it is spawned via the `Builder` type,
84 //! which currently allows you to set the name, stack size, and writers for
85 //! `println!` and `panic!` for the child thread:
86 //!
87 //! ```rust
88 //! use std::thread;
89 //!
90 //! thread::Builder::new().name("child1".to_string()).spawn(move || {
91 //!     println!("Hello, world!")
92 //! }).detach();
93 //! ```
94 //!
95 //! ## Blocking support: park and unpark
96 //!
97 //! Every thread is equipped with some basic low-level blocking support, via the
98 //! `park` and `unpark` functions.
99 //!
100 //! Conceptually, each `Thread` handle has an associated token, which is
101 //! initially not present:
102 //!
103 //! * The `Thread::park()` function blocks the current thread unless or until
104 //!   the token is available for its thread handle, at which point It atomically
105 //!   consumes the token. It may also return *spuriously*, without consuming the
106 //!   token.
107 //!
108 //! * The `unpark()` method on a `Thread` atomically makes the token available
109 //!   if it wasn't already.
110 //!
111 //! In other words, each `Thread` acts a bit like a semaphore with initial count
112 //! 0, except that the semaphore is *saturating* (the count cannot go above 1),
113 //! and can return spuriously.
114 //!
115 //! The API is typically used by acquiring a handle to the current thread,
116 //! placing that handle in a shared data structure so that other threads can
117 //! find it, and then `park`ing. When some desired condition is met, another
118 //! thread calls `unpark` on the handle.
119 //!
120 //! The motivation for this design is twofold:
121 //!
122 //! * It avoids the need to allocate mutexes and condvars when building new
123 //!   synchronization primitives; the threads already provide basic blocking/signaling.
124 //!
125 //! * It can be implemented highly efficiently on many platforms.
126
127 use any::Any;
128 use borrow::IntoCow;
129 use boxed::Box;
130 use cell::UnsafeCell;
131 use clone::Clone;
132 use kinds::{Send, Sync};
133 use ops::{Drop, FnOnce};
134 use option::Option::{mod, Some, None};
135 use result::Result::{Err, Ok};
136 use sync::{Mutex, Condvar, Arc};
137 use str::Str;
138 use string::String;
139 use rt::{mod, unwind};
140 use io::{Writer, stdio};
141 use thunk::Thunk;
142
143 use sys::thread as imp;
144 use sys_common::{stack, thread_info};
145
146 /// Thread configuation. Provides detailed control over the properties
147 /// and behavior of new threads.
148 pub struct Builder {
149     // A name for the thread-to-be, for identification in panic messages
150     name: Option<String>,
151     // The size of the stack for the spawned thread
152     stack_size: Option<uint>,
153     // Thread-local stdout
154     stdout: Option<Box<Writer + Send>>,
155     // Thread-local stderr
156     stderr: Option<Box<Writer + Send>>,
157 }
158
159 impl Builder {
160     /// Generate the base configuration for spawning a thread, from which
161     /// configuration methods can be chained.
162     pub fn new() -> Builder {
163         Builder {
164             name: None,
165             stack_size: None,
166             stdout: None,
167             stderr: None,
168         }
169     }
170
171     /// Name the thread-to-be. Currently the name is used for identification
172     /// only in panic messages.
173     pub fn name(mut self, name: String) -> Builder {
174         self.name = Some(name);
175         self
176     }
177
178     /// Deprecated: use `name` instead
179     #[deprecated = "use name instead"]
180     pub fn named<T: IntoCow<'static, String, str>>(self, name: T) -> Builder {
181         self.name(name.into_cow().into_owned())
182     }
183
184     /// Set the size of the stack for the new thread.
185     pub fn stack_size(mut self, size: uint) -> Builder {
186         self.stack_size = Some(size);
187         self
188     }
189
190     /// Redirect thread-local stdout.
191     #[experimental = "Will likely go away after proc removal"]
192     pub fn stdout(mut self, stdout: Box<Writer + Send>) -> Builder {
193         self.stdout = Some(stdout);
194         self
195     }
196
197     /// Redirect thread-local stderr.
198     #[experimental = "Will likely go away after proc removal"]
199     pub fn stderr(mut self, stderr: Box<Writer + Send>) -> Builder {
200         self.stderr = Some(stderr);
201         self
202     }
203
204     /// Spawn a new joinable thread, and return a JoinGuard guard for it.
205     ///
206     /// See `Thead::spawn` and the module doc for more details.
207     pub fn spawn<T, F>(self, f: F) -> JoinGuard<T> where
208         T: Send, F: FnOnce() -> T, F: Send
209     {
210         self.spawn_inner(Thunk::new(f))
211     }
212
213     fn spawn_inner<T: Send>(self, f: Thunk<(), T>) -> JoinGuard<T> {
214         let my_packet = Packet(Arc::new(UnsafeCell::new(None)));
215         let their_packet = Packet(my_packet.0.clone());
216
217         let Builder { name, stack_size, stdout, stderr } = self;
218
219         let stack_size = stack_size.unwrap_or(rt::min_stack());
220         let my_thread = Thread::new(name);
221         let their_thread = my_thread.clone();
222
223         // Spawning a new OS thread guarantees that __morestack will never get
224         // triggered, but we must manually set up the actual stack bounds once
225         // this function starts executing. This raises the lower limit by a bit
226         // because by the time that this function is executing we've already
227         // consumed at least a little bit of stack (we don't know the exact byte
228         // address at which our stack started).
229         let main = move |:| {
230             let something_around_the_top_of_the_stack = 1;
231             let addr = &something_around_the_top_of_the_stack as *const int;
232             let my_stack_top = addr as uint;
233             let my_stack_bottom = my_stack_top - stack_size + 1024;
234             unsafe {
235                 stack::record_os_managed_stack_bounds(my_stack_bottom,
236                                                       my_stack_top);
237                 thread_info::set(imp::guard::current(), their_thread);
238             }
239
240             let mut output = None;
241             let f: Thunk<(), T> = if stdout.is_some() || stderr.is_some() {
242                 Thunk::new(move |:| {
243                     let _ = stdout.map(stdio::set_stdout);
244                     let _ = stderr.map(stdio::set_stderr);
245                     f.invoke(())
246                 })
247             } else {
248                 f
249             };
250
251             let try_result = {
252                 let ptr = &mut output;
253
254                 // There are two primary reasons that general try/catch is
255                 // unsafe. The first is that we do not support nested
256                 // try/catch. The fact that this is happening in a newly-spawned
257                 // thread suffices. The second is that unwinding while unwinding
258                 // is not defined.  We take care of that by having an
259                 // 'unwinding' flag in the thread itself. For these reasons,
260                 // this unsafety should be ok.
261                 unsafe {
262                     unwind::try(move || *ptr = Some(f.invoke(())))
263                 }
264             };
265             unsafe {
266                 *their_packet.0.get() = Some(match (output, try_result) {
267                     (Some(data), Ok(_)) => Ok(data),
268                     (None, Err(cause)) => Err(cause),
269                     _ => unreachable!()
270                 });
271             }
272         };
273
274         JoinGuard {
275             native: unsafe { imp::create(stack_size, Thunk::new(main)) },
276             joined: false,
277             packet: my_packet,
278             thread: my_thread,
279         }
280     }
281 }
282
283 struct Inner {
284     name: Option<String>,
285     lock: Mutex<bool>,          // true when there is a buffered unpark
286     cvar: Condvar,
287 }
288
289 unsafe impl Sync for Inner {}
290
291 #[deriving(Clone)]
292 /// A handle to a thread.
293 pub struct Thread {
294     inner: Arc<Inner>,
295 }
296
297 unsafe impl Sync for Thread {}
298
299 impl Thread {
300     // Used only internally to construct a thread object without spawning
301     fn new(name: Option<String>) -> Thread {
302         Thread {
303             inner: Arc::new(Inner {
304                 name: name,
305                 lock: Mutex::new(false),
306                 cvar: Condvar::new(),
307             })
308         }
309     }
310
311     /// Spawn a new joinable thread, returning a `JoinGuard` for it.
312     ///
313     /// The join guard can be used to explicitly join the child thread (via
314     /// `join`), returning `Result<T>`, or it will implicitly join the child
315     /// upon being dropped. To detach the child, allowing it to outlive the
316     /// current thread, use `detach`.  See the module documentation for additional details.
317     pub fn spawn<T, F>(f: F) -> JoinGuard<T> where
318         T: Send, F: FnOnce() -> T, F: Send
319     {
320         Builder::new().spawn(f)
321     }
322
323     /// Gets a handle to the thread that invokes it.
324     pub fn current() -> Thread {
325         thread_info::current_thread()
326     }
327
328     /// Cooperatively give up a timeslice to the OS scheduler.
329     pub fn yield_now() {
330         unsafe { imp::yield_now() }
331     }
332
333     /// Determines whether the current thread is panicking.
334     #[inline]
335     pub fn panicking() -> bool {
336         unwind::panicking()
337     }
338
339     /// Block unless or until the current thread's token is made available (may wake spuriously).
340     ///
341     /// See the module doc for more detail.
342     //
343     // The implementation currently uses the trivial strategy of a Mutex+Condvar
344     // with wakeup flag, which does not actually allow spurious wakeups. In the
345     // future, this will be implemented in a more efficient way, perhaps along the lines of
346     //   http://cr.openjdk.java.net/~stefank/6989984.1/raw_files/new/src/os/linux/vm/os_linux.cpp
347     // or futuxes, and in either case may allow spurious wakeups.
348     pub fn park() {
349         let thread = Thread::current();
350         let mut guard = thread.inner.lock.lock().unwrap();
351         while !*guard {
352             guard = thread.inner.cvar.wait(guard).unwrap();
353         }
354         *guard = false;
355     }
356
357     /// Atomically makes the handle's token available if it is not already.
358     ///
359     /// See the module doc for more detail.
360     pub fn unpark(&self) {
361         let mut guard = self.inner.lock.lock().unwrap();
362         if !*guard {
363             *guard = true;
364             self.inner.cvar.notify_one();
365         }
366     }
367
368     /// Get the thread's name.
369     pub fn name(&self) -> Option<&str> {
370         self.inner.name.as_ref().map(|s| s.as_slice())
371     }
372 }
373
374 // a hack to get around privacy restrictions
375 impl thread_info::NewThread for Thread {
376     fn new(name: Option<String>) -> Thread { Thread::new(name) }
377 }
378
379 /// Indicates the manner in which a thread exited.
380 ///
381 /// A thread that completes without panicking is considered to exit successfully.
382 pub type Result<T> = ::result::Result<T, Box<Any + Send>>;
383
384 struct Packet<T>(Arc<UnsafeCell<Option<Result<T>>>>);
385
386 unsafe impl<T:'static+Send> Send for Packet<T> {}
387 unsafe impl<T> Sync for Packet<T> {}
388
389 #[must_use]
390 /// An RAII-style guard that will block until thread termination when dropped.
391 ///
392 /// The type `T` is the return type for the thread's main function.
393 pub struct JoinGuard<T> {
394     native: imp::rust_thread,
395     thread: Thread,
396     joined: bool,
397     packet: Packet<T>,
398 }
399
400 unsafe impl<T: Send> Sync for JoinGuard<T> {}
401
402 impl<T: Send> JoinGuard<T> {
403     /// Extract a handle to the thread this guard will join on.
404     pub fn thread(&self) -> &Thread {
405         &self.thread
406     }
407
408     /// Wait for the associated thread to finish, returning the result of the thread's
409     /// calculation.
410     ///
411     /// If the child thread panics, `Err` is returned with the parameter given
412     /// to `panic`.
413     pub fn join(mut self) -> Result<T> {
414         assert!(!self.joined);
415         unsafe { imp::join(self.native) };
416         self.joined = true;
417         unsafe {
418             (*self.packet.0.get()).take().unwrap()
419         }
420     }
421
422     /// Detaches the child thread, allowing it to outlive its parent.
423     pub fn detach(mut self) {
424         unsafe { imp::detach(self.native) };
425         self.joined = true; // avoid joining in the destructor
426     }
427 }
428
429 #[unsafe_destructor]
430 impl<T: Send> Drop for JoinGuard<T> {
431     fn drop(&mut self) {
432         if !self.joined {
433             unsafe { imp::join(self.native) };
434         }
435     }
436 }
437
438 #[cfg(test)]
439 mod test {
440     use prelude::*;
441     use any::{Any, AnyRefExt};
442     use boxed::BoxAny;
443     use result;
444     use std::io::{ChanReader, ChanWriter};
445     use thunk::Thunk;
446     use super::{Thread, Builder};
447
448     // !!! These tests are dangerous. If something is buggy, they will hang, !!!
449     // !!! instead of exiting cleanly. This might wedge the buildbots.       !!!
450
451     #[test]
452     fn test_unnamed_thread() {
453         Thread::spawn(move|| {
454             assert!(Thread::current().name().is_none());
455         }).join().map_err(|_| ()).unwrap();
456     }
457
458     #[test]
459     fn test_named_thread() {
460         Builder::new().name("ada lovelace".to_string()).spawn(move|| {
461             assert!(Thread::current().name().unwrap() == "ada lovelace".to_string());
462         }).join().map_err(|_| ()).unwrap();
463     }
464
465     #[test]
466     fn test_run_basic() {
467         let (tx, rx) = channel();
468         Thread::spawn(move|| {
469             tx.send(());
470         }).detach();
471         rx.recv();
472     }
473
474     #[test]
475     fn test_join_success() {
476         match Thread::spawn(move|| -> String {
477             "Success!".to_string()
478         }).join().as_ref().map(|s| s.as_slice()) {
479             result::Result::Ok("Success!") => (),
480             _ => panic!()
481         }
482     }
483
484     #[test]
485     fn test_join_panic() {
486         match Thread::spawn(move|| {
487             panic!()
488         }).join() {
489             result::Result::Err(_) => (),
490             result::Result::Ok(()) => panic!()
491         }
492     }
493
494     #[test]
495     fn test_spawn_sched() {
496         use clone::Clone;
497
498         let (tx, rx) = channel();
499
500         fn f(i: int, tx: Sender<()>) {
501             let tx = tx.clone();
502             Thread::spawn(move|| {
503                 if i == 0 {
504                     tx.send(());
505                 } else {
506                     f(i - 1, tx);
507                 }
508             }).detach();
509
510         }
511         f(10, tx);
512         rx.recv();
513     }
514
515     #[test]
516     fn test_spawn_sched_childs_on_default_sched() {
517         let (tx, rx) = channel();
518
519         Thread::spawn(move|| {
520             Thread::spawn(move|| {
521                 tx.send(());
522             }).detach();
523         }).detach();
524
525         rx.recv();
526     }
527
528     fn avoid_copying_the_body<F>(spawnfn: F) where F: FnOnce(Thunk) {
529         let (tx, rx) = channel::<uint>();
530
531         let x = box 1;
532         let x_in_parent = (&*x) as *const int as uint;
533
534         spawnfn(Thunk::new(move|| {
535             let x_in_child = (&*x) as *const int as uint;
536             tx.send(x_in_child);
537         }));
538
539         let x_in_child = rx.recv();
540         assert_eq!(x_in_parent, x_in_child);
541     }
542
543     #[test]
544     fn test_avoid_copying_the_body_spawn() {
545         avoid_copying_the_body(|v| {
546             Thread::spawn(move || v.invoke(())).detach();
547         });
548     }
549
550     #[test]
551     fn test_avoid_copying_the_body_thread_spawn() {
552         avoid_copying_the_body(|f| {
553             Thread::spawn(move|| {
554                 f.invoke(());
555             }).detach();
556         })
557     }
558
559     #[test]
560     fn test_avoid_copying_the_body_join() {
561         avoid_copying_the_body(|f| {
562             let _ = Thread::spawn(move|| {
563                 f.invoke(())
564             }).join();
565         })
566     }
567
568     #[test]
569     fn test_child_doesnt_ref_parent() {
570         // If the child refcounts the parent task, this will stack overflow when
571         // climbing the task tree to dereference each ancestor. (See #1789)
572         // (well, it would if the constant were 8000+ - I lowered it to be more
573         // valgrind-friendly. try this at home, instead..!)
574         static GENERATIONS: uint = 16;
575         fn child_no(x: uint) -> Thunk {
576             return Thunk::new(move|| {
577                 if x < GENERATIONS {
578                     Thread::spawn(move|| child_no(x+1).invoke(())).detach();
579                 }
580             });
581         }
582         Thread::spawn(|| child_no(0).invoke(())).detach();
583     }
584
585     #[test]
586     fn test_simple_newsched_spawn() {
587         Thread::spawn(move || {}).detach();
588     }
589
590     #[test]
591     fn test_try_panic_message_static_str() {
592         match Thread::spawn(move|| {
593             panic!("static string");
594         }).join() {
595             Err(e) => {
596                 type T = &'static str;
597                 assert!(e.is::<T>());
598                 assert_eq!(*e.downcast::<T>().unwrap(), "static string");
599             }
600             Ok(()) => panic!()
601         }
602     }
603
604     #[test]
605     fn test_try_panic_message_owned_str() {
606         match Thread::spawn(move|| {
607             panic!("owned string".to_string());
608         }).join() {
609             Err(e) => {
610                 type T = String;
611                 assert!(e.is::<T>());
612                 assert_eq!(*e.downcast::<T>().unwrap(), "owned string".to_string());
613             }
614             Ok(()) => panic!()
615         }
616     }
617
618     #[test]
619     fn test_try_panic_message_any() {
620         match Thread::spawn(move|| {
621             panic!(box 413u16 as Box<Any + Send>);
622         }).join() {
623             Err(e) => {
624                 type T = Box<Any + Send>;
625                 assert!(e.is::<T>());
626                 let any = e.downcast::<T>().unwrap();
627                 assert!(any.is::<u16>());
628                 assert_eq!(*any.downcast::<u16>().unwrap(), 413u16);
629             }
630             Ok(()) => panic!()
631         }
632     }
633
634     #[test]
635     fn test_try_panic_message_unit_struct() {
636         struct Juju;
637
638         match Thread::spawn(move|| {
639             panic!(Juju)
640         }).join() {
641             Err(ref e) if e.is::<Juju>() => {}
642             Err(_) | Ok(()) => panic!()
643         }
644     }
645
646     #[test]
647     fn test_stdout() {
648         let (tx, rx) = channel();
649         let mut reader = ChanReader::new(rx);
650         let stdout = ChanWriter::new(tx);
651
652         let r = Builder::new().stdout(box stdout as Box<Writer + Send>).spawn(move|| {
653             print!("Hello, world!");
654         }).join();
655         assert!(r.is_ok());
656
657         let output = reader.read_to_string().unwrap();
658         assert_eq!(output, "Hello, world!".to_string());
659     }
660
661     // NOTE: the corresponding test for stderr is in run-pass/task-stderr, due
662     // to the test harness apparently interfering with stderr configuration.
663 }