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