Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(234)

Side by Side Diff: base/message_pump_win.h

Issue 8156: Switch MessagePumpForIO to use completion ports on Windows.... (Closed) Base URL: svn://chrome-svn/chrome/trunk/src/
Patch Set: '' Created 12 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « base/message_loop_unittest.cc ('k') | base/message_pump_win.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #ifndef BASE_MESSAGE_PUMP_WIN_H_ 5 #ifndef BASE_MESSAGE_PUMP_WIN_H_
6 #define BASE_MESSAGE_PUMP_WIN_H_ 6 #define BASE_MESSAGE_PUMP_WIN_H_
7 7
8 #include <vector> 8 #include <windows.h>
9 9
10 #include <windows.h> 10 #include <list>
11 11
12 #include "base/lock.h" 12 #include "base/lock.h"
13 #include "base/message_pump.h" 13 #include "base/message_pump.h"
14 #include "base/observer_list.h" 14 #include "base/observer_list.h"
15 #include "base/scoped_handle.h" 15 #include "base/scoped_handle.h"
16 #include "base/time.h" 16 #include "base/time.h"
17 17
18 namespace base { 18 namespace base {
19 19
20 // MessagePumpWin implements a "traditional" Windows message pump. It contains 20 // MessagePumpWin serves as the base for specialized versions of the MessagePump
21 // a nearly infinite loop that peeks out messages, and then dispatches them. 21 // for Windows. It provides basic functionality like handling of observers and
22 // Intermixed with those peeks are callouts to DoWork for pending tasks, 22 // controlling the lifetime of the message pump.
23 // DoDelayedWork for pending timers, and OnObjectSignaled for signaled objects.
24 // When there are no events to be serviced, this pump goes into a wait state.
25 // In most cases, this message pump handles all processing.
26 //
27 // However, when a task, or windows event, invokes on the stack a native dialog
28 // box or such, that window typically provides a bare bones (native?) message
29 // pump. That bare-bones message pump generally supports little more than a
30 // peek of the Windows message queue, followed by a dispatch of the peeked
31 // message. MessageLoop extends that bare-bones message pump to also service
32 // Tasks, at the cost of some complexity.
33 //
34 // The basic structure of the extension (refered to as a sub-pump) is that a
35 // special message, kMsgHaveWork, is repeatedly injected into the Windows
36 // Message queue. Each time the kMsgHaveWork message is peeked, checks are
37 // made for an extended set of events, including the availability of Tasks to
38 // run.
39 //
40 // After running a task, the special message kMsgHaveWork is again posted to
41 // the Windows Message queue, ensuring a future time slice for processing a
42 // future event. To prevent flooding the Windows Message queue, care is taken
43 // to be sure that at most one kMsgHaveWork message is EVER pending in the
44 // Window's Message queue.
45 //
46 // There are a few additional complexities in this system where, when there are
47 // no Tasks to run, this otherwise infinite stream of messages which drives the
48 // sub-pump is halted. The pump is automatically re-started when Tasks are
49 // queued.
50 //
51 // A second complexity is that the presence of this stream of posted tasks may
52 // prevent a bare-bones message pump from ever peeking a WM_PAINT or WM_TIMER.
53 // Such paint and timer events always give priority to a posted message, such as
54 // kMsgHaveWork messages. As a result, care is taken to do some peeking in
55 // between the posting of each kMsgHaveWork message (i.e., after kMsgHaveWork
56 // is peeked, and before a replacement kMsgHaveWork is posted).
57 //
58 // NOTE: Although it may seem odd that messages are used to start and stop this
59 // flow (as opposed to signaling objects, etc.), it should be understood that
60 // the native message pump will *only* respond to messages. As a result, it is
61 // an excellent choice. It is also helpful that the starter messages that are
62 // placed in the queue when new task arrive also awakens DoRunLoop.
63 //
64 class MessagePumpWin : public MessagePump { 23 class MessagePumpWin : public MessagePump {
65 public: 24 public:
66 // An Observer is an object that receives global notifications from the 25 // An Observer is an object that receives global notifications from the
67 // MessageLoop. 26 // MessageLoop.
68 // 27 //
69 // NOTE: An Observer implementation should be extremely fast! 28 // NOTE: An Observer implementation should be extremely fast!
70 // 29 //
71 class Observer { 30 class Observer {
72 public: 31 public:
73 virtual ~Observer() {} 32 virtual ~Observer() {}
(...skipping 16 matching lines...) Expand all
90 // The nested loop is exited by either posting a quit, or returning false 49 // The nested loop is exited by either posting a quit, or returning false
91 // from Dispatch. 50 // from Dispatch.
92 class Dispatcher { 51 class Dispatcher {
93 public: 52 public:
94 virtual ~Dispatcher() {} 53 virtual ~Dispatcher() {}
95 // Dispatches the event. If true is returned processing continues as 54 // Dispatches the event. If true is returned processing continues as
96 // normal. If false is returned, the nested loop exits immediately. 55 // normal. If false is returned, the nested loop exits immediately.
97 virtual bool Dispatch(const MSG& msg) = 0; 56 virtual bool Dispatch(const MSG& msg) = 0;
98 }; 57 };
99 58
100 MessagePumpWin(); 59 MessagePumpWin() : have_work_(0), state_(NULL) {}
101 virtual ~MessagePumpWin(); 60 virtual ~MessagePumpWin() {}
102 61
103 // Add an Observer, which will start receiving notifications immediately. 62 // Add an Observer, which will start receiving notifications immediately.
104 void AddObserver(Observer* observer); 63 void AddObserver(Observer* observer);
105 64
106 // Remove an Observer. It is safe to call this method while an Observer is 65 // Remove an Observer. It is safe to call this method while an Observer is
107 // receiving a notification callback. 66 // receiving a notification callback.
108 void RemoveObserver(Observer* observer); 67 void RemoveObserver(Observer* observer);
109 68
110 // Give a chance to code processing additional messages to notify the 69 // Give a chance to code processing additional messages to notify the
111 // message loop observers that another message has been processed. 70 // message loop observers that another message has been processed.
112 void WillProcessMessage(const MSG& msg); 71 void WillProcessMessage(const MSG& msg);
113 void DidProcessMessage(const MSG& msg); 72 void DidProcessMessage(const MSG& msg);
114 73
115 // Applications can call this to encourage us to process all pending WM_PAINT
116 // messages. This method will process all paint messages the Windows Message
117 // queue can provide, up to some fixed number (to avoid any infinite loops).
118 void PumpOutPendingPaintMessages();
119
120 // Like MessagePump::Run, but MSG objects are routed through dispatcher. 74 // Like MessagePump::Run, but MSG objects are routed through dispatcher.
121 void RunWithDispatcher(Delegate* delegate, Dispatcher* dispatcher); 75 void RunWithDispatcher(Delegate* delegate, Dispatcher* dispatcher);
122 76
123 // MessagePump methods: 77 // MessagePump methods:
124 virtual void Run(Delegate* delegate) { RunWithDispatcher(delegate, NULL); } 78 virtual void Run(Delegate* delegate) { RunWithDispatcher(delegate, NULL); }
125 virtual void Quit(); 79 virtual void Quit();
126 virtual void ScheduleWork();
127 virtual void ScheduleDelayedWork(const Time& delayed_work_time);
128 80
129 protected: 81 protected:
130 struct RunState { 82 struct RunState {
131 Delegate* delegate; 83 Delegate* delegate;
132 Dispatcher* dispatcher; 84 Dispatcher* dispatcher;
133 85
134 // Used to flag that the current Run() invocation should return ASAP. 86 // Used to flag that the current Run() invocation should return ASAP.
135 bool should_quit; 87 bool should_quit;
136 88
137 // Used to count how many Run() invocations are on the stack. 89 // Used to count how many Run() invocations are on the stack.
138 int run_depth; 90 int run_depth;
139 }; 91 };
140 92
141 static LRESULT CALLBACK WndProcThunk(
142 HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam);
143 virtual void DoRunLoop() = 0; 93 virtual void DoRunLoop() = 0;
144 void InitMessageWnd();
145 void HandleWorkMessage();
146 void HandleTimerMessage();
147 bool ProcessNextWindowsMessage();
148 bool ProcessMessageHelper(const MSG& msg);
149 bool ProcessPumpReplacementMessage();
150 int GetCurrentDelay() const; 94 int GetCurrentDelay() const;
151 95
152 // A hidden message-only window.
153 HWND message_hwnd_;
154
155 ObserverList<Observer> observers_; 96 ObserverList<Observer> observers_;
156 97
157 // The time at which delayed work should run. 98 // The time at which delayed work should run.
158 Time delayed_work_time_; 99 Time delayed_work_time_;
159 100
160 // A boolean value used to indicate if there is a kMsgDoWork message pending 101 // A boolean value used to indicate if there is a kMsgDoWork message pending
161 // in the Windows Message queue. There is at most one such message, and it 102 // in the Windows Message queue. There is at most one such message, and it
162 // can drive execution of tasks when a native message pump is running. 103 // can drive execution of tasks when a native message pump is running.
163 LONG have_work_; 104 LONG have_work_;
164 105
165 // State for the current invocation of Run. 106 // State for the current invocation of Run.
166 RunState* state_; 107 RunState* state_;
167 }; 108 };
168 109
169 //----------------------------------------------------------------------------- 110 //-----------------------------------------------------------------------------
170 // MessagePumpForUI extends MessagePumpWin with methods that are particular to a 111 // MessagePumpForUI extends MessagePumpWin with methods that are particular to a
171 // MessageLoop instantiated with TYPE_UI. 112 // MessageLoop instantiated with TYPE_UI.
172 // 113 //
114 // MessagePumpForUI implements a "traditional" Windows message pump. It contains
115 // a nearly infinite loop that peeks out messages, and then dispatches them.
116 // Intermixed with those peeks are callouts to DoWork for pending tasks, and
117 // DoDelayedWork for pending timers. When there are no events to be serviced,
118 // this pump goes into a wait state. In most cases, this message pump handles
119 // all processing.
120 //
121 // However, when a task, or windows event, invokes on the stack a native dialog
122 // box or such, that window typically provides a bare bones (native?) message
123 // pump. That bare-bones message pump generally supports little more than a
124 // peek of the Windows message queue, followed by a dispatch of the peeked
125 // message. MessageLoop extends that bare-bones message pump to also service
126 // Tasks, at the cost of some complexity.
127 //
128 // The basic structure of the extension (refered to as a sub-pump) is that a
129 // special message, kMsgHaveWork, is repeatedly injected into the Windows
130 // Message queue. Each time the kMsgHaveWork message is peeked, checks are
131 // made for an extended set of events, including the availability of Tasks to
132 // run.
133 //
134 // After running a task, the special message kMsgHaveWork is again posted to
135 // the Windows Message queue, ensuring a future time slice for processing a
136 // future event. To prevent flooding the Windows Message queue, care is taken
137 // to be sure that at most one kMsgHaveWork message is EVER pending in the
138 // Window's Message queue.
139 //
140 // There are a few additional complexities in this system where, when there are
141 // no Tasks to run, this otherwise infinite stream of messages which drives the
142 // sub-pump is halted. The pump is automatically re-started when Tasks are
143 // queued.
144 //
145 // A second complexity is that the presence of this stream of posted tasks may
146 // prevent a bare-bones message pump from ever peeking a WM_PAINT or WM_TIMER.
147 // Such paint and timer events always give priority to a posted message, such as
148 // kMsgHaveWork messages. As a result, care is taken to do some peeking in
149 // between the posting of each kMsgHaveWork message (i.e., after kMsgHaveWork
150 // is peeked, and before a replacement kMsgHaveWork is posted).
151 //
152 // NOTE: Although it may seem odd that messages are used to start and stop this
153 // flow (as opposed to signaling objects, etc.), it should be understood that
154 // the native message pump will *only* respond to messages. As a result, it is
155 // an excellent choice. It is also helpful that the starter messages that are
156 // placed in the queue when new task arrive also awakens DoRunLoop.
157 //
173 class MessagePumpForUI : public MessagePumpWin { 158 class MessagePumpForUI : public MessagePumpWin {
174 public: 159 public:
175 MessagePumpForUI() {} 160 MessagePumpForUI();
176 virtual ~MessagePumpForUI() {} 161 virtual ~MessagePumpForUI();
162
163 // MessagePump methods:
164 virtual void ScheduleWork();
165 virtual void ScheduleDelayedWork(const Time& delayed_work_time);
166
167 // Applications can call this to encourage us to process all pending WM_PAINT
168 // messages. This method will process all paint messages the Windows Message
169 // queue can provide, up to some fixed number (to avoid any infinite loops).
170 void PumpOutPendingPaintMessages();
171
177 private: 172 private:
173 static LRESULT CALLBACK WndProcThunk(
174 HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam);
178 virtual void DoRunLoop(); 175 virtual void DoRunLoop();
176 void InitMessageWnd();
179 void WaitForWork(); 177 void WaitForWork();
178 void HandleWorkMessage();
179 void HandleTimerMessage();
180 bool ProcessNextWindowsMessage();
181 bool ProcessMessageHelper(const MSG& msg);
182 bool ProcessPumpReplacementMessage();
183
184 // A hidden message-only window.
185 HWND message_hwnd_;
180 }; 186 };
181 187
182 //----------------------------------------------------------------------------- 188 //-----------------------------------------------------------------------------
183 // MessagePumpForIO extends MessagePumpWin with methods that are particular to a 189 // MessagePumpForIO extends MessagePumpWin with methods that are particular to a
184 // MessageLoop instantiated with TYPE_IO. 190 // MessageLoop instantiated with TYPE_IO. This version of MessagePump does not
191 // deal with Windows mesagges, and instead has a Run loop based on Completion
192 // Ports so it is better suited for IO operations.
185 // 193 //
186 class MessagePumpForIO : public MessagePumpWin { 194 class MessagePumpForIO : public MessagePumpWin {
187 public: 195 public:
188 // Used with WatchObject to asynchronously monitor the signaled state of a 196 struct IOContext;
189 // HANDLE object.
190 class Watcher {
191 public:
192 virtual ~Watcher() {}
193 // Called from MessageLoop::Run when a signalled object is detected.
194 virtual void OnObjectSignaled(HANDLE object) = 0;
195 };
196 197
197 // Clients interested in receiving OS notifications when asynchronous IO 198 // Clients interested in receiving OS notifications when asynchronous IO
198 // operations complete should implement this interface and register themselves 199 // operations complete should implement this interface and register themselves
199 // with the message pump. 200 // with the message pump.
201 //
202 // Typical use #1:
203 // // Use only when there are no user's buffers involved on the actual IO,
204 // // so that all the cleanup can be done by the message pump.
205 // class MyFile : public IOHandler {
206 // MyFile() {
207 // ...
208 // context_ = new IOContext;
209 // context_->handler = this;
210 // message_pump->RegisterIOHandler(file_, this);
211 // }
212 // ~MyFile() {
213 // if (pending_) {
214 // // By setting the handler to NULL, we're asking for this context
215 // // to be deleted when received, without calling back to us.
216 // context_->handler = NULL;
217 // } else {
218 // delete context_;
219 // }
220 // }
221 // virtual void OnIOCompleted(IOContext* context, DWORD bytes_transfered,
222 // DWORD error) {
223 // pending_ = false;
224 // }
225 // void DoSomeIo() {
226 // ...
227 // // The only buffer required for this operation is the overlapped
228 // // structure.
229 // ConnectNamedPipe(file_, &context_->overlapped);
230 // pending_ = true;
231 // }
232 // bool pending_;
233 // IOContext* context_;
234 // HANDLE file_;
235 // };
236 //
237 // Typical use #2:
238 // class MyFile : public IOHandler {
239 // MyFile() {
240 // ...
241 // message_pump->RegisterIOHandler(file_, this);
242 // }
243 // // Plus some code to make sure that this destructor is not called
244 // // while there are pending IO operations.
245 // ~MyFile() {
246 // }
247 // virtual void OnIOCompleted(IOContext* context, DWORD bytes_transfered,
248 // DWORD error) {
249 // ...
250 // delete context;
251 // }
252 // void DoSomeIo() {
253 // ...
254 // IOContext* context = new IOContext;
255 // // This is not used for anything. It just prevents the context from
256 // // being considered "abandoned".
257 // context->handler = this;
258 // ReadFile(file_, buffer, num_bytes, &read, &context->overlapped);
259 // }
260 // HANDLE file_;
261 // };
262 //
263 // Typical use #3:
264 // Same as the previous example, except that in order to deal with the
265 // requirement stated for the destructor, the class calls WaitForIOCompletion
266 // from the destructor to block until all IO finishes.
267 // ~MyFile() {
268 // while(pending_)
269 // message_pump->WaitForIOCompletion(INFINITE, this);
270 // }
271 //
200 class IOHandler { 272 class IOHandler {
201 public: 273 public:
202 virtual ~IOHandler() {} 274 virtual ~IOHandler() {}
203 // This will be called once the pending IO operation associated with 275 // This will be called once the pending IO operation associated with
204 // |context| completes. |error| is the Win32 error code of the IO operation 276 // |context| completes. |error| is the Win32 error code of the IO operation
205 // (ERROR_SUCCESS if there was no error). |bytes_transfered| will be zero 277 // (ERROR_SUCCESS if there was no error). |bytes_transfered| will be zero
206 // on error. 278 // on error.
207 virtual void OnIOCompleted(OVERLAPPED* context, DWORD bytes_transfered, 279 virtual void OnIOCompleted(IOContext* context, DWORD bytes_transfered,
208 DWORD error) = 0; 280 DWORD error) = 0;
209 }; 281 };
210 282
211 MessagePumpForIO() {} 283 // The extended context that should be used as the base structure on every
284 // overlapped IO operation. |handler| must be set to the registered IOHandler
285 // for the given file when the operation is started, and it can be set to NULL
286 // before the operation completes to indicate that the handler should not be
287 // called anymore, and instead, the IOContext should be deleted when the OS
288 // notifies the completion of this operation. Please remember that any buffers
289 // involved with an IO operation should be around until the callback is
290 // received, so this technique can only be used for IO that do not involve
291 // additional buffers (other than the overlapped structure itself).
292 struct IOContext {
293 OVERLAPPED overlapped;
294 IOHandler* handler;
295 };
296
297 MessagePumpForIO();
212 virtual ~MessagePumpForIO() {} 298 virtual ~MessagePumpForIO() {}
213 299
214 // Have the current thread's message loop watch for a signaled object. 300 // MessagePump methods:
215 // Pass a null watcher to stop watching the object. 301 virtual void ScheduleWork();
216 void WatchObject(HANDLE, Watcher*); 302 virtual void ScheduleDelayedWork(const Time& delayed_work_time);
217 303
218 // Register the handler to be used when asynchronous IO for the given file 304 // Register the handler to be used when asynchronous IO for the given file
219 // completes. The registration persists as long as |file_handle| is valid, so 305 // completes. The registration persists as long as |file_handle| is valid, so
220 // |handler| must be valid as long as there is pending IO for the given file. 306 // |handler| must be valid as long as there is pending IO for the given file.
221 void RegisterIOHandler(HANDLE file_handle, IOHandler* handler); 307 void RegisterIOHandler(HANDLE file_handle, IOHandler* handler);
222 308
223 // This is just a throw away function to ease transition to completion ports. 309 // Waits for the next IO completion that should be processed by |filter|, for
224 // Pass NULL for handler to stop tracking this request. WARNING: cancellation 310 // up to |timeout| milliseconds. Return true if any IO operation completed,
225 // correctness is the responsibility of the caller. |context| must contain a 311 // regardless of the involved handler, and false if the timeout expired. If
226 // valid manual reset event, but the caller should not interact directly with 312 // the completion port received any message and the involved IO handler
227 // it. The registration can live across a single IO operation, or it can live 313 // matches |filter|, the callback is called before returning from this code;
228 // across multiple IO operations without having to reset it after each IO 314 // if the handler is not the one that we are looking for, the callback will
229 // completion callback. Internally, there will be a WatchObject registration 315 // be postponed for another time, so reentrancy problems can be avoided.
230 // alive as long as this context registration is in effect. It is an error 316 // External use of this method should be reserved for the rare case when the
231 // to unregister a context that has not been registered before. 317 // caller is willing to allow pausing regular task dispatching on this thread.
232 void RegisterIOContext(OVERLAPPED* context, IOHandler* handler); 318 bool WaitForIOCompletion(DWORD timeout, IOHandler* filter);
233 319
234 private: 320 private:
321 struct IOItem {
322 IOHandler* handler;
323 IOContext* context;
324 DWORD bytes_transfered;
325 DWORD error;
326 };
327
235 virtual void DoRunLoop(); 328 virtual void DoRunLoop();
236 void WaitForWork(); 329 void WaitForWork();
237 bool ProcessNextObject(); 330 bool MatchCompletedIOItem(IOHandler* filter, IOItem* item);
238 bool SignalWatcher(size_t object_index); 331 bool GetIOItem(DWORD timeout, IOItem* item);
239 332 bool ProcessInternalIOItem(const IOItem& item);
240 // A vector of objects (and corresponding watchers) that are routinely
241 // serviced by this message pump.
242 std::vector<HANDLE> objects_;
243 std::vector<Watcher*> watchers_;
244 333
245 // The completion port associated with this thread. 334 // The completion port associated with this thread.
246 ScopedHandle port_; 335 ScopedHandle port_;
336 // This list will be empty almost always. It stores IO completions that have
337 // not been delivered yet because somebody was doing cleanup.
338 std::list<IOItem> completed_io_;
247 }; 339 };
248 340
249 } // namespace base 341 } // namespace base
250 342
251 #endif // BASE_MESSAGE_PUMP_WIN_H_ 343 #endif // BASE_MESSAGE_PUMP_WIN_H_
OLDNEW
« no previous file with comments | « base/message_loop_unittest.cc ('k') | base/message_pump_win.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698