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
;
90 typedef MessagePumpIOSForIO MessagePumpForIO
;
91 #elif defined(OS_NACL_SFI)
92 typedef MessagePumpDefault MessagePumpForIO
;
93 #elif defined(OS_POSIX)
94 typedef MessagePumpLibevent MessagePumpForIO
;
97 #if !defined(OS_NACL_SFI)
98 MessagePumpForIO
* ToPumpIO(MessagePump
* pump
) {
99 return static_cast<MessagePumpForIO
*>(pump
);
101 #endif // !defined(OS_NACL_SFI)
103 scoped_ptr
<MessagePump
> ReturnPump(scoped_ptr
<MessagePump
> pump
) {
109 //------------------------------------------------------------------------------
111 MessageLoop::TaskObserver::TaskObserver() {
114 MessageLoop::TaskObserver::~TaskObserver() {
117 MessageLoop::DestructionObserver::~DestructionObserver() {
120 //------------------------------------------------------------------------------
122 MessageLoop::MessageLoop(Type type
)
123 : MessageLoop(type
, MessagePumpFactoryCallback()) {
124 BindToCurrentThread();
127 MessageLoop::MessageLoop(scoped_ptr
<MessagePump
> pump
)
128 : MessageLoop(TYPE_CUSTOM
, Bind(&ReturnPump
, Passed(&pump
))) {
129 BindToCurrentThread();
132 MessageLoop::~MessageLoop() {
133 // current() could be NULL if this message loop is destructed before it is
134 // bound to a thread.
135 DCHECK(current() == this || !current());
137 // iOS just attaches to the loop, it doesn't Run it.
138 // TODO(stuartmorgan): Consider wiring up a Detach().
144 if (in_high_res_mode_
)
145 Time::ActivateHighResolutionTimer(false);
147 // Clean up any unprocessed tasks, but take care: deleting a task could
148 // result in the addition of more tasks (e.g., via DeleteSoon). We set a
149 // limit on the number of times we will allow a deleted task to generate more
150 // tasks. Normally, we should only pass through this loop once or twice. If
151 // we end up hitting the loop limit, then it is probably due to one task that
152 // is being stubborn. Inspect the queues to see who is left.
154 for (int i
= 0; i
< 100; ++i
) {
155 DeletePendingTasks();
157 // If we end up with empty queues, then break out of the loop.
158 did_work
= DeletePendingTasks();
164 // Let interested parties have one last shot at accessing this.
165 FOR_EACH_OBSERVER(DestructionObserver
, destruction_observers_
,
166 WillDestroyCurrentMessageLoop());
168 thread_task_runner_handle_
.reset();
170 // Tell the incoming queue that we are dying.
171 incoming_task_queue_
->WillDestroyCurrentMessageLoop();
172 incoming_task_queue_
= NULL
;
175 // OK, now make it so that no one can find us.
176 lazy_tls_ptr
.Pointer()->Set(NULL
);
180 MessageLoop
* MessageLoop::current() {
181 // TODO(darin): sadly, we cannot enable this yet since people call us even
182 // when they have no intention of using us.
183 // DCHECK(loop) << "Ouch, did you forget to initialize me?";
184 return lazy_tls_ptr
.Pointer()->Get();
188 void MessageLoop::EnableHistogrammer(bool enable
) {
189 enable_histogrammer_
= enable
;
193 bool MessageLoop::InitMessagePumpForUIFactory(MessagePumpFactory
* factory
) {
194 if (message_pump_for_ui_factory_
)
197 message_pump_for_ui_factory_
= factory
;
202 scoped_ptr
<MessagePump
> MessageLoop::CreateMessagePumpForType(Type type
) {
203 // TODO(rvargas): Get rid of the OS guards.
204 #if defined(USE_GLIB) && !defined(OS_NACL)
205 typedef MessagePumpGlib MessagePumpForUI
;
206 #elif defined(OS_LINUX) && !defined(OS_NACL)
207 typedef MessagePumpLibevent MessagePumpForUI
;
210 #if defined(OS_IOS) || defined(OS_MACOSX)
211 #define MESSAGE_PUMP_UI scoped_ptr<MessagePump>(MessagePumpMac::Create())
212 #elif defined(OS_NACL)
213 // Currently NaCl doesn't have a UI MessageLoop.
214 // TODO(abarth): Figure out if we need this.
215 #define MESSAGE_PUMP_UI scoped_ptr<MessagePump>()
217 #define MESSAGE_PUMP_UI scoped_ptr<MessagePump>(new MessagePumpForUI())
220 #if defined(OS_MACOSX)
221 // Use an OS native runloop on Mac to support timer coalescing.
222 #define MESSAGE_PUMP_DEFAULT \
223 scoped_ptr<MessagePump>(new MessagePumpCFRunLoop())
225 #define MESSAGE_PUMP_DEFAULT scoped_ptr<MessagePump>(new MessagePumpDefault())
228 if (type
== MessageLoop::TYPE_UI
) {
229 if (message_pump_for_ui_factory_
)
230 return message_pump_for_ui_factory_();
231 return MESSAGE_PUMP_UI
;
233 if (type
== MessageLoop::TYPE_IO
)
234 return scoped_ptr
<MessagePump
>(new MessagePumpForIO());
236 #if defined(OS_ANDROID)
237 if (type
== MessageLoop::TYPE_JAVA
)
238 return scoped_ptr
<MessagePump
>(new MessagePumpForUI());
241 DCHECK_EQ(MessageLoop::TYPE_DEFAULT
, type
);
242 return MESSAGE_PUMP_DEFAULT
;
245 void MessageLoop::AddDestructionObserver(
246 DestructionObserver
* destruction_observer
) {
247 DCHECK_EQ(this, current());
248 destruction_observers_
.AddObserver(destruction_observer
);
251 void MessageLoop::RemoveDestructionObserver(
252 DestructionObserver
* destruction_observer
) {
253 DCHECK_EQ(this, current());
254 destruction_observers_
.RemoveObserver(destruction_observer
);
257 void MessageLoop::PostTask(
258 const tracked_objects::Location
& from_here
,
259 const Closure
& task
) {
260 task_runner_
->PostTask(from_here
, task
);
263 void MessageLoop::PostDelayedTask(
264 const tracked_objects::Location
& from_here
,
267 task_runner_
->PostDelayedTask(from_here
, task
, delay
);
270 void MessageLoop::PostNonNestableTask(
271 const tracked_objects::Location
& from_here
,
272 const Closure
& task
) {
273 task_runner_
->PostNonNestableTask(from_here
, task
);
276 void MessageLoop::PostNonNestableDelayedTask(
277 const tracked_objects::Location
& from_here
,
280 task_runner_
->PostNonNestableDelayedTask(from_here
, task
, delay
);
283 void MessageLoop::Run() {
289 void MessageLoop::RunUntilIdle() {
292 run_loop
.RunUntilIdle();
295 void MessageLoop::QuitWhenIdle() {
296 DCHECK_EQ(this, current());
298 run_loop_
->quit_when_idle_received_
= true;
300 NOTREACHED() << "Must be inside Run to call Quit";
304 void MessageLoop::QuitNow() {
305 DCHECK_EQ(this, current());
309 NOTREACHED() << "Must be inside Run to call Quit";
313 bool MessageLoop::IsType(Type type
) const {
314 return type_
== type
;
317 static void QuitCurrentWhenIdle() {
318 MessageLoop::current()->QuitWhenIdle();
322 Closure
MessageLoop::QuitWhenIdleClosure() {
323 return Bind(&QuitCurrentWhenIdle
);
326 void MessageLoop::SetNestableTasksAllowed(bool allowed
) {
328 // Kick the native pump just in case we enter a OS-driven nested message
330 pump_
->ScheduleWork();
332 nestable_tasks_allowed_
= allowed
;
335 bool MessageLoop::NestableTasksAllowed() const {
336 return nestable_tasks_allowed_
;
339 bool MessageLoop::IsNested() {
340 return run_loop_
->run_depth_
> 1;
343 void MessageLoop::AddTaskObserver(TaskObserver
* task_observer
) {
344 DCHECK_EQ(this, current());
345 task_observers_
.AddObserver(task_observer
);
348 void MessageLoop::RemoveTaskObserver(TaskObserver
* task_observer
) {
349 DCHECK_EQ(this, current());
350 task_observers_
.RemoveObserver(task_observer
);
353 bool MessageLoop::is_running() const {
354 DCHECK_EQ(this, current());
355 return run_loop_
!= NULL
;
358 bool MessageLoop::HasHighResolutionTasks() {
359 return incoming_task_queue_
->HasHighResolutionTasks();
362 bool MessageLoop::IsIdleForTesting() {
363 // We only check the imcoming queue|, since we don't want to lock the work
365 return incoming_task_queue_
->IsIdleForTesting();
368 //------------------------------------------------------------------------------
370 scoped_ptr
<MessageLoop
> MessageLoop::CreateUnbound(
371 Type type
, MessagePumpFactoryCallback pump_factory
) {
372 return make_scoped_ptr(new MessageLoop(type
, pump_factory
));
375 MessageLoop::MessageLoop(Type type
, MessagePumpFactoryCallback pump_factory
)
378 pending_high_res_tasks_(0),
379 in_high_res_mode_(false),
381 nestable_tasks_allowed_(true),
383 os_modal_loop_(false),
385 pump_factory_(pump_factory
),
386 message_histogram_(NULL
),
388 incoming_task_queue_(new internal::IncomingTaskQueue(this)),
389 task_runner_(new internal::MessageLoopTaskRunner(incoming_task_queue_
)) {
390 // If type is TYPE_CUSTOM non-null pump_factory must be given.
391 DCHECK_EQ(type_
== TYPE_CUSTOM
, !pump_factory_
.is_null());
394 void MessageLoop::BindToCurrentThread() {
396 if (!pump_factory_
.is_null())
397 pump_
= pump_factory_
.Run();
399 pump_
= CreateMessagePumpForType(type_
);
401 DCHECK(!current()) << "should only have one message loop per thread";
402 lazy_tls_ptr
.Pointer()->Set(this);
404 incoming_task_queue_
->StartScheduling();
405 task_runner_
->BindToCurrentThread();
406 thread_task_runner_handle_
.reset(new ThreadTaskRunnerHandle(task_runner_
));
409 void MessageLoop::RunHandler() {
410 DCHECK_EQ(this, current());
415 if (run_loop_
->dispatcher_
&& type() == TYPE_UI
) {
416 static_cast<MessagePumpForUI
*>(pump_
.get())->
417 RunWithDispatcher(this, run_loop_
->dispatcher_
);
425 bool MessageLoop::ProcessNextDelayedNonNestableTask() {
426 if (run_loop_
->run_depth_
!= 1)
429 if (deferred_non_nestable_work_queue_
.empty())
432 PendingTask pending_task
= deferred_non_nestable_work_queue_
.front();
433 deferred_non_nestable_work_queue_
.pop();
435 RunTask(pending_task
);
439 void MessageLoop::RunTask(const PendingTask
& pending_task
) {
440 DCHECK(nestable_tasks_allowed_
);
443 if (pending_task
.is_high_res
) {
444 pending_high_res_tasks_
--;
445 CHECK_GE(pending_high_res_tasks_
, 0);
449 // Execute the task and assume the worst: It is probably not reentrant.
450 nestable_tasks_allowed_
= false;
452 HistogramEvent(kTaskRunEvent
);
454 FOR_EACH_OBSERVER(TaskObserver
, task_observers_
,
455 WillProcessTask(pending_task
));
456 task_annotator_
.RunTask(
457 "MessageLoop::PostTask", "MessageLoop::RunTask", pending_task
);
458 FOR_EACH_OBSERVER(TaskObserver
, task_observers_
,
459 DidProcessTask(pending_task
));
461 nestable_tasks_allowed_
= true;
464 bool MessageLoop::DeferOrRunPendingTask(const PendingTask
& pending_task
) {
465 if (pending_task
.nestable
|| run_loop_
->run_depth_
== 1) {
466 RunTask(pending_task
);
467 // Show that we ran a task (Note: a new one might arrive as a
472 // We couldn't run the task now because we're in a nested message loop
473 // and the task isn't nestable.
474 deferred_non_nestable_work_queue_
.push(pending_task
);
478 void MessageLoop::AddToDelayedWorkQueue(const PendingTask
& pending_task
) {
479 // Move to the delayed work queue.
480 delayed_work_queue_
.push(pending_task
);
483 bool MessageLoop::DeletePendingTasks() {
484 bool did_work
= !work_queue_
.empty();
485 while (!work_queue_
.empty()) {
486 PendingTask pending_task
= work_queue_
.front();
488 if (!pending_task
.delayed_run_time
.is_null()) {
489 // We want to delete delayed tasks in the same order in which they would
490 // normally be deleted in case of any funny dependencies between delayed
492 AddToDelayedWorkQueue(pending_task
);
495 did_work
|= !deferred_non_nestable_work_queue_
.empty();
496 while (!deferred_non_nestable_work_queue_
.empty()) {
497 deferred_non_nestable_work_queue_
.pop();
499 did_work
|= !delayed_work_queue_
.empty();
501 // Historically, we always delete the task regardless of valgrind status. It's
502 // not completely clear why we want to leak them in the loops above. This
503 // code is replicating legacy behavior, and should not be considered
504 // absolutely "correct" behavior. See TODO above about deleting all tasks
506 while (!delayed_work_queue_
.empty()) {
507 delayed_work_queue_
.pop();
512 void MessageLoop::ReloadWorkQueue() {
513 // We can improve performance of our loading tasks from the incoming queue to
514 // |*work_queue| by waiting until the last minute (|*work_queue| is empty) to
515 // load. That reduces the number of locks-per-task significantly when our
517 if (work_queue_
.empty()) {
519 pending_high_res_tasks_
+=
520 incoming_task_queue_
->ReloadWorkQueue(&work_queue_
);
522 incoming_task_queue_
->ReloadWorkQueue(&work_queue_
);
527 void MessageLoop::ScheduleWork() {
528 pump_
->ScheduleWork();
531 //------------------------------------------------------------------------------
532 // Method and data for histogramming events and actions taken by each instance
535 void MessageLoop::StartHistogrammer() {
536 #if !defined(OS_NACL) // NaCl build has no metrics code.
537 if (enable_histogrammer_
&& !message_histogram_
538 && StatisticsRecorder::IsActive()) {
539 DCHECK(!thread_name_
.empty());
540 message_histogram_
= LinearHistogram::FactoryGetWithRangeDescription(
541 "MsgLoop:" + thread_name_
,
542 kLeastNonZeroMessageId
, kMaxMessageId
,
543 kNumberOfDistinctMessagesDisplayed
,
544 message_histogram_
->kHexRangePrintingFlag
,
545 event_descriptions_
);
550 void MessageLoop::HistogramEvent(int event
) {
551 #if !defined(OS_NACL)
552 if (message_histogram_
)
553 message_histogram_
->Add(event
);
557 bool MessageLoop::DoWork() {
558 if (!nestable_tasks_allowed_
) {
559 // Task can't be executed right now.
565 if (work_queue_
.empty())
568 // Execute oldest task.
570 PendingTask pending_task
= work_queue_
.front();
572 if (!pending_task
.delayed_run_time
.is_null()) {
573 AddToDelayedWorkQueue(pending_task
);
574 // If we changed the topmost task, then it is time to reschedule.
575 if (delayed_work_queue_
.top().task
.Equals(pending_task
.task
))
576 pump_
->ScheduleDelayedWork(pending_task
.delayed_run_time
);
578 if (DeferOrRunPendingTask(pending_task
))
581 } while (!work_queue_
.empty());
588 bool MessageLoop::DoDelayedWork(TimeTicks
* next_delayed_work_time
) {
589 if (!nestable_tasks_allowed_
|| delayed_work_queue_
.empty()) {
590 recent_time_
= *next_delayed_work_time
= TimeTicks();
594 // When we "fall behind," there will be a lot of tasks in the delayed work
595 // queue that are ready to run. To increase efficiency when we fall behind,
596 // we will only call Time::Now() intermittently, and then process all tasks
597 // that are ready to run before calling it again. As a result, the more we
598 // fall behind (and have a lot of ready-to-run delayed tasks), the more
599 // efficient we'll be at handling the tasks.
601 TimeTicks next_run_time
= delayed_work_queue_
.top().delayed_run_time
;
602 if (next_run_time
> recent_time_
) {
603 recent_time_
= TimeTicks::Now(); // Get a better view of Now();
604 if (next_run_time
> recent_time_
) {
605 *next_delayed_work_time
= next_run_time
;
610 PendingTask pending_task
= delayed_work_queue_
.top();
611 delayed_work_queue_
.pop();
613 if (!delayed_work_queue_
.empty())
614 *next_delayed_work_time
= delayed_work_queue_
.top().delayed_run_time
;
616 return DeferOrRunPendingTask(pending_task
);
619 bool MessageLoop::DoIdleWork() {
620 if (ProcessNextDelayedNonNestableTask())
623 if (run_loop_
->quit_when_idle_received_
)
626 // When we return we will do a kernel wait for more tasks.
628 // On Windows we activate the high resolution timer so that the wait
629 // _if_ triggered by the timer happens with good resolution. If we don't
630 // do this the default resolution is 15ms which might not be acceptable
632 bool high_res
= pending_high_res_tasks_
> 0;
633 if (high_res
!= in_high_res_mode_
) {
634 in_high_res_mode_
= high_res
;
635 Time::ActivateHighResolutionTimer(in_high_res_mode_
);
641 void MessageLoop::DeleteSoonInternal(const tracked_objects::Location
& from_here
,
642 void(*deleter
)(const void*),
643 const void* object
) {
644 PostNonNestableTask(from_here
, Bind(deleter
, object
));
647 void MessageLoop::ReleaseSoonInternal(
648 const tracked_objects::Location
& from_here
,
649 void(*releaser
)(const void*),
650 const void* object
) {
651 PostNonNestableTask(from_here
, Bind(releaser
, object
));
654 #if !defined(OS_NACL)
655 //------------------------------------------------------------------------------
658 #if defined(OS_ANDROID)
659 void MessageLoopForUI::Start() {
660 // No Histogram support for UI message loop as it is managed by Java side
661 static_cast<MessagePumpForUI
*>(pump_
.get())->Start(this);
666 void MessageLoopForUI::Attach() {
667 static_cast<MessagePumpUIApplication
*>(pump_
.get())->Attach(this);
671 #if defined(USE_OZONE) || (defined(USE_X11) && !defined(USE_GLIB))
672 bool MessageLoopForUI::WatchFileDescriptor(
675 MessagePumpLibevent::Mode mode
,
676 MessagePumpLibevent::FileDescriptorWatcher
*controller
,
677 MessagePumpLibevent::Watcher
*delegate
) {
678 return static_cast<MessagePumpLibevent
*>(pump_
.get())->WatchFileDescriptor(
687 #endif // !defined(OS_NACL)
689 //------------------------------------------------------------------------------
692 #if !defined(OS_NACL_SFI)
693 void MessageLoopForIO::AddIOObserver(
694 MessageLoopForIO::IOObserver
* io_observer
) {
695 ToPumpIO(pump_
.get())->AddIOObserver(io_observer
);
698 void MessageLoopForIO::RemoveIOObserver(
699 MessageLoopForIO::IOObserver
* io_observer
) {
700 ToPumpIO(pump_
.get())->RemoveIOObserver(io_observer
);
704 void MessageLoopForIO::RegisterIOHandler(HANDLE file
, IOHandler
* handler
) {
705 ToPumpIO(pump_
.get())->RegisterIOHandler(file
, handler
);
708 bool MessageLoopForIO::RegisterJobObject(HANDLE job
, IOHandler
* handler
) {
709 return ToPumpIO(pump_
.get())->RegisterJobObject(job
, handler
);
712 bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout
, IOHandler
* filter
) {
713 return ToPumpIO(pump_
.get())->WaitForIOCompletion(timeout
, filter
);
715 #elif defined(OS_POSIX)
716 bool MessageLoopForIO::WatchFileDescriptor(int fd
,
719 FileDescriptorWatcher
* controller
,
721 return ToPumpIO(pump_
.get())->WatchFileDescriptor(
730 #endif // !defined(OS_NACL_SFI)