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 #include "base/message_loop/message_loop.h"
10 #include "base/compiler_specific.h"
11 #include "base/lazy_instance.h"
12 #include "base/logging.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/message_loop/message_pump_default.h"
15 #include "base/metrics/histogram.h"
16 #include "base/metrics/statistics_recorder.h"
17 #include "base/run_loop.h"
18 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
19 #include "base/thread_task_runner_handle.h"
20 #include "base/threading/thread_local.h"
21 #include "base/time/time.h"
22 #include "base/tracked_objects.h"
24 #if defined(OS_MACOSX)
25 #include "base/message_loop/message_pump_mac.h"
27 #if defined(OS_POSIX) && !defined(OS_IOS)
28 #include "base/message_loop/message_pump_libevent.h"
30 #if defined(OS_ANDROID)
31 #include "base/message_loop/message_pump_android.h"
34 #include "base/message_loop/message_pump_glib.h"
41 // A lazily created thread local storage for quick access to a thread's message
42 // loop, if one exists. This should be safe and free of static constructors.
43 LazyInstance
<base::ThreadLocalPointer
<MessageLoop
> >::Leaky lazy_tls_ptr
=
44 LAZY_INSTANCE_INITIALIZER
;
46 // Logical events for Histogram profiling. Run with -message-loop-histogrammer
47 // to get an accounting of messages and actions taken on each thread.
48 const int kTaskRunEvent
= 0x1;
50 const int kTimerEvent
= 0x2;
52 // Provide range of message IDs for use in histogramming and debug display.
53 const int kLeastNonZeroMessageId
= 1;
54 const int kMaxMessageId
= 1099;
55 const int kNumberOfDistinctMessagesDisplayed
= 1100;
57 // Provide a macro that takes an expression (such as a constant, or macro
58 // constant) and creates a pair to initalize an array of pairs. In this case,
59 // our pair consists of the expressions value, and the "stringized" version
60 // of the expression (i.e., the exrpression put in quotes). For example, if
64 // then the following:
65 // VALUE_TO_NUMBER_AND_NAME(FOO + BAR)
68 // We use the resulting array as an argument to our histogram, which reads the
69 // number as a bucket identifier, and proceeds to use the corresponding name
70 // in the pair (i.e., the quoted string) when printing out a histogram.
71 #define VALUE_TO_NUMBER_AND_NAME(name) {name, #name},
73 const LinearHistogram::DescriptionPair event_descriptions_
[] = {
74 // Provide some pretty print capability in our histogram for our internal
77 // A few events we handle (kindred to messages), and used to profile actions.
78 VALUE_TO_NUMBER_AND_NAME(kTaskRunEvent
)
79 VALUE_TO_NUMBER_AND_NAME(kTimerEvent
)
81 {-1, NULL
} // The list must be null terminated, per API to histogram.
83 #endif // !defined(OS_NACL)
85 bool enable_histogrammer_
= false;
87 MessageLoop::MessagePumpFactory
* message_pump_for_ui_factory_
= NULL
;
89 // Returns true if MessagePump::ScheduleWork() must be called one
90 // time for every task that is added to the MessageLoop incoming queue.
91 bool AlwaysNotifyPump(MessageLoop::Type type
) {
92 #if defined(OS_ANDROID)
93 // The Android UI message loop needs to get notified each time a task is added
94 // to the incoming queue.
95 return type
== MessageLoop::TYPE_UI
|| type
== MessageLoop::TYPE_JAVA
;
102 typedef MessagePumpIOSForIO MessagePumpForIO
;
103 #elif defined(OS_NACL)
104 typedef MessagePumpDefault MessagePumpForIO
;
105 #elif defined(OS_POSIX)
106 typedef MessagePumpLibevent MessagePumpForIO
;
109 MessagePumpForIO
* ToPumpIO(MessagePump
* pump
) {
110 return static_cast<MessagePumpForIO
*>(pump
);
115 //------------------------------------------------------------------------------
117 MessageLoop::TaskObserver::TaskObserver() {
120 MessageLoop::TaskObserver::~TaskObserver() {
123 MessageLoop::DestructionObserver::~DestructionObserver() {
126 //------------------------------------------------------------------------------
128 MessageLoop::MessageLoop(Type type
)
130 nestable_tasks_allowed_(true),
132 os_modal_loop_(false),
134 message_histogram_(NULL
),
138 pump_
= CreateMessagePumpForType(type
).Pass();
141 MessageLoop::MessageLoop(scoped_ptr
<MessagePump
> pump
)
142 : pump_(pump
.Pass()),
144 nestable_tasks_allowed_(true),
146 os_modal_loop_(false),
148 message_histogram_(NULL
),
154 MessageLoop::~MessageLoop() {
155 DCHECK_EQ(this, current());
159 // Clean up any unprocessed tasks, but take care: deleting a task could
160 // result in the addition of more tasks (e.g., via DeleteSoon). We set a
161 // limit on the number of times we will allow a deleted task to generate more
162 // tasks. Normally, we should only pass through this loop once or twice. If
163 // we end up hitting the loop limit, then it is probably due to one task that
164 // is being stubborn. Inspect the queues to see who is left.
166 for (int i
= 0; i
< 100; ++i
) {
167 DeletePendingTasks();
169 // If we end up with empty queues, then break out of the loop.
170 did_work
= DeletePendingTasks();
176 // Let interested parties have one last shot at accessing this.
177 FOR_EACH_OBSERVER(DestructionObserver
, destruction_observers_
,
178 WillDestroyCurrentMessageLoop());
180 thread_task_runner_handle_
.reset();
182 // Tell the incoming queue that we are dying.
183 incoming_task_queue_
->WillDestroyCurrentMessageLoop();
184 incoming_task_queue_
= NULL
;
185 message_loop_proxy_
= NULL
;
187 // OK, now make it so that no one can find us.
188 lazy_tls_ptr
.Pointer()->Set(NULL
);
192 MessageLoop
* MessageLoop::current() {
193 // TODO(darin): sadly, we cannot enable this yet since people call us even
194 // when they have no intention of using us.
195 // DCHECK(loop) << "Ouch, did you forget to initialize me?";
196 return lazy_tls_ptr
.Pointer()->Get();
200 void MessageLoop::EnableHistogrammer(bool enable
) {
201 enable_histogrammer_
= enable
;
205 bool MessageLoop::InitMessagePumpForUIFactory(MessagePumpFactory
* factory
) {
206 if (message_pump_for_ui_factory_
)
209 message_pump_for_ui_factory_
= factory
;
214 scoped_ptr
<MessagePump
> MessageLoop::CreateMessagePumpForType(Type type
) {
215 // TODO(rvargas): Get rid of the OS guards.
216 #if defined(USE_GLIB) && !defined(OS_NACL)
217 typedef MessagePumpGlib MessagePumpForUI
;
218 #elif defined(OS_LINUX) && !defined(OS_NACL)
219 typedef MessagePumpLibevent MessagePumpForUI
;
222 #if defined(OS_IOS) || defined(OS_MACOSX)
223 #define MESSAGE_PUMP_UI scoped_ptr<MessagePump>(MessagePumpMac::Create())
224 #elif defined(OS_NACL)
225 // Currently NaCl doesn't have a UI MessageLoop.
226 // TODO(abarth): Figure out if we need this.
227 #define MESSAGE_PUMP_UI scoped_ptr<MessagePump>()
229 #define MESSAGE_PUMP_UI scoped_ptr<MessagePump>(new MessagePumpForUI())
232 #if defined(OS_MACOSX)
233 // Use an OS native runloop on Mac to support timer coalescing.
234 #define MESSAGE_PUMP_DEFAULT \
235 scoped_ptr<MessagePump>(new MessagePumpCFRunLoop())
237 #define MESSAGE_PUMP_DEFAULT scoped_ptr<MessagePump>(new MessagePumpDefault())
240 if (type
== MessageLoop::TYPE_UI
) {
241 if (message_pump_for_ui_factory_
)
242 return message_pump_for_ui_factory_();
243 return MESSAGE_PUMP_UI
;
245 if (type
== MessageLoop::TYPE_IO
)
246 return scoped_ptr
<MessagePump
>(new MessagePumpForIO());
248 #if defined(OS_ANDROID)
249 if (type
== MessageLoop::TYPE_JAVA
)
250 return scoped_ptr
<MessagePump
>(new MessagePumpForUI());
253 DCHECK_EQ(MessageLoop::TYPE_DEFAULT
, type
);
254 return MESSAGE_PUMP_DEFAULT
;
257 void MessageLoop::AddDestructionObserver(
258 DestructionObserver
* destruction_observer
) {
259 DCHECK_EQ(this, current());
260 destruction_observers_
.AddObserver(destruction_observer
);
263 void MessageLoop::RemoveDestructionObserver(
264 DestructionObserver
* destruction_observer
) {
265 DCHECK_EQ(this, current());
266 destruction_observers_
.RemoveObserver(destruction_observer
);
269 void MessageLoop::PostTask(
270 const tracked_objects::Location
& from_here
,
271 const Closure
& task
) {
272 DCHECK(!task
.is_null()) << from_here
.ToString();
273 incoming_task_queue_
->AddToIncomingQueue(from_here
, task
, TimeDelta(), true);
276 void MessageLoop::PostDelayedTask(
277 const tracked_objects::Location
& from_here
,
280 DCHECK(!task
.is_null()) << from_here
.ToString();
281 incoming_task_queue_
->AddToIncomingQueue(from_here
, task
, delay
, true);
284 void MessageLoop::PostNonNestableTask(
285 const tracked_objects::Location
& from_here
,
286 const Closure
& task
) {
287 DCHECK(!task
.is_null()) << from_here
.ToString();
288 incoming_task_queue_
->AddToIncomingQueue(from_here
, task
, TimeDelta(), false);
291 void MessageLoop::PostNonNestableDelayedTask(
292 const tracked_objects::Location
& from_here
,
295 DCHECK(!task
.is_null()) << from_here
.ToString();
296 incoming_task_queue_
->AddToIncomingQueue(from_here
, task
, delay
, false);
299 void MessageLoop::Run() {
304 void MessageLoop::RunUntilIdle() {
306 run_loop
.RunUntilIdle();
309 void MessageLoop::QuitWhenIdle() {
310 DCHECK_EQ(this, current());
312 run_loop_
->quit_when_idle_received_
= true;
314 NOTREACHED() << "Must be inside Run to call Quit";
318 void MessageLoop::QuitNow() {
319 DCHECK_EQ(this, current());
323 NOTREACHED() << "Must be inside Run to call Quit";
327 bool MessageLoop::IsType(Type type
) const {
328 return type_
== type
;
331 static void QuitCurrentWhenIdle() {
332 MessageLoop::current()->QuitWhenIdle();
336 Closure
MessageLoop::QuitWhenIdleClosure() {
337 return Bind(&QuitCurrentWhenIdle
);
340 void MessageLoop::SetNestableTasksAllowed(bool allowed
) {
342 // Kick the native pump just in case we enter a OS-driven nested message
344 pump_
->ScheduleWork();
346 nestable_tasks_allowed_
= allowed
;
349 bool MessageLoop::NestableTasksAllowed() const {
350 return nestable_tasks_allowed_
;
353 bool MessageLoop::IsNested() {
354 return run_loop_
->run_depth_
> 1;
357 void MessageLoop::AddTaskObserver(TaskObserver
* task_observer
) {
358 DCHECK_EQ(this, current());
359 task_observers_
.AddObserver(task_observer
);
362 void MessageLoop::RemoveTaskObserver(TaskObserver
* task_observer
) {
363 DCHECK_EQ(this, current());
364 task_observers_
.RemoveObserver(task_observer
);
367 bool MessageLoop::is_running() const {
368 DCHECK_EQ(this, current());
369 return run_loop_
!= NULL
;
372 bool MessageLoop::IsHighResolutionTimerEnabledForTesting() {
373 return incoming_task_queue_
->IsHighResolutionTimerEnabledForTesting();
376 bool MessageLoop::IsIdleForTesting() {
377 // We only check the imcoming queue|, since we don't want to lock the work
379 return incoming_task_queue_
->IsIdleForTesting();
382 //------------------------------------------------------------------------------
384 void MessageLoop::Init() {
385 DCHECK(!current()) << "should only have one message loop per thread";
386 lazy_tls_ptr
.Pointer()->Set(this);
388 incoming_task_queue_
= new internal::IncomingTaskQueue(this);
389 message_loop_proxy_
=
390 new internal::MessageLoopProxyImpl(incoming_task_queue_
);
391 thread_task_runner_handle_
.reset(
392 new ThreadTaskRunnerHandle(message_loop_proxy_
));
395 void MessageLoop::RunHandler() {
396 DCHECK_EQ(this, current());
401 if (run_loop_
->dispatcher_
&& type() == TYPE_UI
) {
402 static_cast<MessagePumpForUI
*>(pump_
.get())->
403 RunWithDispatcher(this, run_loop_
->dispatcher_
);
411 bool MessageLoop::ProcessNextDelayedNonNestableTask() {
412 if (run_loop_
->run_depth_
!= 1)
415 if (deferred_non_nestable_work_queue_
.empty())
418 PendingTask pending_task
= deferred_non_nestable_work_queue_
.front();
419 deferred_non_nestable_work_queue_
.pop();
421 RunTask(pending_task
);
425 void MessageLoop::RunTask(const PendingTask
& pending_task
) {
426 DCHECK(nestable_tasks_allowed_
);
428 // Execute the task and assume the worst: It is probably not reentrant.
429 nestable_tasks_allowed_
= false;
431 HistogramEvent(kTaskRunEvent
);
433 FOR_EACH_OBSERVER(TaskObserver
, task_observers_
,
434 WillProcessTask(pending_task
));
435 task_annotator_
.RunTask(
436 "MessageLoop::PostTask", "MessageLoop::RunTask", pending_task
);
437 FOR_EACH_OBSERVER(TaskObserver
, task_observers_
,
438 DidProcessTask(pending_task
));
440 nestable_tasks_allowed_
= true;
443 bool MessageLoop::DeferOrRunPendingTask(const PendingTask
& pending_task
) {
444 if (pending_task
.nestable
|| run_loop_
->run_depth_
== 1) {
445 RunTask(pending_task
);
446 // Show that we ran a task (Note: a new one might arrive as a
451 // We couldn't run the task now because we're in a nested message loop
452 // and the task isn't nestable.
453 deferred_non_nestable_work_queue_
.push(pending_task
);
457 void MessageLoop::AddToDelayedWorkQueue(const PendingTask
& pending_task
) {
458 // Move to the delayed work queue.
459 delayed_work_queue_
.push(pending_task
);
462 bool MessageLoop::DeletePendingTasks() {
463 bool did_work
= !work_queue_
.empty();
464 while (!work_queue_
.empty()) {
465 PendingTask pending_task
= work_queue_
.front();
467 if (!pending_task
.delayed_run_time
.is_null()) {
468 // We want to delete delayed tasks in the same order in which they would
469 // normally be deleted in case of any funny dependencies between delayed
471 AddToDelayedWorkQueue(pending_task
);
474 did_work
|= !deferred_non_nestable_work_queue_
.empty();
475 while (!deferred_non_nestable_work_queue_
.empty()) {
476 deferred_non_nestable_work_queue_
.pop();
478 did_work
|= !delayed_work_queue_
.empty();
480 // Historically, we always delete the task regardless of valgrind status. It's
481 // not completely clear why we want to leak them in the loops above. This
482 // code is replicating legacy behavior, and should not be considered
483 // absolutely "correct" behavior. See TODO above about deleting all tasks
485 while (!delayed_work_queue_
.empty()) {
486 delayed_work_queue_
.pop();
491 void MessageLoop::ReloadWorkQueue() {
492 // We can improve performance of our loading tasks from the incoming queue to
493 // |*work_queue| by waiting until the last minute (|*work_queue| is empty) to
494 // load. That reduces the number of locks-per-task significantly when our
496 if (work_queue_
.empty())
497 incoming_task_queue_
->ReloadWorkQueue(&work_queue_
);
500 void MessageLoop::ScheduleWork(bool was_empty
) {
501 if (was_empty
|| AlwaysNotifyPump(type_
))
502 pump_
->ScheduleWork();
505 //------------------------------------------------------------------------------
506 // Method and data for histogramming events and actions taken by each instance
509 void MessageLoop::StartHistogrammer() {
510 #if !defined(OS_NACL) // NaCl build has no metrics code.
511 if (enable_histogrammer_
&& !message_histogram_
512 && StatisticsRecorder::IsActive()) {
513 DCHECK(!thread_name_
.empty());
514 message_histogram_
= LinearHistogram::FactoryGetWithRangeDescription(
515 "MsgLoop:" + thread_name_
,
516 kLeastNonZeroMessageId
, kMaxMessageId
,
517 kNumberOfDistinctMessagesDisplayed
,
518 message_histogram_
->kHexRangePrintingFlag
,
519 event_descriptions_
);
524 void MessageLoop::HistogramEvent(int event
) {
525 #if !defined(OS_NACL)
526 if (message_histogram_
)
527 message_histogram_
->Add(event
);
531 bool MessageLoop::DoWork() {
532 if (!nestable_tasks_allowed_
) {
533 // Task can't be executed right now.
539 if (work_queue_
.empty())
542 // Execute oldest task.
544 PendingTask pending_task
= work_queue_
.front();
546 if (!pending_task
.delayed_run_time
.is_null()) {
547 AddToDelayedWorkQueue(pending_task
);
548 // If we changed the topmost task, then it is time to reschedule.
549 if (delayed_work_queue_
.top().task
.Equals(pending_task
.task
))
550 pump_
->ScheduleDelayedWork(pending_task
.delayed_run_time
);
552 if (DeferOrRunPendingTask(pending_task
))
555 } while (!work_queue_
.empty());
562 bool MessageLoop::DoDelayedWork(TimeTicks
* next_delayed_work_time
) {
563 if (!nestable_tasks_allowed_
|| delayed_work_queue_
.empty()) {
564 recent_time_
= *next_delayed_work_time
= TimeTicks();
568 // When we "fall behind," there will be a lot of tasks in the delayed work
569 // queue that are ready to run. To increase efficiency when we fall behind,
570 // we will only call Time::Now() intermittently, and then process all tasks
571 // that are ready to run before calling it again. As a result, the more we
572 // fall behind (and have a lot of ready-to-run delayed tasks), the more
573 // efficient we'll be at handling the tasks.
575 TimeTicks next_run_time
= delayed_work_queue_
.top().delayed_run_time
;
576 if (next_run_time
> recent_time_
) {
577 recent_time_
= TimeTicks::Now(); // Get a better view of Now();
578 if (next_run_time
> recent_time_
) {
579 *next_delayed_work_time
= next_run_time
;
584 PendingTask pending_task
= delayed_work_queue_
.top();
585 delayed_work_queue_
.pop();
587 if (!delayed_work_queue_
.empty())
588 *next_delayed_work_time
= delayed_work_queue_
.top().delayed_run_time
;
590 return DeferOrRunPendingTask(pending_task
);
593 bool MessageLoop::DoIdleWork() {
594 if (ProcessNextDelayedNonNestableTask())
597 if (run_loop_
->quit_when_idle_received_
)
603 void MessageLoop::DeleteSoonInternal(const tracked_objects::Location
& from_here
,
604 void(*deleter
)(const void*),
605 const void* object
) {
606 PostNonNestableTask(from_here
, Bind(deleter
, object
));
609 void MessageLoop::ReleaseSoonInternal(
610 const tracked_objects::Location
& from_here
,
611 void(*releaser
)(const void*),
612 const void* object
) {
613 PostNonNestableTask(from_here
, Bind(releaser
, object
));
616 #if !defined(OS_NACL)
617 //------------------------------------------------------------------------------
620 #if defined(OS_ANDROID)
621 void MessageLoopForUI::Start() {
622 // No Histogram support for UI message loop as it is managed by Java side
623 static_cast<MessagePumpForUI
*>(pump_
.get())->Start(this);
628 void MessageLoopForUI::Attach() {
629 static_cast<MessagePumpUIApplication
*>(pump_
.get())->Attach(this);
633 #if defined(USE_OZONE) || (defined(USE_X11) && !defined(USE_GLIB))
634 bool MessageLoopForUI::WatchFileDescriptor(
637 MessagePumpLibevent::Mode mode
,
638 MessagePumpLibevent::FileDescriptorWatcher
*controller
,
639 MessagePumpLibevent::Watcher
*delegate
) {
640 return static_cast<MessagePumpLibevent
*>(pump_
.get())->WatchFileDescriptor(
649 #endif // !defined(OS_NACL)
651 //------------------------------------------------------------------------------
654 #if !defined(OS_NACL)
655 void MessageLoopForIO::AddIOObserver(
656 MessageLoopForIO::IOObserver
* io_observer
) {
657 ToPumpIO(pump_
.get())->AddIOObserver(io_observer
);
660 void MessageLoopForIO::RemoveIOObserver(
661 MessageLoopForIO::IOObserver
* io_observer
) {
662 ToPumpIO(pump_
.get())->RemoveIOObserver(io_observer
);
666 void MessageLoopForIO::RegisterIOHandler(HANDLE file
, IOHandler
* handler
) {
667 ToPumpIO(pump_
.get())->RegisterIOHandler(file
, handler
);
670 bool MessageLoopForIO::RegisterJobObject(HANDLE job
, IOHandler
* handler
) {
671 return ToPumpIO(pump_
.get())->RegisterJobObject(job
, handler
);
674 bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout
, IOHandler
* filter
) {
675 return ToPumpIO(pump_
.get())->WaitForIOCompletion(timeout
, filter
);
677 #elif defined(OS_POSIX)
678 bool MessageLoopForIO::WatchFileDescriptor(int fd
,
681 FileDescriptorWatcher
*controller
,
683 return ToPumpIO(pump_
.get())->WatchFileDescriptor(
692 #endif // !defined(OS_NACL)