1 // Copyright (c) 2012 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_export.h"
13 #include "base/basictypes.h"
14 #include "base/callback_forward.h"
15 #include "base/location.h"
16 #include "base/memory/ref_counted.h"
17 #include "base/message_loop_proxy.h"
18 #include "base/message_pump.h"
19 #include "base/observer_list.h"
20 #include "base/pending_task.h"
21 #include "base/sequenced_task_runner_helpers.h"
22 #include "base/synchronization/lock.h"
23 #include "base/tracking_info.h"
24 #include "base/time.h"
27 // We need this to declare base::MessagePumpWin::Dispatcher, which we should
28 // really just eliminate.
29 #include "base/message_pump_win.h"
30 #elif defined(OS_POSIX)
31 #include "base/message_pump_libevent.h"
32 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
34 #if defined(USE_WAYLAND)
35 #include "base/message_pump_wayland.h"
36 #elif defined(USE_AURA)
37 #include "base/message_pump_x.h"
39 #include "base/message_pump_gtk.h"
49 // A MessageLoop is used to process events for a particular thread. There is
50 // at most one MessageLoop instance per thread.
52 // Events include at a minimum Task instances submitted to PostTask or those
53 // managed by TimerManager. Depending on the type of message pump used by the
54 // MessageLoop other events such as UI messages may be processed. On Windows
55 // APC calls (as time permits) and signals sent to a registered set of HANDLEs
56 // may also be processed.
58 // NOTE: Unless otherwise specified, a MessageLoop's methods may only be called
59 // on the thread where the MessageLoop's Run method executes.
61 // NOTE: MessageLoop has task reentrancy protection. This means that if a
62 // task is being processed, a second task cannot start until the first task is
63 // finished. Reentrancy can happen when processing a task, and an inner
64 // message pump is created. That inner pump then processes native messages
65 // which could implicitly start an inner task. Inner message pumps are created
66 // with dialogs (DialogBox), common dialogs (GetOpenFileName), OLE functions
67 // (DoDragDrop), printer functions (StartDoc) and *many* others.
69 // Sample workaround when inner task processing is needed:
72 // MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());
73 // hr = DoDragDrop(...); // Implicitly runs a modal message loop.
75 // // Process |hr| (the result returned by DoDragDrop()).
77 // Please be SURE your task is reentrant (nestable) and all global variables
78 // are stable and accessible before calling SetNestableTasksAllowed(true).
80 class BASE_EXPORT MessageLoop
: public base::MessagePump::Delegate
{
83 typedef base::MessagePumpWin::Dispatcher Dispatcher
;
84 typedef base::MessagePumpObserver Observer
;
85 #elif !defined(OS_MACOSX) && !defined(OS_ANDROID)
86 typedef base::MessagePumpDispatcher Dispatcher
;
87 typedef base::MessagePumpObserver Observer
;
90 // A MessageLoop has a particular type, which indicates the set of
91 // asynchronous events it may process in addition to tasks and timers.
94 // This type of ML only supports tasks and timers.
97 // This type of ML also supports native UI events (e.g., Windows messages).
98 // See also MessageLoopForUI.
101 // This type of ML also supports asynchronous IO. See also
110 // Normally, it is not necessary to instantiate a MessageLoop. Instead, it
111 // is typical to make use of the current thread's MessageLoop instance.
112 explicit MessageLoop(Type type
= TYPE_DEFAULT
);
113 virtual ~MessageLoop();
115 // Returns the MessageLoop object for the current thread, or null if none.
116 static MessageLoop
* current();
118 static void EnableHistogrammer(bool enable_histogrammer
);
120 typedef base::MessagePump
* (MessagePumpFactory
)();
121 // Using the given base::MessagePumpForUIFactory to override the default
122 // MessagePump implementation for 'TYPE_UI'.
123 static void InitMessagePumpForUIFactory(MessagePumpFactory
* factory
);
125 // A DestructionObserver is notified when the current MessageLoop is being
126 // destroyed. These observers are notified prior to MessageLoop::current()
127 // being changed to return NULL. This gives interested parties the chance to
128 // do final cleanup that depends on the MessageLoop.
130 // NOTE: Any tasks posted to the MessageLoop during this notification will
131 // not be run. Instead, they will be deleted.
133 class BASE_EXPORT DestructionObserver
{
135 virtual void WillDestroyCurrentMessageLoop() = 0;
138 virtual ~DestructionObserver();
141 // Add a DestructionObserver, which will start receiving notifications
143 void AddDestructionObserver(DestructionObserver
* destruction_observer
);
145 // Remove a DestructionObserver. It is safe to call this method while a
146 // DestructionObserver is receiving a notification callback.
147 void RemoveDestructionObserver(DestructionObserver
* destruction_observer
);
149 // The "PostTask" family of methods call the task's Run method asynchronously
150 // from within a message loop at some point in the future.
152 // With the PostTask variant, tasks are invoked in FIFO order, inter-mixed
153 // with normal UI or IO event processing. With the PostDelayedTask variant,
154 // tasks are called after at least approximately 'delay_ms' have elapsed.
156 // The NonNestable variants work similarly except that they promise never to
157 // dispatch the task from a nested invocation of MessageLoop::Run. Instead,
158 // such tasks get deferred until the top-most MessageLoop::Run is executing.
160 // The MessageLoop takes ownership of the Task, and deletes it after it has
163 // NOTE: These methods may be called on any thread. The Task will be invoked
164 // on the thread that executes MessageLoop::Run().
166 const tracked_objects::Location
& from_here
,
167 const base::Closure
& task
);
169 void PostDelayedTask(
170 const tracked_objects::Location
& from_here
,
171 const base::Closure
& task
, int64 delay_ms
);
173 void PostDelayedTask(
174 const tracked_objects::Location
& from_here
,
175 const base::Closure
& task
,
176 base::TimeDelta delay
);
178 void PostNonNestableTask(
179 const tracked_objects::Location
& from_here
,
180 const base::Closure
& task
);
182 void PostNonNestableDelayedTask(
183 const tracked_objects::Location
& from_here
,
184 const base::Closure
& task
, int64 delay_ms
);
186 void PostNonNestableDelayedTask(
187 const tracked_objects::Location
& from_here
,
188 const base::Closure
& task
,
189 base::TimeDelta delay
);
191 // A variant on PostTask that deletes the given object. This is useful
192 // if the object needs to live until the next run of the MessageLoop (for
193 // example, deleting a RenderProcessHost from within an IPC callback is not
196 // NOTE: This method may be called on any thread. The object will be deleted
197 // on the thread that executes MessageLoop::Run(). If this is not the same
198 // as the thread that calls PostDelayedTask(FROM_HERE, ), then T MUST inherit
199 // from RefCountedThreadSafe<T>!
201 void DeleteSoon(const tracked_objects::Location
& from_here
, const T
* object
) {
202 base::subtle::DeleteHelperInternal
<T
, void>::DeleteViaSequencedTaskRunner(
203 this, from_here
, object
);
206 // A variant on PostTask that releases the given reference counted object
207 // (by calling its Release method). This is useful if the object needs to
208 // live until the next run of the MessageLoop, or if the object needs to be
209 // released on a particular thread.
211 // NOTE: This method may be called on any thread. The object will be
212 // released (and thus possibly deleted) on the thread that executes
213 // MessageLoop::Run(). If this is not the same as the thread that calls
214 // PostDelayedTask(FROM_HERE, ), then T MUST inherit from
215 // RefCountedThreadSafe<T>!
217 void ReleaseSoon(const tracked_objects::Location
& from_here
,
219 base::subtle::ReleaseHelperInternal
<T
, void>::ReleaseViaSequencedTaskRunner(
220 this, from_here
, object
);
223 // Run the message loop.
226 // Process all pending tasks, windows messages, etc., but don't wait/sleep.
227 // Return as soon as all items that can be run are taken care of.
228 void RunAllPending();
230 // Signals the Run method to return after it is done processing all pending
231 // messages. This method may only be called on the same thread that called
232 // Run, and Run must still be on the call stack.
234 // Use QuitClosure if you need to Quit another thread's MessageLoop, but note
235 // that doing so is fairly dangerous if the target thread makes nested calls
236 // to MessageLoop::Run. The problem being that you won't know which nested
237 // run loop you are quitting, so be careful!
240 // This method is a variant of Quit, that does not wait for pending messages
241 // to be processed before returning from Run.
244 // Invokes Quit on the current MessageLoop when run. Useful to schedule an
245 // arbitrary MessageLoop to Quit.
246 static base::Closure
QuitClosure();
248 // Returns the type passed to the constructor.
249 Type
type() const { return type_
; }
251 // Optional call to connect the thread name with this loop.
252 void set_thread_name(const std::string
& thread_name
) {
253 DCHECK(thread_name_
.empty()) << "Should not rename this thread!";
254 thread_name_
= thread_name
;
256 const std::string
& thread_name() const { return thread_name_
; }
258 // Gets the message loop proxy associated with this message loop.
259 scoped_refptr
<base::MessageLoopProxy
> message_loop_proxy() {
260 return message_loop_proxy_
.get();
263 // Enables or disables the recursive task processing. This happens in the case
264 // of recursive message loops. Some unwanted message loop may occurs when
265 // using common controls or printer functions. By default, recursive task
266 // processing is disabled.
268 // Please utilize |ScopedNestableTaskAllower| instead of calling these methods
269 // directly. In general nestable message loops are to be avoided. They are
270 // dangerous and difficult to get right, so please use with extreme caution.
272 // The specific case where tasks get queued is:
273 // - The thread is running a message loop.
274 // - It receives a task #1 and execute it.
275 // - The task #1 implicitly start a message loop, like a MessageBox in the
276 // unit test. This can also be StartDoc or GetSaveFileName.
277 // - The thread receives a task #2 before or while in this second message
279 // - With NestableTasksAllowed set to true, the task #2 will run right away.
280 // Otherwise, it will get executed right after task #1 completes at "thread
281 // message loop level".
282 void SetNestableTasksAllowed(bool allowed
);
283 bool NestableTasksAllowed() const;
285 // Enables nestable tasks on |loop| while in scope.
286 class ScopedNestableTaskAllower
{
288 explicit ScopedNestableTaskAllower(MessageLoop
* loop
)
290 old_state_(loop_
->NestableTasksAllowed()) {
291 loop_
->SetNestableTasksAllowed(true);
293 ~ScopedNestableTaskAllower() {
294 loop_
->SetNestableTasksAllowed(old_state_
);
302 // Enables or disables the restoration during an exception of the unhandled
303 // exception filter that was active when Run() was called. This can happen
304 // if some third party code call SetUnhandledExceptionFilter() and never
305 // restores the previous filter.
306 void set_exception_restoration(bool restore
) {
307 exception_restoration_
= restore
;
310 // Returns true if we are currently running a nested message loop.
313 // A TaskObserver is an object that receives task notifications from the
316 // NOTE: A TaskObserver implementation should be extremely fast!
317 class BASE_EXPORT TaskObserver
{
321 // This method is called before processing a task.
322 virtual void WillProcessTask(base::TimeTicks time_posted
) = 0;
324 // This method is called after processing a task.
325 virtual void DidProcessTask(base::TimeTicks time_posted
) = 0;
328 virtual ~TaskObserver();
331 // These functions can only be called on the same thread that |this| is
333 void AddTaskObserver(TaskObserver
* task_observer
);
334 void RemoveTaskObserver(TaskObserver
* task_observer
);
336 // Returns true if the message loop has high resolution timers enabled.
337 // Provided for testing.
338 bool high_resolution_timers_enabled() {
340 return !high_resolution_timer_expiration_
.is_null();
346 // When we go into high resolution timer mode, we will stay in hi-res mode
348 static const int kHighResolutionTimerModeLeaseTimeMs
= 1000;
350 // Asserts that the MessageLoop is "idle".
351 void AssertIdle() const;
354 void set_os_modal_loop(bool os_modal_loop
) {
355 os_modal_loop_
= os_modal_loop
;
358 bool os_modal_loop() const {
359 return os_modal_loop_
;
363 // Can only be called from the thread that owns the MessageLoop.
364 bool is_running() const;
366 //----------------------------------------------------------------------------
369 // Used to count how many Run() invocations are on the stack.
372 // Used to record that Quit() was called, or that we should quit the pump
373 // once it becomes idle.
376 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
377 Dispatcher
* dispatcher
;
381 #if defined(OS_ANDROID)
382 // Android Java process manages the UI thread message loop. So its
383 // MessagePumpForUI needs to keep the RunState.
386 class BASE_EXPORT AutoRunState
: RunState
{
388 explicit AutoRunState(MessageLoop
* loop
);
392 RunState
* previous_state_
;
394 #if defined(OS_ANDROID)
399 base::MessagePumpWin
* pump_win() {
400 return static_cast<base::MessagePumpWin
*>(pump_
.get());
402 #elif defined(OS_POSIX)
403 base::MessagePumpLibevent
* pump_libevent() {
404 return static_cast<base::MessagePumpLibevent
*>(pump_
.get());
408 // A function to encapsulate all the exception handling capability in the
409 // stacks around the running of a main message loop. It will run the message
410 // loop in a SEH try block or not depending on the set_SEH_restoration()
411 // flag invoking respectively RunInternalInSEHFrame() or RunInternal().
415 __declspec(noinline
) void RunInternalInSEHFrame();
418 // A surrounding stack frame around the running of the message loop that
419 // supports all saving and restoring of state, as is needed for any/all (ugly)
423 // Called to process any delayed non-nestable tasks.
424 bool ProcessNextDelayedNonNestableTask();
426 // Runs the specified PendingTask.
427 void RunTask(const base::PendingTask
& pending_task
);
429 // Calls RunTask or queues the pending_task on the deferred task list if it
430 // cannot be run right now. Returns true if the task was run.
431 bool DeferOrRunPendingTask(const base::PendingTask
& pending_task
);
433 // Adds the pending task to delayed_work_queue_.
434 void AddToDelayedWorkQueue(const base::PendingTask
& pending_task
);
436 // Adds the pending task to our incoming_queue_.
438 // Caller retains ownership of |pending_task|, but this function will
439 // reset the value of pending_task->task. This is needed to ensure
440 // that the posting call stack does not retain pending_task->task
441 // beyond this function call.
442 void AddToIncomingQueue(base::PendingTask
* pending_task
);
444 // Load tasks from the incoming_queue_ into work_queue_ if the latter is
445 // empty. The former requires a lock to access, while the latter is directly
446 // accessible on this thread.
447 void ReloadWorkQueue();
449 // Delete tasks that haven't run yet without running them. Used in the
450 // destructor to make sure all the task's destructors get called. Returns
451 // true if some work was done.
452 bool DeletePendingTasks();
454 // Calculates the time at which a PendingTask should run.
455 base::TimeTicks
CalculateDelayedRuntime(int64 delay_ms
);
457 // Start recording histogram info about events and action IF it was enabled
458 // and IF the statistics recorder can accept a registration of our histogram.
459 void StartHistogrammer();
461 // Add occurrence of event to our histogram, so that we can see what is being
462 // done in a specific MessageLoop instance (i.e., specific thread).
463 // If message_histogram_ is NULL, this is a no-op.
464 void HistogramEvent(int event
);
466 // base::MessagePump::Delegate methods:
467 virtual bool DoWork() OVERRIDE
;
468 virtual bool DoDelayedWork(base::TimeTicks
* next_delayed_work_time
) OVERRIDE
;
469 virtual bool DoIdleWork() OVERRIDE
;
473 // A list of tasks that need to be processed by this instance. Note that
474 // this queue is only accessed (push/pop) by our current thread.
475 base::TaskQueue work_queue_
;
477 // Contains delayed tasks, sorted by their 'delayed_run_time' property.
478 base::DelayedTaskQueue delayed_work_queue_
;
480 // A recent snapshot of Time::Now(), used to check delayed_work_queue_.
481 base::TimeTicks recent_time_
;
483 // A queue of non-nestable tasks that we had to defer because when it came
484 // time to execute them we were in a nested message loop. They will execute
485 // once we're out of nested message loops.
486 base::TaskQueue deferred_non_nestable_work_queue_
;
488 scoped_refptr
<base::MessagePump
> pump_
;
490 ObserverList
<DestructionObserver
> destruction_observers_
;
492 // A recursion block that prevents accidentally running additional tasks when
493 // insider a (accidentally induced?) nested message pump.
494 bool nestable_tasks_allowed_
;
496 bool exception_restoration_
;
498 std::string thread_name_
;
499 // A profiling histogram showing the counts of various messages and events.
500 base::Histogram
* message_histogram_
;
502 // A null terminated list which creates an incoming_queue of tasks that are
503 // acquired under a mutex for processing on this instance's thread. These
504 // tasks have not yet been sorted out into items for our work_queue_ vs items
505 // that will be handled by the TimerManager.
506 base::TaskQueue incoming_queue_
;
507 // Protect access to incoming_queue_.
508 mutable base::Lock incoming_queue_lock_
;
513 base::TimeTicks high_resolution_timer_expiration_
;
514 // Should be set to true before calling Windows APIs like TrackPopupMenu, etc
515 // which enter a modal message loop.
519 // The next sequence number to use for delayed tasks.
520 int next_sequence_num_
;
522 ObserverList
<TaskObserver
> task_observers_
;
524 // The message loop proxy associated with this message loop, if one exists.
525 scoped_refptr
<base::MessageLoopProxy
> message_loop_proxy_
;
528 template <class T
, class R
> friend class base::subtle::DeleteHelperInternal
;
529 template <class T
, class R
> friend class base::subtle::ReleaseHelperInternal
;
531 void DeleteSoonInternal(const tracked_objects::Location
& from_here
,
532 void(*deleter
)(const void*),
534 void ReleaseSoonInternal(const tracked_objects::Location
& from_here
,
535 void(*releaser
)(const void*),
539 DISALLOW_COPY_AND_ASSIGN(MessageLoop
);
542 //-----------------------------------------------------------------------------
543 // MessageLoopForUI extends MessageLoop with methods that are particular to a
544 // MessageLoop instantiated with TYPE_UI.
546 // This class is typically used like so:
547 // MessageLoopForUI::current()->...call some method...
549 class BASE_EXPORT MessageLoopForUI
: public MessageLoop
{
551 MessageLoopForUI() : MessageLoop(TYPE_UI
) {
554 // Returns the MessageLoopForUI of the current thread.
555 static MessageLoopForUI
* current() {
556 MessageLoop
* loop
= MessageLoop::current();
558 DCHECK_EQ(MessageLoop::TYPE_UI
, loop
->type());
559 return static_cast<MessageLoopForUI
*>(loop
);
563 void DidProcessMessage(const MSG
& message
);
564 #endif // defined(OS_WIN)
566 #if defined(OS_ANDROID)
567 // On Android, the UI message loop is handled by Java side. So Run() should
568 // never be called. Instead use Start(), which will forward all the native UI
569 // events to the Java message loop.
571 #elif !defined(OS_MACOSX)
572 // Please see message_pump_win/message_pump_glib for definitions of these
574 void AddObserver(Observer
* observer
);
575 void RemoveObserver(Observer
* observer
);
576 void RunWithDispatcher(Dispatcher
* dispatcher
);
577 void RunAllPendingWithDispatcher(Dispatcher
* dispatcher
);
580 // TODO(rvargas): Make this platform independent.
581 base::MessagePumpForUI
* pump_ui() {
582 return static_cast<base::MessagePumpForUI
*>(pump_
.get());
584 #endif // !defined(OS_MACOSX)
587 // Do not add any member variables to MessageLoopForUI! This is important b/c
588 // MessageLoopForUI is often allocated via MessageLoop(TYPE_UI). Any extra
589 // data that you need should be stored on the MessageLoop's pump_ instance.
590 COMPILE_ASSERT(sizeof(MessageLoop
) == sizeof(MessageLoopForUI
),
591 MessageLoopForUI_should_not_have_extra_member_variables
);
593 //-----------------------------------------------------------------------------
594 // MessageLoopForIO extends MessageLoop with methods that are particular to a
595 // MessageLoop instantiated with TYPE_IO.
597 // This class is typically used like so:
598 // MessageLoopForIO::current()->...call some method...
600 class BASE_EXPORT MessageLoopForIO
: public MessageLoop
{
603 typedef base::MessagePumpForIO::IOHandler IOHandler
;
604 typedef base::MessagePumpForIO::IOContext IOContext
;
605 typedef base::MessagePumpForIO::IOObserver IOObserver
;
606 #elif defined(OS_POSIX)
607 typedef base::MessagePumpLibevent::Watcher Watcher
;
608 typedef base::MessagePumpLibevent::FileDescriptorWatcher
609 FileDescriptorWatcher
;
610 typedef base::MessagePumpLibevent::IOObserver IOObserver
;
613 WATCH_READ
= base::MessagePumpLibevent::WATCH_READ
,
614 WATCH_WRITE
= base::MessagePumpLibevent::WATCH_WRITE
,
615 WATCH_READ_WRITE
= base::MessagePumpLibevent::WATCH_READ_WRITE
620 MessageLoopForIO() : MessageLoop(TYPE_IO
) {
623 // Returns the MessageLoopForIO of the current thread.
624 static MessageLoopForIO
* current() {
625 MessageLoop
* loop
= MessageLoop::current();
626 DCHECK_EQ(MessageLoop::TYPE_IO
, loop
->type());
627 return static_cast<MessageLoopForIO
*>(loop
);
630 void AddIOObserver(IOObserver
* io_observer
) {
631 pump_io()->AddIOObserver(io_observer
);
634 void RemoveIOObserver(IOObserver
* io_observer
) {
635 pump_io()->RemoveIOObserver(io_observer
);
639 // Please see MessagePumpWin for definitions of these methods.
640 void RegisterIOHandler(HANDLE file_handle
, IOHandler
* handler
);
641 bool WaitForIOCompletion(DWORD timeout
, IOHandler
* filter
);
644 // TODO(rvargas): Make this platform independent.
645 base::MessagePumpForIO
* pump_io() {
646 return static_cast<base::MessagePumpForIO
*>(pump_
.get());
649 #elif defined(OS_POSIX)
650 // Please see MessagePumpLibevent for definition.
651 bool WatchFileDescriptor(int fd
,
654 FileDescriptorWatcher
* controller
,
658 base::MessagePumpLibevent
* pump_io() {
659 return static_cast<base::MessagePumpLibevent
*>(pump_
.get());
661 #endif // defined(OS_POSIX)
664 // Do not add any member variables to MessageLoopForIO! This is important b/c
665 // MessageLoopForIO is often allocated via MessageLoop(TYPE_IO). Any extra
666 // data that you need should be stored on the MessageLoop's pump_ instance.
667 COMPILE_ASSERT(sizeof(MessageLoop
) == sizeof(MessageLoopForIO
),
668 MessageLoopForIO_should_not_have_extra_member_variables
);
670 #endif // BASE_MESSAGE_LOOP_H_