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
3 // found in the LICENSE file.
5 #ifndef BASE_MESSAGE_LOOP_H_
6 #define BASE_MESSAGE_LOOP_H_
12 #include "base/basictypes.h"
13 #include "base/lock.h"
14 #include "base/message_pump.h"
15 #include "base/observer_list.h"
16 #include "base/ref_counted.h"
17 #include "base/task.h"
20 // We need this to declare base::MessagePumpWin::Dispatcher, which we should
21 // really just eliminate.
22 #include "base/message_pump_win.h"
23 #elif defined(OS_POSIX)
24 #include "base/message_pump_libevent.h"
25 #if !defined(OS_MACOSX)
26 #include "base/message_pump_glib.h"
32 // A MessageLoop is used to process events for a particular thread. There is
33 // at most one MessageLoop instance per thread.
35 // Events include at a minimum Task instances submitted to PostTask or those
36 // managed by TimerManager. Depending on the type of message pump used by the
37 // MessageLoop other events such as UI messages may be processed. On Windows
38 // APC calls (as time permits) and signals sent to a registered set of HANDLEs
39 // may also be processed.
41 // NOTE: Unless otherwise specified, a MessageLoop's methods may only be called
42 // on the thread where the MessageLoop's Run method executes.
44 // NOTE: MessageLoop has task reentrancy protection. This means that if a
45 // task is being processed, a second task cannot start until the first task is
46 // finished. Reentrancy can happen when processing a task, and an inner
47 // message pump is created. That inner pump then processes native messages
48 // which could implicitly start an inner task. Inner message pumps are created
49 // with dialogs (DialogBox), common dialogs (GetOpenFileName), OLE functions
50 // (DoDragDrop), printer functions (StartDoc) and *many* others.
52 // Sample workaround when inner task processing is needed:
53 // bool old_state = MessageLoop::current()->NestableTasksAllowed();
54 // MessageLoop::current()->SetNestableTasksAllowed(true);
55 // HRESULT hr = DoDragDrop(...); // Implicitly runs a modal message loop here.
56 // MessageLoop::current()->SetNestableTasksAllowed(old_state);
57 // // Process hr (the result returned by DoDragDrop().
59 // Please be SURE your task is reentrant (nestable) and all global variables
60 // are stable and accessible before calling SetNestableTasksAllowed(true).
62 class MessageLoop
: public base::MessagePump::Delegate
{
64 // A TaskObserver is an object that receives task notifications from the
67 // NOTE: A TaskObserver implementation should be extremely fast!
72 // This method is called before processing a task.
73 virtual void WillProcessTask(base::TimeTicks birth_time
) = 0;
75 // This method is called after processing a task.
76 virtual void DidProcessTask() = 0;
79 virtual ~TaskObserver();
82 static void EnableHistogrammer(bool enable_histogrammer
);
84 // A DestructionObserver is notified when the current MessageLoop is being
85 // destroyed. These obsevers are notified prior to MessageLoop::current()
86 // being changed to return NULL. This gives interested parties the chance to
87 // do final cleanup that depends on the MessageLoop.
89 // NOTE: Any tasks posted to the MessageLoop during this notification will
90 // not be run. Instead, they will be deleted.
92 class DestructionObserver
{
94 virtual ~DestructionObserver();
95 virtual void WillDestroyCurrentMessageLoop() = 0;
98 // Add a DestructionObserver, which will start receiving notifications
100 void AddDestructionObserver(DestructionObserver
* destruction_observer
);
102 // Remove a DestructionObserver. It is safe to call this method while a
103 // DestructionObserver is receiving a notification callback.
104 void RemoveDestructionObserver(DestructionObserver
* destruction_observer
);
106 // The "PostTask" family of methods call the task's Run method asynchronously
107 // from within a message loop at some point in the future.
109 // With the PostTask variant, tasks are invoked in FIFO order, inter-mixed
110 // with normal UI or IO event processing. With the PostDelayedTask variant,
111 // tasks are called after at least approximately 'delay_ms' have elapsed.
113 // The NonNestable variants work similarly except that they promise never to
114 // dispatch the task from a nested invocation of MessageLoop::Run. Instead,
115 // such tasks get deferred until the top-most MessageLoop::Run is executing.
117 // The MessageLoop takes ownership of the Task, and deletes it after it has
120 // NOTE: These methods may be called on any thread. The Task will be invoked
121 // on the thread that executes MessageLoop::Run().
124 const tracked_objects::Location
& from_here
, Task
* task
);
126 void PostDelayedTask(
127 const tracked_objects::Location
& from_here
, Task
* task
, int64 delay_ms
);
129 void PostNonNestableTask(
130 const tracked_objects::Location
& from_here
, Task
* task
);
132 void PostNonNestableDelayedTask(
133 const tracked_objects::Location
& from_here
, Task
* task
, int64 delay_ms
);
135 // A variant on PostTask that deletes the given object. This is useful
136 // if the object needs to live until the next run of the MessageLoop (for
137 // example, deleting a RenderProcessHost from within an IPC callback is not
140 // NOTE: This method may be called on any thread. The object will be deleted
141 // on the thread that executes MessageLoop::Run(). If this is not the same
142 // as the thread that calls PostDelayedTask(FROM_HERE, ), then T MUST inherit
143 // from RefCountedThreadSafe<T>!
145 void DeleteSoon(const tracked_objects::Location
& from_here
, T
* object
) {
146 PostNonNestableTask(from_here
, new DeleteTask
<T
>(object
));
149 // A variant on PostTask that releases the given reference counted object
150 // (by calling its Release method). This is useful if the object needs to
151 // live until the next run of the MessageLoop, or if the object needs to be
152 // released on a particular thread.
154 // NOTE: This method may be called on any thread. The object will be
155 // released (and thus possibly deleted) on the thread that executes
156 // MessageLoop::Run(). If this is not the same as the thread that calls
157 // PostDelayedTask(FROM_HERE, ), then T MUST inherit from
158 // RefCountedThreadSafe<T>!
160 void ReleaseSoon(const tracked_objects::Location
& from_here
, T
* object
) {
161 PostNonNestableTask(from_here
, new ReleaseTask
<T
>(object
));
164 // Run the message loop.
167 // Process all pending tasks, windows messages, etc., but don't wait/sleep.
168 // Return as soon as all items that can be run are taken care of.
169 void RunAllPending();
171 // Signals the Run method to return after it is done processing all pending
172 // messages. This method may only be called on the same thread that called
173 // Run, and Run must still be on the call stack.
175 // Use QuitTask if you need to Quit another thread's MessageLoop, but note
176 // that doing so is fairly dangerous if the target thread makes nested calls
177 // to MessageLoop::Run. The problem being that you won't know which nested
178 // run loop you are quiting, so be careful!
182 // This method is a variant of Quit, that does not wait for pending messages
183 // to be processed before returning from Run.
186 // Invokes Quit on the current MessageLoop when run. Useful to schedule an
187 // arbitrary MessageLoop to Quit.
188 class QuitTask
: public Task
{
191 MessageLoop::current()->Quit();
195 // A MessageLoop has a particular type, which indicates the set of
196 // asynchronous events it may process in addition to tasks and timers.
199 // This type of ML only supports tasks and timers.
202 // This type of ML also supports native UI events (e.g., Windows messages).
203 // See also MessageLoopForUI.
206 // This type of ML also supports asynchronous IO. See also
215 // Normally, it is not necessary to instantiate a MessageLoop. Instead, it
216 // is typical to make use of the current thread's MessageLoop instance.
217 explicit MessageLoop(Type type
= TYPE_DEFAULT
);
220 // Returns the type passed to the constructor.
221 Type
type() const { return type_
; }
223 // Optional call to connect the thread name with this loop.
224 void set_thread_name(const std::string
& thread_name
) {
225 DCHECK(thread_name_
.empty()) << "Should not rename this thread!";
226 thread_name_
= thread_name
;
228 const std::string
& thread_name() const { return thread_name_
; }
230 // Returns the MessageLoop object for the current thread, or null if none.
231 static MessageLoop
* current();
233 // Enables or disables the recursive task processing. This happens in the case
234 // of recursive message loops. Some unwanted message loop may occurs when
235 // using common controls or printer functions. By default, recursive task
236 // processing is disabled.
238 // The specific case where tasks get queued is:
239 // - The thread is running a message loop.
240 // - It receives a task #1 and execute it.
241 // - The task #1 implicitly start a message loop, like a MessageBox in the
242 // unit test. This can also be StartDoc or GetSaveFileName.
243 // - The thread receives a task #2 before or while in this second message
245 // - With NestableTasksAllowed set to true, the task #2 will run right away.
246 // Otherwise, it will get executed right after task #1 completes at "thread
247 // message loop level".
248 void SetNestableTasksAllowed(bool allowed
);
249 bool NestableTasksAllowed() const;
251 // Enables nestable tasks on |loop| while in scope.
252 class ScopedNestableTaskAllower
{
254 explicit ScopedNestableTaskAllower(MessageLoop
* loop
)
256 old_state_(loop_
->NestableTasksAllowed()) {
257 loop_
->SetNestableTasksAllowed(true);
259 ~ScopedNestableTaskAllower() {
260 loop_
->SetNestableTasksAllowed(old_state_
);
268 // Enables or disables the restoration during an exception of the unhandled
269 // exception filter that was active when Run() was called. This can happen
270 // if some third party code call SetUnhandledExceptionFilter() and never
271 // restores the previous filter.
272 void set_exception_restoration(bool restore
) {
273 exception_restoration_
= restore
;
276 // Returns true if we are currently running a nested message loop.
279 // These functions can only be called on the same thread that |this| is
281 void AddTaskObserver(TaskObserver
* task_observer
);
282 void RemoveTaskObserver(TaskObserver
* task_observer
);
285 typedef base::MessagePumpWin::Dispatcher Dispatcher
;
286 typedef base::MessagePumpForUI::Observer Observer
;
287 #elif !defined(OS_MACOSX)
288 typedef base::MessagePumpForUI::Dispatcher Dispatcher
;
289 typedef base::MessagePumpForUI::Observer Observer
;
292 // Returns true if the message loop has high resolution timers enabled.
293 // Provided for testing.
294 bool high_resolution_timers_enabled() {
296 return !high_resolution_timer_expiration_
.is_null();
302 // When we go into high resolution timer mode, we will stay in hi-res mode
304 static const int kHighResolutionTimerModeLeaseTimeMs
= 1000;
306 //----------------------------------------------------------------------------
309 // Used to count how many Run() invocations are on the stack.
312 // Used to record that Quit() was called, or that we should quit the pump
313 // once it becomes idle.
316 #if !defined(OS_MACOSX)
317 Dispatcher
* dispatcher
;
321 class AutoRunState
: RunState
{
323 explicit AutoRunState(MessageLoop
* loop
);
327 RunState
* previous_state_
;
330 // This structure is copied around by value.
332 Task
* task
; // The task to run.
333 base::Time delayed_run_time
; // The time when the task should be run.
334 int sequence_num
; // Used to facilitate sorting by run time.
335 bool nestable
; // True if OK to dispatch from a nested loop.
337 PendingTask(Task
* task
, bool nestable
)
338 : task(task
), sequence_num(0), nestable(nestable
) {
341 // Used to support sorting.
342 bool operator<(const PendingTask
& other
) const;
345 class TaskQueue
: public std::queue
<PendingTask
> {
347 void Swap(TaskQueue
* queue
) {
348 c
.swap(queue
->c
); // Calls std::deque::swap
352 typedef std::priority_queue
<PendingTask
> DelayedTaskQueue
;
355 base::MessagePumpWin
* pump_win() {
356 return static_cast<base::MessagePumpWin
*>(pump_
.get());
358 #elif defined(OS_POSIX)
359 base::MessagePumpLibevent
* pump_libevent() {
360 return static_cast<base::MessagePumpLibevent
*>(pump_
.get());
364 // A function to encapsulate all the exception handling capability in the
365 // stacks around the running of a main message loop. It will run the message
366 // loop in a SEH try block or not depending on the set_SEH_restoration()
367 // flag invoking respectively RunInternalInSEHFrame() or RunInternal().
371 __declspec(noinline
) void RunInternalInSEHFrame();
374 // A surrounding stack frame around the running of the message loop that
375 // supports all saving and restoring of state, as is needed for any/all (ugly)
379 // Called to process any delayed non-nestable tasks.
380 bool ProcessNextDelayedNonNestableTask();
382 //----------------------------------------------------------------------------
383 // Run a work_queue_ task or new_task, and delete it (if it was processed by
384 // PostTask). If there are queued tasks, the oldest one is executed and
385 // new_task is queued. new_task is optional and can be NULL. In this NULL
386 // case, the method will run one pending task (if any exist). Returns true if
387 // it executes a task. Queued tasks accumulate only when there is a
388 // non-nestable task currently processing, in which case the new_task is
389 // appended to the list work_queue_. Such re-entrancy generally happens when
390 // an unrequested message pump (typical of a native dialog) is executing in
391 // the context of a task.
392 bool QueueOrRunTask(Task
* new_task
);
394 // Runs the specified task and deletes it.
395 void RunTask(Task
* task
);
397 // Calls RunTask or queues the pending_task on the deferred task list if it
398 // cannot be run right now. Returns true if the task was run.
399 bool DeferOrRunPendingTask(const PendingTask
& pending_task
);
401 // Adds the pending task to delayed_work_queue_.
402 void AddToDelayedWorkQueue(const PendingTask
& pending_task
);
404 // Load tasks from the incoming_queue_ into work_queue_ if the latter is
405 // empty. The former requires a lock to access, while the latter is directly
406 // accessible on this thread.
407 void ReloadWorkQueue();
409 // Delete tasks that haven't run yet without running them. Used in the
410 // destructor to make sure all the task's destructors get called. Returns
411 // true if some work was done.
412 bool DeletePendingTasks();
414 // Post a task to our incomming queue.
415 void PostTask_Helper(const tracked_objects::Location
& from_here
, Task
* task
,
416 int64 delay_ms
, bool nestable
);
418 // base::MessagePump::Delegate methods:
419 virtual bool DoWork();
420 virtual bool DoDelayedWork(base::Time
* next_delayed_work_time
);
421 virtual bool DoIdleWork();
423 // Start recording histogram info about events and action IF it was enabled
424 // and IF the statistics recorder can accept a registration of our histogram.
425 void StartHistogrammer();
427 // Add occurence of event to our histogram, so that we can see what is being
428 // done in a specific MessageLoop instance (i.e., specific thread).
429 // If message_histogram_ is NULL, this is a no-op.
430 void HistogramEvent(int event
);
434 // A list of tasks that need to be processed by this instance. Note that
435 // this queue is only accessed (push/pop) by our current thread.
436 TaskQueue work_queue_
;
438 // Contains delayed tasks, sorted by their 'delayed_run_time' property.
439 DelayedTaskQueue delayed_work_queue_
;
441 // A queue of non-nestable tasks that we had to defer because when it came
442 // time to execute them we were in a nested message loop. They will execute
443 // once we're out of nested message loops.
444 TaskQueue deferred_non_nestable_work_queue_
;
446 scoped_refptr
<base::MessagePump
> pump_
;
448 ObserverList
<DestructionObserver
> destruction_observers_
;
450 // A recursion block that prevents accidentally running additonal tasks when
451 // insider a (accidentally induced?) nested message pump.
452 bool nestable_tasks_allowed_
;
454 bool exception_restoration_
;
456 std::string thread_name_
;
457 // A profiling histogram showing the counts of various messages and events.
458 scoped_refptr
<Histogram
> message_histogram_
;
460 // A null terminated list which creates an incoming_queue of tasks that are
461 // aquired under a mutex for processing on this instance's thread. These tasks
462 // have not yet been sorted out into items for our work_queue_ vs items that
463 // will be handled by the TimerManager.
464 TaskQueue incoming_queue_
;
465 // Protect access to incoming_queue_.
466 Lock incoming_queue_lock_
;
471 base::TimeTicks high_resolution_timer_expiration_
;
474 // The next sequence number to use for delayed tasks.
475 int next_sequence_num_
;
477 ObserverList
<TaskObserver
> task_observers_
;
479 DISALLOW_COPY_AND_ASSIGN(MessageLoop
);
482 //-----------------------------------------------------------------------------
483 // MessageLoopForUI extends MessageLoop with methods that are particular to a
484 // MessageLoop instantiated with TYPE_UI.
486 // This class is typically used like so:
487 // MessageLoopForUI::current()->...call some method...
489 class MessageLoopForUI
: public MessageLoop
{
491 MessageLoopForUI() : MessageLoop(TYPE_UI
) {
494 // Returns the MessageLoopForUI of the current thread.
495 static MessageLoopForUI
* current() {
496 MessageLoop
* loop
= MessageLoop::current();
497 DCHECK_EQ(MessageLoop::TYPE_UI
, loop
->type());
498 return static_cast<MessageLoopForUI
*>(loop
);
502 void DidProcessMessage(const MSG
& message
);
503 #endif // defined(OS_WIN)
505 #if !defined(OS_MACOSX)
506 // Please see message_pump_win/message_pump_glib for definitions of these
508 void AddObserver(Observer
* observer
);
509 void RemoveObserver(Observer
* observer
);
510 void Run(Dispatcher
* dispatcher
);
513 // TODO(rvargas): Make this platform independent.
514 base::MessagePumpForUI
* pump_ui() {
515 return static_cast<base::MessagePumpForUI
*>(pump_
.get());
517 #endif // !defined(OS_MACOSX)
520 // Do not add any member variables to MessageLoopForUI! This is important b/c
521 // MessageLoopForUI is often allocated via MessageLoop(TYPE_UI). Any extra
522 // data that you need should be stored on the MessageLoop's pump_ instance.
523 COMPILE_ASSERT(sizeof(MessageLoop
) == sizeof(MessageLoopForUI
),
524 MessageLoopForUI_should_not_have_extra_member_variables
);
526 //-----------------------------------------------------------------------------
527 // MessageLoopForIO extends MessageLoop with methods that are particular to a
528 // MessageLoop instantiated with TYPE_IO.
530 // This class is typically used like so:
531 // MessageLoopForIO::current()->...call some method...
533 class MessageLoopForIO
: public MessageLoop
{
536 typedef base::MessagePumpForIO::IOHandler IOHandler
;
537 typedef base::MessagePumpForIO::IOContext IOContext
;
538 typedef base::MessagePumpForIO::IOObserver IOObserver
;
539 #elif defined(OS_POSIX)
540 typedef base::MessagePumpLibevent::Watcher Watcher
;
541 typedef base::MessagePumpLibevent::FileDescriptorWatcher
542 FileDescriptorWatcher
;
543 typedef base::MessagePumpLibevent::IOObserver IOObserver
;
546 WATCH_READ
= base::MessagePumpLibevent::WATCH_READ
,
547 WATCH_WRITE
= base::MessagePumpLibevent::WATCH_WRITE
,
548 WATCH_READ_WRITE
= base::MessagePumpLibevent::WATCH_READ_WRITE
553 MessageLoopForIO() : MessageLoop(TYPE_IO
) {
556 // Returns the MessageLoopForIO of the current thread.
557 static MessageLoopForIO
* current() {
558 MessageLoop
* loop
= MessageLoop::current();
559 DCHECK_EQ(MessageLoop::TYPE_IO
, loop
->type());
560 return static_cast<MessageLoopForIO
*>(loop
);
563 void AddIOObserver(IOObserver
* io_observer
) {
564 pump_io()->AddIOObserver(io_observer
);
567 void RemoveIOObserver(IOObserver
* io_observer
) {
568 pump_io()->RemoveIOObserver(io_observer
);
572 // Please see MessagePumpWin for definitions of these methods.
573 void RegisterIOHandler(HANDLE file_handle
, IOHandler
* handler
);
574 bool WaitForIOCompletion(DWORD timeout
, IOHandler
* filter
);
577 // TODO(rvargas): Make this platform independent.
578 base::MessagePumpForIO
* pump_io() {
579 return static_cast<base::MessagePumpForIO
*>(pump_
.get());
582 #elif defined(OS_POSIX)
583 // Please see MessagePumpLibevent for definition.
584 bool WatchFileDescriptor(int fd
,
587 FileDescriptorWatcher
*controller
,
591 base::MessagePumpLibevent
* pump_io() {
592 return static_cast<base::MessagePumpLibevent
*>(pump_
.get());
594 #endif // defined(OS_POSIX)
597 // Do not add any member variables to MessageLoopForIO! This is important b/c
598 // MessageLoopForIO is often allocated via MessageLoop(TYPE_IO). Any extra
599 // data that you need should be stored on the MessageLoop's pump_ instance.
600 COMPILE_ASSERT(sizeof(MessageLoop
) == sizeof(MessageLoopForIO
),
601 MessageLoopForIO_should_not_have_extra_member_variables
);
603 #endif // BASE_MESSAGE_LOOP_H_