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.
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.
11 //! Implementation of the helper thread for the timer module
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.
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
28 use sync::{StaticMutex, StaticCondvar};
29 use sync::mpsc::{channel, Sender, Receiver};
30 use sys::helper_signal;
34 /// A structure for management of a helper thread.
36 /// This is generally a static structure which tracks the lifetime of a helper
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,
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).
50 /// Lazily allocated channel to send messages to the helper thread.
51 pub chan: UnsafeCell<*mut Sender<M>>,
53 /// OS handle used to wake up a blocked helper thread
54 pub signal: UnsafeCell<uint>,
56 /// Flag if this helper thread has booted and been initialized yet.
57 pub initialized: UnsafeCell<bool>,
59 /// Flag if this helper thread has shut down
60 pub shutdown: UnsafeCell<bool>,
63 unsafe impl<M:Send> Send for Helper<M> { }
65 unsafe impl<M:Send> Sync for Helper<M> { }
67 struct RaceBox(helper_signal::signal);
69 unsafe impl Send for RaceBox {}
70 unsafe impl Sync for RaceBox {}
72 impl<M: Send> Helper<M> {
73 /// Lazily boots a helper thread, becoming a no-op if the helper has already
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.
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
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;
94 let receive = RaceBox(receive);
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()
104 rt::at_exit(move|:| { self.shutdown() });
105 *self.initialized.get() = true;
110 /// Sends a message to a spawned worker thread.
112 /// This is only valid if the worker thread has previously booted
113 pub fn send(&'static self, msg: M) {
115 let _guard = self.lock.lock().unwrap();
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
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);
126 fn shutdown(&'static self) {
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
131 let mut guard = self.lock.lock().unwrap();
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>;
137 helper_signal::signal(*self.signal.get() as helper_signal::signal);
139 // Wait for the child to exit
140 while !*self.shutdown.get() {
141 guard = self.cond.wait(guard).unwrap();
145 // Clean up after ourselves
147 helper_signal::close(*self.signal.get() as helper_signal::signal);
148 *self.signal.get() = 0;