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
29 use sync::{StaticMutex, StaticCondvar};
30 use sync::mpsc::{channel, Sender, Receiver};
31 use sys::helper_signal;
35 /// A structure for management of a helper thread.
37 /// This is generally a static structure which tracks the lifetime of a helper
40 /// The fields of this helper are all public, but they should not be used, this
41 /// is for static initialization.
42 pub struct Helper<M> {
43 /// Internal lock which protects the remaining fields
44 pub lock: StaticMutex,
45 pub cond: StaticCondvar,
47 // You'll notice that the remaining fields are UnsafeCell<T>, and this is
48 // because all helper thread operations are done through &self, but we need
49 // these to be mutable (once `lock` is held).
51 /// Lazily allocated channel to send messages to the helper thread.
52 pub chan: UnsafeCell<*mut Sender<M>>,
54 /// OS handle used to wake up a blocked helper thread
55 pub signal: UnsafeCell<uint>,
57 /// Flag if this helper thread has booted and been initialized yet.
58 pub initialized: UnsafeCell<bool>,
60 /// Flag if this helper thread has shut down
61 pub shutdown: UnsafeCell<bool>,
64 unsafe impl<M:Send> Send for Helper<M> { }
66 unsafe impl<M:Send> Sync for Helper<M> { }
68 struct RaceBox(helper_signal::signal);
70 unsafe impl Send for RaceBox {}
71 unsafe impl Sync for RaceBox {}
73 impl<M: Send> Helper<M> {
74 /// Lazily boots a helper thread, becoming a no-op if the helper has already
77 /// This function will check to see if the thread has been initialized, and
78 /// if it has it returns quickly. If initialization has not happened yet,
79 /// the closure `f` will be run (inside of the initialization lock) and
80 /// passed to the helper thread in a separate task.
82 /// This function is safe to be called many times.
83 pub fn boot<T, F>(&'static self, f: F, helper: fn(helper_signal::signal, Receiver<M>, T)) where
88 let _guard = self.lock.lock().unwrap();
89 if !*self.initialized.get() {
90 let (tx, rx) = channel();
91 *self.chan.get() = mem::transmute(box tx);
92 let (receive, send) = helper_signal::new();
93 *self.signal.get() = send as uint;
95 let receive = RaceBox(receive);
98 Thread::spawn(move |:| {
99 helper(receive.0, rx, t);
100 let _g = self.lock.lock().unwrap();
101 *self.shutdown.get() = true;
102 self.cond.notify_one()
105 rt::at_exit(move|:| { self.shutdown() });
106 *self.initialized.get() = true;
111 /// Sends a message to a spawned worker thread.
113 /// This is only valid if the worker thread has previously booted
114 pub fn send(&'static self, msg: M) {
116 let _guard = self.lock.lock().unwrap();
118 // Must send and *then* signal to ensure that the child receives the
119 // message. Otherwise it could wake up and go to sleep before we
121 assert!(!self.chan.get().is_null());
122 (**self.chan.get()).send(msg).unwrap();
123 helper_signal::signal(*self.signal.get() as helper_signal::signal);
127 fn shutdown(&'static self) {
129 // Shut down, but make sure this is done inside our lock to ensure
130 // that we'll always receive the exit signal when the thread
132 let mut guard = self.lock.lock().unwrap();
134 // Close the channel by destroying it
135 let chan: Box<Sender<M>> = mem::transmute(*self.chan.get());
136 *self.chan.get() = ptr::null_mut();
138 helper_signal::signal(*self.signal.get() as helper_signal::signal);
140 // Wait for the child to exit
141 while !*self.shutdown.get() {
142 guard = self.cond.wait(guard).unwrap();
146 // Clean up after ourselves
148 helper_signal::close(*self.signal.get() as helper_signal::signal);
149 *self.signal.get() = 0;