]> git.lizzy.rs Git - rust.git/blob - src/libnative/io/helper_thread.rs
Doc says to avoid mixing allocator instead of forbiding it
[rust.git] / src / libnative / io / 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 #![macro_escape]
24
25 use std::mem;
26 use std::rt::bookkeeping;
27 use std::rt::mutex::StaticNativeMutex;
28 use std::rt;
29 use std::cell::UnsafeCell;
30
31 use task;
32
33 /// A structure for management of a helper thread.
34 ///
35 /// This is generally a static structure which tracks the lifetime of a helper
36 /// thread.
37 ///
38 /// The fields of this helper are all public, but they should not be used, this
39 /// is for static initialization.
40 pub struct Helper<M> {
41     /// Internal lock which protects the remaining fields
42     pub lock: StaticNativeMutex,
43
44     // You'll notice that the remaining fields are UnsafeCell<T>, and this is
45     // because all helper thread operations are done through &self, but we need
46     // these to be mutable (once `lock` is held).
47
48     /// Lazily allocated channel to send messages to the helper thread.
49     pub chan: UnsafeCell<*mut Sender<M>>,
50
51     /// OS handle used to wake up a blocked helper thread
52     pub signal: UnsafeCell<uint>,
53
54     /// Flag if this helper thread has booted and been initialized yet.
55     pub initialized: UnsafeCell<bool>,
56 }
57
58 macro_rules! helper_init( (static mut $name:ident: Helper<$m:ty>) => (
59     static mut $name: Helper<$m> = Helper {
60         lock: ::std::rt::mutex::NATIVE_MUTEX_INIT,
61         chan: ::std::cell::UnsafeCell { value: 0 as *mut Sender<$m> },
62         signal: ::std::cell::UnsafeCell { value: 0 },
63         initialized: ::std::cell::UnsafeCell { value: false },
64     };
65 ) )
66
67 impl<M: Send> Helper<M> {
68     /// Lazily boots a helper thread, becoming a no-op if the helper has already
69     /// been spawned.
70     ///
71     /// This function will check to see if the thread has been initialized, and
72     /// if it has it returns quickly. If initialization has not happened yet,
73     /// the closure `f` will be run (inside of the initialization lock) and
74     /// passed to the helper thread in a separate task.
75     ///
76     /// This function is safe to be called many times.
77     pub fn boot<T: Send>(&'static self,
78                          f: || -> T,
79                          helper: fn(imp::signal, Receiver<M>, T)) {
80         unsafe {
81             let _guard = self.lock.lock();
82             if !*self.initialized.get() {
83                 let (tx, rx) = channel();
84                 *self.chan.get() = mem::transmute(box tx);
85                 let (receive, send) = imp::new();
86                 *self.signal.get() = send as uint;
87
88                 let t = f();
89                 task::spawn(proc() {
90                     bookkeeping::decrement();
91                     helper(receive, rx, t);
92                     self.lock.lock().signal()
93                 });
94
95                 rt::at_exit(proc() { self.shutdown() });
96                 *self.initialized.get() = true;
97             }
98         }
99     }
100
101     /// Sends a message to a spawned worker thread.
102     ///
103     /// This is only valid if the worker thread has previously booted
104     pub fn send(&'static self, msg: M) {
105         unsafe {
106             let _guard = self.lock.lock();
107
108             // Must send and *then* signal to ensure that the child receives the
109             // message. Otherwise it could wake up and go to sleep before we
110             // send the message.
111             assert!(!self.chan.get().is_null());
112             (**self.chan.get()).send(msg);
113             imp::signal(*self.signal.get() as imp::signal);
114         }
115     }
116
117     fn shutdown(&'static self) {
118         unsafe {
119             // Shut down, but make sure this is done inside our lock to ensure
120             // that we'll always receive the exit signal when the thread
121             // returns.
122             let guard = self.lock.lock();
123
124             // Close the channel by destroying it
125             let chan: Box<Sender<M>> = mem::transmute(*self.chan.get());
126             *self.chan.get() = 0 as *mut Sender<M>;
127             drop(chan);
128             imp::signal(*self.signal.get() as imp::signal);
129
130             // Wait for the child to exit
131             guard.wait();
132             drop(guard);
133
134             // Clean up after ourselves
135             self.lock.destroy();
136             imp::close(*self.signal.get() as imp::signal);
137             *self.signal.get() = 0;
138         }
139     }
140 }
141
142 #[cfg(unix)]
143 mod imp {
144     use libc;
145     use std::os;
146
147     use io::file::FileDesc;
148
149     pub type signal = libc::c_int;
150
151     pub fn new() -> (signal, signal) {
152         let os::Pipe { reader, writer } = unsafe { os::pipe().unwrap() };
153         (reader, writer)
154     }
155
156     pub fn signal(fd: libc::c_int) {
157         FileDesc::new(fd, false).inner_write([0]).ok().unwrap();
158     }
159
160     pub fn close(fd: libc::c_int) {
161         let _fd = FileDesc::new(fd, true);
162     }
163 }
164
165 #[cfg(windows)]
166 mod imp {
167     use libc::{BOOL, LPCSTR, HANDLE, LPSECURITY_ATTRIBUTES, CloseHandle};
168     use std::ptr;
169     use libc;
170
171     pub type signal = HANDLE;
172
173     pub fn new() -> (HANDLE, HANDLE) {
174         unsafe {
175             let handle = CreateEventA(ptr::mut_null(), libc::FALSE, libc::FALSE,
176                                       ptr::null());
177             (handle, handle)
178         }
179     }
180
181     pub fn signal(handle: HANDLE) {
182         assert!(unsafe { SetEvent(handle) != 0 });
183     }
184
185     pub fn close(handle: HANDLE) {
186         assert!(unsafe { CloseHandle(handle) != 0 });
187     }
188
189     extern "system" {
190         fn CreateEventA(lpSecurityAttributes: LPSECURITY_ATTRIBUTES,
191                         bManualReset: BOOL,
192                         bInitialState: BOOL,
193                         lpName: LPCSTR) -> HANDLE;
194         fn SetEvent(hEvent: HANDLE) -> BOOL;
195     }
196 }