]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/common/helper_thread.rs
auto merge of #21132 : sfackler/rust/wait_timeout, r=alexcrichton
[rust.git] / src / libstd / sys / common / helper_thread.rs
1 // Copyright 2013-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 //! Implementation of the helper thread for the timer module
12 //!
13 //! This module contains the management necessary for the timer worker thread.
14 //! This thread is responsible for performing the send()s on channels for timers
15 //! that are using channels instead of a blocking call.
16 //!
17 //! The timer thread is lazily initialized, and it's shut down via the
18 //! `shutdown` function provided. It must be maintained as an invariant that
19 //! `shutdown` is only called when the entire program is finished. No new timers
20 //! can be created in the future and there must be no active timers at that
21 //! time.
22
23 use prelude::v1::*;
24
25 use cell::UnsafeCell;
26 use mem;
27 use rt;
28 use sync::{StaticMutex, StaticCondvar};
29 use sync::mpsc::{channel, Sender, Receiver};
30 use sys::helper_signal;
31
32 use thread::Thread;
33
34 /// A structure for management of a helper thread.
35 ///
36 /// This is generally a static structure which tracks the lifetime of a helper
37 /// thread.
38 ///
39 /// The fields of this helper are all public, but they should not be used, this
40 /// is for static initialization.
41 pub struct Helper<M> {
42     /// Internal lock which protects the remaining fields
43     pub lock: StaticMutex,
44     pub cond: StaticCondvar,
45
46     // You'll notice that the remaining fields are UnsafeCell<T>, and this is
47     // because all helper thread operations are done through &self, but we need
48     // these to be mutable (once `lock` is held).
49
50     /// Lazily allocated channel to send messages to the helper thread.
51     pub chan: UnsafeCell<*mut Sender<M>>,
52
53     /// OS handle used to wake up a blocked helper thread
54     pub signal: UnsafeCell<uint>,
55
56     /// Flag if this helper thread has booted and been initialized yet.
57     pub initialized: UnsafeCell<bool>,
58
59     /// Flag if this helper thread has shut down
60     pub shutdown: UnsafeCell<bool>,
61 }
62
63 unsafe impl<M:Send> Send for Helper<M> { }
64
65 unsafe impl<M:Send> Sync for Helper<M> { }
66
67 struct RaceBox(helper_signal::signal);
68
69 unsafe impl Send for RaceBox {}
70 unsafe impl Sync for RaceBox {}
71
72 impl<M: Send> Helper<M> {
73     /// Lazily boots a helper thread, becoming a no-op if the helper has already
74     /// been spawned.
75     ///
76     /// This function will check to see if the thread has been initialized, and
77     /// if it has it returns quickly. If initialization has not happened yet,
78     /// the closure `f` will be run (inside of the initialization lock) and
79     /// passed to the helper thread in a separate task.
80     ///
81     /// This function is safe to be called many times.
82     pub fn boot<T, F>(&'static self, f: F, helper: fn(helper_signal::signal, Receiver<M>, T)) where
83         T: Send,
84         F: FnOnce() -> T,
85     {
86         unsafe {
87             let _guard = self.lock.lock().unwrap();
88             if !*self.initialized.get() {
89                 let (tx, rx) = channel();
90                 *self.chan.get() = mem::transmute(box tx);
91                 let (receive, send) = helper_signal::new();
92                 *self.signal.get() = send as uint;
93
94                 let receive = RaceBox(receive);
95
96                 let t = f();
97                 Thread::spawn(move |:| {
98                     helper(receive.0, rx, t);
99                     let _g = self.lock.lock().unwrap();
100                     *self.shutdown.get() = true;
101                     self.cond.notify_one()
102                 });
103
104                 rt::at_exit(move|:| { self.shutdown() });
105                 *self.initialized.get() = true;
106             }
107         }
108     }
109
110     /// Sends a message to a spawned worker thread.
111     ///
112     /// This is only valid if the worker thread has previously booted
113     pub fn send(&'static self, msg: M) {
114         unsafe {
115             let _guard = self.lock.lock().unwrap();
116
117             // Must send and *then* signal to ensure that the child receives the
118             // message. Otherwise it could wake up and go to sleep before we
119             // send the message.
120             assert!(!self.chan.get().is_null());
121             (**self.chan.get()).send(msg).unwrap();
122             helper_signal::signal(*self.signal.get() as helper_signal::signal);
123         }
124     }
125
126     fn shutdown(&'static self) {
127         unsafe {
128             // Shut down, but make sure this is done inside our lock to ensure
129             // that we'll always receive the exit signal when the thread
130             // returns.
131             let mut guard = self.lock.lock().unwrap();
132
133             // Close the channel by destroying it
134             let chan: Box<Sender<M>> = mem::transmute(*self.chan.get());
135             *self.chan.get() = 0 as *mut Sender<M>;
136             drop(chan);
137             helper_signal::signal(*self.signal.get() as helper_signal::signal);
138
139             // Wait for the child to exit
140             while !*self.shutdown.get() {
141                 guard = self.cond.wait(guard).unwrap();
142             }
143             drop(guard);
144
145             // Clean up after ourselves
146             self.lock.destroy();
147             helper_signal::close(*self.signal.get() as helper_signal::signal);
148             *self.signal.get() = 0;
149         }
150     }
151 }