1 // Copyright (c) 2011 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/base_api.h"
13 #include "base/basictypes.h"
14 #include "base/callback.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/message_pump.h"
17 #include "base/observer_list.h"
18 #include "base/synchronization/lock.h"
19 #include "base/task.h"
20 #include "base/time.h"
21 #include "base/tracked.h"
24 // We need this to declare base::MessagePumpWin::Dispatcher, which we should
25 // really just eliminate.
26 #include "base/message_pump_win.h"
27 #elif defined(OS_POSIX)
28 #include "base/message_pump_libevent.h"
29 #if !defined(OS_MACOSX)
31 #include "base/message_pump_x.h"
33 #include "base/message_pump_gtk.h"
42 #if defined(TRACK_ALL_TASK_OBJECTS)
43 namespace tracked_objects
{
46 #endif // defined(TRACK_ALL_TASK_OBJECTS)
48 // A MessageLoop is used to process events for a particular thread. There is
49 // at most one MessageLoop instance per thread.
51 // Events include at a minimum Task instances submitted to PostTask or those
52 // managed by TimerManager. Depending on the type of message pump used by the
53 // MessageLoop other events such as UI messages may be processed. On Windows
54 // APC calls (as time permits) and signals sent to a registered set of HANDLEs
55 // may also be processed.
57 // NOTE: Unless otherwise specified, a MessageLoop's methods may only be called
58 // on the thread where the MessageLoop's Run method executes.
60 // NOTE: MessageLoop has task reentrancy protection. This means that if a
61 // task is being processed, a second task cannot start until the first task is
62 // finished. Reentrancy can happen when processing a task, and an inner
63 // message pump is created. That inner pump then processes native messages
64 // which could implicitly start an inner task. Inner message pumps are created
65 // with dialogs (DialogBox), common dialogs (GetOpenFileName), OLE functions
66 // (DoDragDrop), printer functions (StartDoc) and *many* others.
68 // Sample workaround when inner task processing is needed:
69 // bool old_state = MessageLoop::current()->NestableTasksAllowed();
70 // MessageLoop::current()->SetNestableTasksAllowed(true);
71 // HRESULT hr = DoDragDrop(...); // Implicitly runs a modal message loop here.
72 // MessageLoop::current()->SetNestableTasksAllowed(old_state);
73 // // Process hr (the result returned by DoDragDrop().
75 // Please be SURE your task is reentrant (nestable) and all global variables
76 // are stable and accessible before calling SetNestableTasksAllowed(true).
78 class BASE_API MessageLoop
: public base::MessagePump::Delegate
{
81 typedef base::MessagePumpWin::Dispatcher Dispatcher
;
82 typedef base::MessagePumpForUI::Observer Observer
;
83 #elif !defined(OS_MACOSX)
84 typedef base::MessagePumpDispatcher Dispatcher
;
85 typedef base::MessagePumpObserver Observer
;
88 // A MessageLoop has a particular type, which indicates the set of
89 // asynchronous events it may process in addition to tasks and timers.
92 // This type of ML only supports tasks and timers.
95 // This type of ML also supports native UI events (e.g., Windows messages).
96 // See also MessageLoopForUI.
99 // This type of ML also supports asynchronous IO. See also
108 // Normally, it is not necessary to instantiate a MessageLoop. Instead, it
109 // is typical to make use of the current thread's MessageLoop instance.
110 explicit MessageLoop(Type type
= TYPE_DEFAULT
);
111 virtual ~MessageLoop();
113 // Returns the MessageLoop object for the current thread, or null if none.
114 static MessageLoop
* current();
116 static void EnableHistogrammer(bool enable_histogrammer
);
118 // A DestructionObserver is notified when the current MessageLoop is being
119 // destroyed. These obsevers are notified prior to MessageLoop::current()
120 // being changed to return NULL. This gives interested parties the chance to
121 // do final cleanup that depends on the MessageLoop.
123 // NOTE: Any tasks posted to the MessageLoop during this notification will
124 // not be run. Instead, they will be deleted.
126 class BASE_API DestructionObserver
{
128 virtual void WillDestroyCurrentMessageLoop() = 0;
131 virtual ~DestructionObserver();
134 // Add a DestructionObserver, which will start receiving notifications
136 void AddDestructionObserver(DestructionObserver
* destruction_observer
);
138 // Remove a DestructionObserver. It is safe to call this method while a
139 // DestructionObserver is receiving a notification callback.
140 void RemoveDestructionObserver(DestructionObserver
* destruction_observer
);
142 // The "PostTask" family of methods call the task's Run method asynchronously
143 // from within a message loop at some point in the future.
145 // With the PostTask variant, tasks are invoked in FIFO order, inter-mixed
146 // with normal UI or IO event processing. With the PostDelayedTask variant,
147 // tasks are called after at least approximately 'delay_ms' have elapsed.
149 // The NonNestable variants work similarly except that they promise never to
150 // dispatch the task from a nested invocation of MessageLoop::Run. Instead,
151 // such tasks get deferred until the top-most MessageLoop::Run is executing.
153 // The MessageLoop takes ownership of the Task, and deletes it after it has
156 // NOTE: These methods may be called on any thread. The Task will be invoked
157 // on the thread that executes MessageLoop::Run().
160 const tracked_objects::Location
& from_here
, Task
* task
);
162 void PostDelayedTask(
163 const tracked_objects::Location
& from_here
, Task
* task
, int64 delay_ms
);
165 void PostNonNestableTask(
166 const tracked_objects::Location
& from_here
, Task
* task
);
168 void PostNonNestableDelayedTask(
169 const tracked_objects::Location
& from_here
, Task
* task
, int64 delay_ms
);
171 // TODO(ajwong): Remove the functions above once the Task -> Closure migration
174 // There are 2 sets of Post*Task functions, one which takes the older Task*
175 // function object representation, and one that takes the newer base::Closure.
176 // We have this overload to allow a staged transition between the two systems.
177 // Once the transition is done, the functions above should be deleted.
179 const tracked_objects::Location
& from_here
,
180 const base::Closure
& task
);
182 void PostDelayedTask(
183 const tracked_objects::Location
& from_here
,
184 const base::Closure
& task
, int64 delay_ms
);
186 void PostNonNestableTask(
187 const tracked_objects::Location
& from_here
,
188 const base::Closure
& task
);
190 void PostNonNestableDelayedTask(
191 const tracked_objects::Location
& from_here
,
192 const base::Closure
& task
, int64 delay_ms
);
194 // A variant on PostTask that deletes the given object. This is useful
195 // if the object needs to live until the next run of the MessageLoop (for
196 // example, deleting a RenderProcessHost from within an IPC callback is not
199 // NOTE: This method may be called on any thread. The object will be deleted
200 // on the thread that executes MessageLoop::Run(). If this is not the same
201 // as the thread that calls PostDelayedTask(FROM_HERE, ), then T MUST inherit
202 // from RefCountedThreadSafe<T>!
204 void DeleteSoon(const tracked_objects::Location
& from_here
, const T
* object
) {
205 PostNonNestableTask(from_here
, new DeleteTask
<T
>(object
));
208 // A variant on PostTask that releases the given reference counted object
209 // (by calling its Release method). This is useful if the object needs to
210 // live until the next run of the MessageLoop, or if the object needs to be
211 // released on a particular thread.
213 // NOTE: This method may be called on any thread. The object will be
214 // released (and thus possibly deleted) on the thread that executes
215 // MessageLoop::Run(). If this is not the same as the thread that calls
216 // PostDelayedTask(FROM_HERE, ), then T MUST inherit from
217 // RefCountedThreadSafe<T>!
219 void ReleaseSoon(const tracked_objects::Location
& from_here
,
221 PostNonNestableTask(from_here
, new ReleaseTask
<T
>(object
));
224 // Run the message loop.
227 // Process all pending tasks, windows messages, etc., but don't wait/sleep.
228 // Return as soon as all items that can be run are taken care of.
229 void RunAllPending();
231 // Signals the Run method to return after it is done processing all pending
232 // messages. This method may only be called on the same thread that called
233 // Run, and Run must still be on the call stack.
235 // Use QuitTask if you need to Quit another thread's MessageLoop, but note
236 // that doing so is fairly dangerous if the target thread makes nested calls
237 // to MessageLoop::Run. The problem being that you won't know which nested
238 // run loop you are quiting, so be careful!
242 // This method is a variant of Quit, that does not wait for pending messages
243 // to be processed before returning from Run.
246 // Invokes Quit on the current MessageLoop when run. Useful to schedule an
247 // arbitrary MessageLoop to Quit.
248 class QuitTask
: public Task
{
251 MessageLoop::current()->Quit();
255 // Returns the type passed to the constructor.
256 Type
type() const { return type_
; }
258 // Optional call to connect the thread name with this loop.
259 void set_thread_name(const std::string
& thread_name
) {
260 DCHECK(thread_name_
.empty()) << "Should not rename this thread!";
261 thread_name_
= thread_name
;
263 const std::string
& thread_name() const { return thread_name_
; }
265 // Enables or disables the recursive task processing. This happens in the case
266 // of recursive message loops. Some unwanted message loop may occurs when
267 // using common controls or printer functions. By default, recursive task
268 // processing is disabled.
270 // The specific case where tasks get queued is:
271 // - The thread is running a message loop.
272 // - It receives a task #1 and execute it.
273 // - The task #1 implicitly start a message loop, like a MessageBox in the
274 // unit test. This can also be StartDoc or GetSaveFileName.
275 // - The thread receives a task #2 before or while in this second message
277 // - With NestableTasksAllowed set to true, the task #2 will run right away.
278 // Otherwise, it will get executed right after task #1 completes at "thread
279 // message loop level".
280 void SetNestableTasksAllowed(bool allowed
);
281 bool NestableTasksAllowed() const;
283 // Enables nestable tasks on |loop| while in scope.
284 class ScopedNestableTaskAllower
{
286 explicit ScopedNestableTaskAllower(MessageLoop
* loop
)
288 old_state_(loop_
->NestableTasksAllowed()) {
289 loop_
->SetNestableTasksAllowed(true);
291 ~ScopedNestableTaskAllower() {
292 loop_
->SetNestableTasksAllowed(old_state_
);
300 // Enables or disables the restoration during an exception of the unhandled
301 // exception filter that was active when Run() was called. This can happen
302 // if some third party code call SetUnhandledExceptionFilter() and never
303 // restores the previous filter.
304 void set_exception_restoration(bool restore
) {
305 exception_restoration_
= restore
;
308 // Returns true if we are currently running a nested message loop.
311 // A TaskObserver is an object that receives task notifications from the
314 // NOTE: A TaskObserver implementation should be extremely fast!
315 class BASE_API TaskObserver
{
319 // This method is called before processing a task.
320 virtual void WillProcessTask(base::TimeTicks time_posted
) = 0;
322 // This method is called after processing a task.
323 virtual void DidProcessTask(base::TimeTicks time_posted
) = 0;
326 virtual ~TaskObserver();
329 // These functions can only be called on the same thread that |this| is
331 void AddTaskObserver(TaskObserver
* task_observer
);
332 void RemoveTaskObserver(TaskObserver
* task_observer
);
334 // Returns true if the message loop has high resolution timers enabled.
335 // Provided for testing.
336 bool high_resolution_timers_enabled() {
338 return !high_resolution_timer_expiration_
.is_null();
344 // When we go into high resolution timer mode, we will stay in hi-res mode
346 static const int kHighResolutionTimerModeLeaseTimeMs
= 1000;
348 // Asserts that the MessageLoop is "idle".
349 void AssertIdle() const;
352 void set_os_modal_loop(bool os_modal_loop
) {
353 os_modal_loop_
= os_modal_loop
;
356 bool os_modal_loop() const {
357 return os_modal_loop_
;
361 //----------------------------------------------------------------------------
364 // Used to count how many Run() invocations are on the stack.
367 // Used to record that Quit() was called, or that we should quit the pump
368 // once it becomes idle.
371 #if !defined(OS_MACOSX)
372 Dispatcher
* dispatcher
;
376 class BASE_API AutoRunState
: RunState
{
378 explicit AutoRunState(MessageLoop
* loop
);
382 RunState
* previous_state_
;
385 // This structure is copied around by value.
387 PendingTask(const base::Closure
& task
,
388 const tracked_objects::Location
& posted_from
,
389 base::TimeTicks delayed_run_time
,
393 // Used to support sorting.
394 bool operator<(const PendingTask
& other
) const;
399 #if defined(TRACK_ALL_TASK_OBJECTS)
400 // Counter for location where the Closure was posted from.
401 tracked_objects::Births
* post_births
;
402 #endif // defined(TRACK_ALL_TASK_OBJECTS)
404 // Time this PendingTask was posted.
405 base::TimeTicks time_posted
;
407 // The time when the task should be run.
408 base::TimeTicks delayed_run_time
;
410 // Secondary sort key for run time.
413 // OK to dispatch from a nested loop.
416 // The site this PendingTask was posted from.
417 const void* birth_program_counter
;
420 class TaskQueue
: public std::queue
<PendingTask
> {
422 void Swap(TaskQueue
* queue
) {
423 c
.swap(queue
->c
); // Calls std::deque::swap
427 typedef std::priority_queue
<PendingTask
> DelayedTaskQueue
;
430 base::MessagePumpWin
* pump_win() {
431 return static_cast<base::MessagePumpWin
*>(pump_
.get());
433 #elif defined(OS_POSIX)
434 base::MessagePumpLibevent
* pump_libevent() {
435 return static_cast<base::MessagePumpLibevent
*>(pump_
.get());
439 // A function to encapsulate all the exception handling capability in the
440 // stacks around the running of a main message loop. It will run the message
441 // loop in a SEH try block or not depending on the set_SEH_restoration()
442 // flag invoking respectively RunInternalInSEHFrame() or RunInternal().
446 __declspec(noinline
) void RunInternalInSEHFrame();
449 // A surrounding stack frame around the running of the message loop that
450 // supports all saving and restoring of state, as is needed for any/all (ugly)
454 // Called to process any delayed non-nestable tasks.
455 bool ProcessNextDelayedNonNestableTask();
457 // Runs the specified PendingTask.
458 void RunTask(const PendingTask
& pending_task
);
460 // Calls RunTask or queues the pending_task on the deferred task list if it
461 // cannot be run right now. Returns true if the task was run.
462 bool DeferOrRunPendingTask(const PendingTask
& pending_task
);
464 // Adds the pending task to delayed_work_queue_.
465 void AddToDelayedWorkQueue(const PendingTask
& pending_task
);
467 // Adds the pending task to our incoming_queue_.
469 // Caller retains ownership of |pending_task|, but this function will
470 // reset the value of pending_task->task. This is needed to ensure
471 // that the posting call stack does not retain pending_task->task
472 // beyond this function call.
473 void AddToIncomingQueue(PendingTask
* pending_task
);
475 // Load tasks from the incoming_queue_ into work_queue_ if the latter is
476 // empty. The former requires a lock to access, while the latter is directly
477 // accessible on this thread.
478 void ReloadWorkQueue();
480 // Delete tasks that haven't run yet without running them. Used in the
481 // destructor to make sure all the task's destructors get called. Returns
482 // true if some work was done.
483 bool DeletePendingTasks();
485 // Calcuates the time at which a PendingTask should run.
486 base::TimeTicks
CalculateDelayedRuntime(int64 delay_ms
);
488 // Start recording histogram info about events and action IF it was enabled
489 // and IF the statistics recorder can accept a registration of our histogram.
490 void StartHistogrammer();
492 // Add occurence of event to our histogram, so that we can see what is being
493 // done in a specific MessageLoop instance (i.e., specific thread).
494 // If message_histogram_ is NULL, this is a no-op.
495 void HistogramEvent(int event
);
497 // base::MessagePump::Delegate methods:
498 virtual bool DoWork();
499 virtual bool DoDelayedWork(base::TimeTicks
* next_delayed_work_time
);
500 virtual bool DoIdleWork();
504 // A list of tasks that need to be processed by this instance. Note that
505 // this queue is only accessed (push/pop) by our current thread.
506 TaskQueue work_queue_
;
508 // Contains delayed tasks, sorted by their 'delayed_run_time' property.
509 DelayedTaskQueue delayed_work_queue_
;
511 // A recent snapshot of Time::Now(), used to check delayed_work_queue_.
512 base::TimeTicks recent_time_
;
514 // A queue of non-nestable tasks that we had to defer because when it came
515 // time to execute them we were in a nested message loop. They will execute
516 // once we're out of nested message loops.
517 TaskQueue deferred_non_nestable_work_queue_
;
519 scoped_refptr
<base::MessagePump
> pump_
;
521 ObserverList
<DestructionObserver
> destruction_observers_
;
523 // A recursion block that prevents accidentally running additonal tasks when
524 // insider a (accidentally induced?) nested message pump.
525 bool nestable_tasks_allowed_
;
527 bool exception_restoration_
;
529 std::string thread_name_
;
530 // A profiling histogram showing the counts of various messages and events.
531 base::Histogram
* message_histogram_
;
533 // A null terminated list which creates an incoming_queue of tasks that are
534 // acquired under a mutex for processing on this instance's thread. These
535 // tasks have not yet been sorted out into items for our work_queue_ vs items
536 // that will be handled by the TimerManager.
537 TaskQueue incoming_queue_
;
538 // Protect access to incoming_queue_.
539 mutable base::Lock incoming_queue_lock_
;
543 // The need for this variable is subtle. Please see implementation comments
544 // around where it is used.
545 bool should_leak_tasks_
;
548 base::TimeTicks high_resolution_timer_expiration_
;
549 // Should be set to true before calling Windows APIs like TrackPopupMenu, etc
550 // which enter a modal message loop.
554 // The next sequence number to use for delayed tasks.
555 int next_sequence_num_
;
557 ObserverList
<TaskObserver
> task_observers_
;
560 DISALLOW_COPY_AND_ASSIGN(MessageLoop
);
563 //-----------------------------------------------------------------------------
564 // MessageLoopForUI extends MessageLoop with methods that are particular to a
565 // MessageLoop instantiated with TYPE_UI.
567 // This class is typically used like so:
568 // MessageLoopForUI::current()->...call some method...
570 class BASE_API MessageLoopForUI
: public MessageLoop
{
572 MessageLoopForUI() : MessageLoop(TYPE_UI
) {
575 // Returns the MessageLoopForUI of the current thread.
576 static MessageLoopForUI
* current() {
577 MessageLoop
* loop
= MessageLoop::current();
578 DCHECK_EQ(MessageLoop::TYPE_UI
, loop
->type());
579 return static_cast<MessageLoopForUI
*>(loop
);
583 void DidProcessMessage(const MSG
& message
);
584 #endif // defined(OS_WIN)
586 #if !defined(OS_MACOSX)
587 // Please see message_pump_win/message_pump_glib for definitions of these
589 void AddObserver(Observer
* observer
);
590 void RemoveObserver(Observer
* observer
);
591 void Run(Dispatcher
* dispatcher
);
594 // TODO(rvargas): Make this platform independent.
595 base::MessagePumpForUI
* pump_ui() {
596 return static_cast<base::MessagePumpForUI
*>(pump_
.get());
598 #endif // !defined(OS_MACOSX)
601 // Do not add any member variables to MessageLoopForUI! This is important b/c
602 // MessageLoopForUI is often allocated via MessageLoop(TYPE_UI). Any extra
603 // data that you need should be stored on the MessageLoop's pump_ instance.
604 COMPILE_ASSERT(sizeof(MessageLoop
) == sizeof(MessageLoopForUI
),
605 MessageLoopForUI_should_not_have_extra_member_variables
);
607 //-----------------------------------------------------------------------------
608 // MessageLoopForIO extends MessageLoop with methods that are particular to a
609 // MessageLoop instantiated with TYPE_IO.
611 // This class is typically used like so:
612 // MessageLoopForIO::current()->...call some method...
614 class BASE_API MessageLoopForIO
: public MessageLoop
{
617 typedef base::MessagePumpForIO::IOHandler IOHandler
;
618 typedef base::MessagePumpForIO::IOContext IOContext
;
619 typedef base::MessagePumpForIO::IOObserver IOObserver
;
620 #elif defined(OS_POSIX)
621 typedef base::MessagePumpLibevent::Watcher Watcher
;
622 typedef base::MessagePumpLibevent::FileDescriptorWatcher
623 FileDescriptorWatcher
;
624 typedef base::MessagePumpLibevent::IOObserver IOObserver
;
627 WATCH_READ
= base::MessagePumpLibevent::WATCH_READ
,
628 WATCH_WRITE
= base::MessagePumpLibevent::WATCH_WRITE
,
629 WATCH_READ_WRITE
= base::MessagePumpLibevent::WATCH_READ_WRITE
634 MessageLoopForIO() : MessageLoop(TYPE_IO
) {
637 // Returns the MessageLoopForIO of the current thread.
638 static MessageLoopForIO
* current() {
639 MessageLoop
* loop
= MessageLoop::current();
640 DCHECK_EQ(MessageLoop::TYPE_IO
, loop
->type());
641 return static_cast<MessageLoopForIO
*>(loop
);
644 void AddIOObserver(IOObserver
* io_observer
) {
645 pump_io()->AddIOObserver(io_observer
);
648 void RemoveIOObserver(IOObserver
* io_observer
) {
649 pump_io()->RemoveIOObserver(io_observer
);
653 // Please see MessagePumpWin for definitions of these methods.
654 void RegisterIOHandler(HANDLE file_handle
, IOHandler
* handler
);
655 bool WaitForIOCompletion(DWORD timeout
, IOHandler
* filter
);
658 // TODO(rvargas): Make this platform independent.
659 base::MessagePumpForIO
* pump_io() {
660 return static_cast<base::MessagePumpForIO
*>(pump_
.get());
663 #elif defined(OS_POSIX)
664 // Please see MessagePumpLibevent for definition.
665 bool WatchFileDescriptor(int fd
,
668 FileDescriptorWatcher
*controller
,
672 base::MessagePumpLibevent
* pump_io() {
673 return static_cast<base::MessagePumpLibevent
*>(pump_
.get());
675 #endif // defined(OS_POSIX)
678 // Do not add any member variables to MessageLoopForIO! This is important b/c
679 // MessageLoopForIO is often allocated via MessageLoop(TYPE_IO). Any extra
680 // data that you need should be stored on the MessageLoop's pump_ instance.
681 COMPILE_ASSERT(sizeof(MessageLoop
) == sizeof(MessageLoopForIO
),
682 MessageLoopForIO_should_not_have_extra_member_variables
);
684 #endif // BASE_MESSAGE_LOOP_H_