1 // Copyright 2013 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_MESSAGE_LOOP_H_
6 #define BASE_MESSAGE_LOOP_MESSAGE_LOOP_H_
11 #include "base/base_export.h"
12 #include "base/basictypes.h"
13 #include "base/callback_forward.h"
14 #include "base/debug/task_annotator.h"
15 #include "base/location.h"
16 #include "base/memory/ref_counted.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/message_loop/incoming_task_queue.h"
19 #include "base/message_loop/message_loop_proxy.h"
20 #include "base/message_loop/message_loop_proxy_impl.h"
21 #include "base/message_loop/message_pump.h"
22 #include "base/message_loop/timer_slack.h"
23 #include "base/observer_list.h"
24 #include "base/pending_task.h"
25 #include "base/sequenced_task_runner_helpers.h"
26 #include "base/synchronization/lock.h"
27 #include "base/time/time.h"
28 #include "base/tracking_info.h"
30 // TODO(sky): these includes should not be necessary. Nuke them.
32 #include "base/message_loop/message_pump_win.h"
34 #include "base/message_loop/message_pump_io_ios.h"
35 #elif defined(OS_POSIX)
36 #include "base/message_loop/message_pump_libevent.h"
43 class ThreadTaskRunnerHandle
;
46 // A MessageLoop is used to process events for a particular thread. There is
47 // at most one MessageLoop instance per thread.
49 // Events include at a minimum Task instances submitted to PostTask and its
50 // variants. Depending on the type of message pump used by the MessageLoop
51 // other events such as UI messages may be processed. On Windows APC calls (as
52 // time permits) and signals sent to a registered set of HANDLEs may also be
55 // NOTE: Unless otherwise specified, a MessageLoop's methods may only be called
56 // on the thread where the MessageLoop's Run method executes.
58 // NOTE: MessageLoop has task reentrancy protection. This means that if a
59 // task is being processed, a second task cannot start until the first task is
60 // finished. Reentrancy can happen when processing a task, and an inner
61 // message pump is created. That inner pump then processes native messages
62 // which could implicitly start an inner task. Inner message pumps are created
63 // with dialogs (DialogBox), common dialogs (GetOpenFileName), OLE functions
64 // (DoDragDrop), printer functions (StartDoc) and *many* others.
66 // Sample workaround when inner task processing is needed:
69 // MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());
70 // hr = DoDragDrop(...); // Implicitly runs a modal message loop.
72 // // Process |hr| (the result returned by DoDragDrop()).
74 // Please be SURE your task is reentrant (nestable) and all global variables
75 // are stable and accessible before calling SetNestableTasksAllowed(true).
77 class BASE_EXPORT MessageLoop
: public MessagePump::Delegate
{
79 // A MessageLoop has a particular type, which indicates the set of
80 // asynchronous events it may process in addition to tasks and timers.
83 // This type of ML only supports tasks and timers.
86 // This type of ML also supports native UI events (e.g., Windows messages).
87 // See also MessageLoopForUI.
90 // This type of ML also supports asynchronous IO. See also
94 // This type of ML is backed by a Java message handler which is responsible
95 // for running the tasks added to the ML. This is only for use on Android.
96 // TYPE_JAVA behaves in essence like TYPE_UI, except during construction
97 // where it does not use the main thread specific pump factory.
100 // MessagePump was supplied to constructor.
107 #if defined(OS_ANDROID)
109 #endif // defined(OS_ANDROID)
112 // Normally, it is not necessary to instantiate a MessageLoop. Instead, it
113 // is typical to make use of the current thread's MessageLoop instance.
114 explicit MessageLoop(Type type
= TYPE_DEFAULT
);
115 // Creates a TYPE_CUSTOM MessageLoop with the supplied MessagePump, which must
117 explicit MessageLoop(scoped_ptr
<base::MessagePump
> pump
);
118 ~MessageLoop() override
;
120 // Returns the MessageLoop object for the current thread, or null if none.
121 static MessageLoop
* current();
123 static void EnableHistogrammer(bool enable_histogrammer
);
125 typedef scoped_ptr
<MessagePump
> (MessagePumpFactory
)();
126 // Uses the given base::MessagePumpForUIFactory to override the default
127 // MessagePump implementation for 'TYPE_UI'. Returns true if the factory
128 // was successfully registered.
129 static bool InitMessagePumpForUIFactory(MessagePumpFactory
* factory
);
131 // Creates the default MessagePump based on |type|. Caller owns return
133 static scoped_ptr
<MessagePump
> CreateMessagePumpForType(Type type
);
134 // A DestructionObserver is notified when the current MessageLoop is being
135 // destroyed. These observers are notified prior to MessageLoop::current()
136 // being changed to return NULL. This gives interested parties the chance to
137 // do final cleanup that depends on the MessageLoop.
139 // NOTE: Any tasks posted to the MessageLoop during this notification will
140 // not be run. Instead, they will be deleted.
142 class BASE_EXPORT DestructionObserver
{
144 virtual void WillDestroyCurrentMessageLoop() = 0;
147 virtual ~DestructionObserver();
150 // Add a DestructionObserver, which will start receiving notifications
152 void AddDestructionObserver(DestructionObserver
* destruction_observer
);
154 // Remove a DestructionObserver. It is safe to call this method while a
155 // DestructionObserver is receiving a notification callback.
156 void RemoveDestructionObserver(DestructionObserver
* destruction_observer
);
158 // NOTE: Deprecated; prefer task_runner() and the TaskRunner interfaces.
159 // TODO(skyostil): Remove these functions (crbug.com/465354).
161 // The "PostTask" family of methods call the task's Run method asynchronously
162 // from within a message loop at some point in the future.
164 // With the PostTask variant, tasks are invoked in FIFO order, inter-mixed
165 // with normal UI or IO event processing. With the PostDelayedTask variant,
166 // tasks are called after at least approximately 'delay_ms' have elapsed.
168 // The NonNestable variants work similarly except that they promise never to
169 // dispatch the task from a nested invocation of MessageLoop::Run. Instead,
170 // such tasks get deferred until the top-most MessageLoop::Run is executing.
172 // The MessageLoop takes ownership of the Task, and deletes it after it has
175 // PostTask(from_here, task) is equivalent to
176 // PostDelayedTask(from_here, task, 0).
178 // NOTE: These methods may be called on any thread. The Task will be invoked
179 // on the thread that executes MessageLoop::Run().
180 void PostTask(const tracked_objects::Location
& from_here
,
181 const Closure
& task
);
183 void PostDelayedTask(const tracked_objects::Location
& from_here
,
187 void PostNonNestableTask(const tracked_objects::Location
& from_here
,
188 const Closure
& task
);
190 void PostNonNestableDelayedTask(const tracked_objects::Location
& from_here
,
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().
202 void DeleteSoon(const tracked_objects::Location
& from_here
, const T
* object
) {
203 base::subtle::DeleteHelperInternal
<T
, void>::DeleteViaSequencedTaskRunner(
204 this, from_here
, object
);
207 // A variant on PostTask that releases the given reference counted object
208 // (by calling its Release method). This is useful if the object needs to
209 // live until the next run of the MessageLoop, or if the object needs to be
210 // released on a particular thread.
212 // A common pattern is to manually increment the object's reference count
213 // (AddRef), clear the pointer, then issue a ReleaseSoon. The reference count
214 // is incremented manually to ensure clearing the pointer does not trigger a
215 // delete and to account for the upcoming decrement (ReleaseSoon). For
218 // scoped_refptr<Foo> foo = ...
220 // Foo* raw_foo = foo.get();
222 // message_loop->ReleaseSoon(raw_foo);
224 // NOTE: This method may be called on any thread. The object will be
225 // released (and thus possibly deleted) on the thread that executes
226 // MessageLoop::Run(). If this is not the same as the thread that calls
227 // ReleaseSoon(FROM_HERE, ), then T MUST inherit from
228 // RefCountedThreadSafe<T>!
230 void ReleaseSoon(const tracked_objects::Location
& from_here
,
232 base::subtle::ReleaseHelperInternal
<T
, void>::ReleaseViaSequencedTaskRunner(
233 this, from_here
, object
);
236 // Deprecated: use RunLoop instead.
237 // Run the message loop.
240 // Deprecated: use RunLoop instead.
241 // Process all pending tasks, windows messages, etc., but don't wait/sleep.
242 // Return as soon as all items that can be run are taken care of.
245 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdle().
246 void Quit() { QuitWhenIdle(); }
248 // Deprecated: use RunLoop instead.
250 // Signals the Run method to return when it becomes idle. It will continue to
251 // process pending messages and future messages as long as they are enqueued.
252 // Warning: if the MessageLoop remains busy, it may never quit. Only use this
253 // Quit method when looping procedures (such as web pages) have been shut
256 // This method may only be called on the same thread that called Run, and Run
257 // must still be on the call stack.
259 // Use QuitClosure variants if you need to Quit another thread's MessageLoop,
260 // but note that doing so is fairly dangerous if the target thread makes
261 // nested calls to MessageLoop::Run. The problem being that you won't know
262 // which nested run loop you are quitting, so be careful!
265 // Deprecated: use RunLoop instead.
267 // This method is a variant of Quit, that does not wait for pending messages
268 // to be processed before returning from Run.
271 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdleClosure().
272 static Closure
QuitClosure() { return QuitWhenIdleClosure(); }
274 // Deprecated: use RunLoop instead.
275 // Construct a Closure that will call QuitWhenIdle(). Useful to schedule an
276 // arbitrary MessageLoop to QuitWhenIdle.
277 static Closure
QuitWhenIdleClosure();
279 // Set the timer slack for this message loop.
280 void SetTimerSlack(TimerSlack timer_slack
) {
281 pump_
->SetTimerSlack(timer_slack
);
284 // Returns true if this loop is |type|. This allows subclasses (especially
285 // those in tests) to specialize how they are identified.
286 virtual bool IsType(Type type
) const;
288 // Returns the type passed to the constructor.
289 Type
type() const { return type_
; }
291 // Optional call to connect the thread name with this loop.
292 void set_thread_name(const std::string
& thread_name
) {
293 DCHECK(thread_name_
.empty()) << "Should not rename this thread!";
294 thread_name_
= thread_name
;
296 const std::string
& thread_name() const { return thread_name_
; }
298 // Gets the message loop proxy associated with this message loop.
300 // NOTE: Deprecated; prefer task_runner() and the TaskRunner interfaces
301 scoped_refptr
<MessageLoopProxy
> message_loop_proxy() {
302 return message_loop_proxy_
;
305 // Gets the TaskRunner associated with this message loop.
306 // TODO(skyostil): Change this to return a const reference to a refptr
307 // once the internal type matches what is being returned (crbug.com/465354).
308 scoped_refptr
<SingleThreadTaskRunner
> task_runner() {
309 return message_loop_proxy_
;
312 // Enables or disables the recursive task processing. This happens in the case
313 // of recursive message loops. Some unwanted message loop may occurs when
314 // using common controls or printer functions. By default, recursive task
315 // processing is disabled.
317 // Please utilize |ScopedNestableTaskAllower| instead of calling these methods
318 // directly. In general nestable message loops are to be avoided. They are
319 // dangerous and difficult to get right, so please use with extreme caution.
321 // The specific case where tasks get queued is:
322 // - The thread is running a message loop.
323 // - It receives a task #1 and execute it.
324 // - The task #1 implicitly start a message loop, like a MessageBox in the
325 // unit test. This can also be StartDoc or GetSaveFileName.
326 // - The thread receives a task #2 before or while in this second message
328 // - With NestableTasksAllowed set to true, the task #2 will run right away.
329 // Otherwise, it will get executed right after task #1 completes at "thread
330 // message loop level".
331 void SetNestableTasksAllowed(bool allowed
);
332 bool NestableTasksAllowed() const;
334 // Enables nestable tasks on |loop| while in scope.
335 class ScopedNestableTaskAllower
{
337 explicit ScopedNestableTaskAllower(MessageLoop
* loop
)
339 old_state_(loop_
->NestableTasksAllowed()) {
340 loop_
->SetNestableTasksAllowed(true);
342 ~ScopedNestableTaskAllower() {
343 loop_
->SetNestableTasksAllowed(old_state_
);
351 // Returns true if we are currently running a nested message loop.
354 // A TaskObserver is an object that receives task notifications from the
357 // NOTE: A TaskObserver implementation should be extremely fast!
358 class BASE_EXPORT TaskObserver
{
362 // This method is called before processing a task.
363 virtual void WillProcessTask(const PendingTask
& pending_task
) = 0;
365 // This method is called after processing a task.
366 virtual void DidProcessTask(const PendingTask
& pending_task
) = 0;
369 virtual ~TaskObserver();
372 // These functions can only be called on the same thread that |this| is
374 void AddTaskObserver(TaskObserver
* task_observer
);
375 void RemoveTaskObserver(TaskObserver
* task_observer
);
378 void set_os_modal_loop(bool os_modal_loop
) {
379 os_modal_loop_
= os_modal_loop
;
382 bool os_modal_loop() const {
383 return os_modal_loop_
;
387 // Can only be called from the thread that owns the MessageLoop.
388 bool is_running() const;
390 // Returns true if the message loop has high resolution timers enabled.
391 // Provided for testing.
392 bool HasHighResolutionTasks();
394 // Returns true if the message loop is "idle". Provided for testing.
395 bool IsIdleForTesting();
397 // Wakes up the message pump. Can be called on any thread. The caller is
398 // responsible for synchronizing ScheduleWork() calls.
401 // Returns the TaskAnnotator which is used to add debug information to posted
403 debug::TaskAnnotator
* task_annotator() { return &task_annotator_
; }
405 // Runs the specified PendingTask.
406 void RunTask(const PendingTask
& pending_task
);
408 //----------------------------------------------------------------------------
410 scoped_ptr
<MessagePump
> pump_
;
413 friend class RunLoop
;
415 // Configures various members for the two constructors.
418 // Invokes the actual run loop using the message pump.
421 // Called to process any delayed non-nestable tasks.
422 bool ProcessNextDelayedNonNestableTask();
424 // Calls RunTask or queues the pending_task on the deferred task list if it
425 // cannot be run right now. Returns true if the task was run.
426 bool DeferOrRunPendingTask(const PendingTask
& pending_task
);
428 // Adds the pending task to delayed_work_queue_.
429 void AddToDelayedWorkQueue(const PendingTask
& pending_task
);
431 // Delete tasks that haven't run yet without running them. Used in the
432 // destructor to make sure all the task's destructors get called. Returns
433 // true if some work was done.
434 bool DeletePendingTasks();
436 // Loads tasks from the incoming queue to |work_queue_| if the latter is
438 void ReloadWorkQueue();
440 // Start recording histogram info about events and action IF it was enabled
441 // and IF the statistics recorder can accept a registration of our histogram.
442 void StartHistogrammer();
444 // Add occurrence of event to our histogram, so that we can see what is being
445 // done in a specific MessageLoop instance (i.e., specific thread).
446 // If message_histogram_ is NULL, this is a no-op.
447 void HistogramEvent(int event
);
449 // MessagePump::Delegate methods:
450 bool DoWork() override
;
451 bool DoDelayedWork(TimeTicks
* next_delayed_work_time
) override
;
452 bool DoIdleWork() override
;
456 // A list of tasks that need to be processed by this instance. Note that
457 // this queue is only accessed (push/pop) by our current thread.
458 TaskQueue work_queue_
;
461 // How many high resolution tasks are in the pending task queue. This value
462 // increases by N every time we call ReloadWorkQueue() and decreases by 1
463 // every time we call RunTask() if the task needs a high resolution timer.
464 int pending_high_res_tasks_
;
465 // Tracks if we have requested high resolution timers. Its only use is to
466 // turn off the high resolution timer upon loop destruction.
467 bool in_high_res_mode_
;
470 // Contains delayed tasks, sorted by their 'delayed_run_time' property.
471 DelayedTaskQueue delayed_work_queue_
;
473 // A recent snapshot of Time::Now(), used to check delayed_work_queue_.
474 TimeTicks recent_time_
;
476 // A queue of non-nestable tasks that we had to defer because when it came
477 // time to execute them we were in a nested message loop. They will execute
478 // once we're out of nested message loops.
479 TaskQueue deferred_non_nestable_work_queue_
;
481 ObserverList
<DestructionObserver
> destruction_observers_
;
483 // A recursion block that prevents accidentally running additional tasks when
484 // insider a (accidentally induced?) nested message pump.
485 bool nestable_tasks_allowed_
;
488 // Should be set to true before calling Windows APIs like TrackPopupMenu, etc
489 // which enter a modal message loop.
493 std::string thread_name_
;
494 // A profiling histogram showing the counts of various messages and events.
495 HistogramBase
* message_histogram_
;
499 ObserverList
<TaskObserver
> task_observers_
;
501 debug::TaskAnnotator task_annotator_
;
503 scoped_refptr
<internal::IncomingTaskQueue
> incoming_task_queue_
;
505 // The message loop proxy associated with this message loop.
506 scoped_refptr
<internal::MessageLoopProxyImpl
> message_loop_proxy_
;
507 scoped_ptr
<ThreadTaskRunnerHandle
> thread_task_runner_handle_
;
509 template <class T
, class R
> friend class base::subtle::DeleteHelperInternal
;
510 template <class T
, class R
> friend class base::subtle::ReleaseHelperInternal
;
512 void DeleteSoonInternal(const tracked_objects::Location
& from_here
,
513 void(*deleter
)(const void*),
515 void ReleaseSoonInternal(const tracked_objects::Location
& from_here
,
516 void(*releaser
)(const void*),
519 DISALLOW_COPY_AND_ASSIGN(MessageLoop
);
522 #if !defined(OS_NACL)
524 //-----------------------------------------------------------------------------
525 // MessageLoopForUI extends MessageLoop with methods that are particular to a
526 // MessageLoop instantiated with TYPE_UI.
528 // This class is typically used like so:
529 // MessageLoopForUI::current()->...call some method...
531 class BASE_EXPORT MessageLoopForUI
: public MessageLoop
{
533 MessageLoopForUI() : MessageLoop(TYPE_UI
) {
536 // Returns the MessageLoopForUI of the current thread.
537 static MessageLoopForUI
* current() {
538 MessageLoop
* loop
= MessageLoop::current();
540 DCHECK_EQ(MessageLoop::TYPE_UI
, loop
->type());
541 return static_cast<MessageLoopForUI
*>(loop
);
544 static bool IsCurrent() {
545 MessageLoop
* loop
= MessageLoop::current();
546 return loop
&& loop
->type() == MessageLoop::TYPE_UI
;
550 // On iOS, the main message loop cannot be Run(). Instead call Attach(),
551 // which connects this MessageLoop to the UI thread's CFRunLoop and allows
552 // PostTask() to work.
556 #if defined(OS_ANDROID)
557 // On Android, the UI message loop is handled by Java side. So Run() should
558 // never be called. Instead use Start(), which will forward all the native UI
559 // events to the Java message loop.
563 #if defined(USE_OZONE) || (defined(USE_X11) && !defined(USE_GLIB))
564 // Please see MessagePumpLibevent for definition.
565 bool WatchFileDescriptor(
568 MessagePumpLibevent::Mode mode
,
569 MessagePumpLibevent::FileDescriptorWatcher
* controller
,
570 MessagePumpLibevent::Watcher
* delegate
);
574 // Do not add any member variables to MessageLoopForUI! This is important b/c
575 // MessageLoopForUI is often allocated via MessageLoop(TYPE_UI). Any extra
576 // data that you need should be stored on the MessageLoop's pump_ instance.
577 COMPILE_ASSERT(sizeof(MessageLoop
) == sizeof(MessageLoopForUI
),
578 MessageLoopForUI_should_not_have_extra_member_variables
);
580 #endif // !defined(OS_NACL)
582 //-----------------------------------------------------------------------------
583 // MessageLoopForIO extends MessageLoop with methods that are particular to a
584 // MessageLoop instantiated with TYPE_IO.
586 // This class is typically used like so:
587 // MessageLoopForIO::current()->...call some method...
589 class BASE_EXPORT MessageLoopForIO
: public MessageLoop
{
591 MessageLoopForIO() : MessageLoop(TYPE_IO
) {
594 // Returns the MessageLoopForIO of the current thread.
595 static MessageLoopForIO
* current() {
596 MessageLoop
* loop
= MessageLoop::current();
597 DCHECK_EQ(MessageLoop::TYPE_IO
, loop
->type());
598 return static_cast<MessageLoopForIO
*>(loop
);
601 static bool IsCurrent() {
602 MessageLoop
* loop
= MessageLoop::current();
603 return loop
&& loop
->type() == MessageLoop::TYPE_IO
;
606 #if !defined(OS_NACL_SFI)
609 typedef MessagePumpForIO::IOHandler IOHandler
;
610 typedef MessagePumpForIO::IOContext IOContext
;
611 typedef MessagePumpForIO::IOObserver IOObserver
;
612 #elif defined(OS_IOS)
613 typedef MessagePumpIOSForIO::Watcher Watcher
;
614 typedef MessagePumpIOSForIO::FileDescriptorWatcher
615 FileDescriptorWatcher
;
616 typedef MessagePumpIOSForIO::IOObserver IOObserver
;
619 WATCH_READ
= MessagePumpIOSForIO::WATCH_READ
,
620 WATCH_WRITE
= MessagePumpIOSForIO::WATCH_WRITE
,
621 WATCH_READ_WRITE
= MessagePumpIOSForIO::WATCH_READ_WRITE
623 #elif defined(OS_POSIX)
624 typedef MessagePumpLibevent::Watcher Watcher
;
625 typedef MessagePumpLibevent::FileDescriptorWatcher
626 FileDescriptorWatcher
;
627 typedef MessagePumpLibevent::IOObserver IOObserver
;
630 WATCH_READ
= MessagePumpLibevent::WATCH_READ
,
631 WATCH_WRITE
= MessagePumpLibevent::WATCH_WRITE
,
632 WATCH_READ_WRITE
= MessagePumpLibevent::WATCH_READ_WRITE
636 void AddIOObserver(IOObserver
* io_observer
);
637 void RemoveIOObserver(IOObserver
* io_observer
);
640 // Please see MessagePumpWin for definitions of these methods.
641 void RegisterIOHandler(HANDLE file
, IOHandler
* handler
);
642 bool RegisterJobObject(HANDLE job
, IOHandler
* handler
);
643 bool WaitForIOCompletion(DWORD timeout
, IOHandler
* filter
);
644 #elif defined(OS_POSIX)
645 // Please see MessagePumpIOSForIO/MessagePumpLibevent for definition.
646 bool WatchFileDescriptor(int fd
,
649 FileDescriptorWatcher
* controller
,
651 #endif // defined(OS_IOS) || defined(OS_POSIX)
652 #endif // !defined(OS_NACL_SFI)
655 // Do not add any member variables to MessageLoopForIO! This is important b/c
656 // MessageLoopForIO is often allocated via MessageLoop(TYPE_IO). Any extra
657 // data that you need should be stored on the MessageLoop's pump_ instance.
658 COMPILE_ASSERT(sizeof(MessageLoop
) == sizeof(MessageLoopForIO
),
659 MessageLoopForIO_should_not_have_extra_member_variables
);
663 #endif // BASE_MESSAGE_LOOP_MESSAGE_LOOP_H_