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
;
173 message_loop_proxy_
= 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 message_loop_proxy_
->PostTask(from_here
, task
);
263 void MessageLoop::PostDelayedTask(
264 const tracked_objects::Location
& from_here
,
267 message_loop_proxy_
->PostDelayedTask(from_here
, task
, delay
);
270 void MessageLoop::PostNonNestableTask(
271 const tracked_objects::Location
& from_here
,
272 const Closure
& task
) {
273 message_loop_proxy_
->PostNonNestableTask(from_here
, task
);
276 void MessageLoop::PostNonNestableDelayedTask(
277 const tracked_objects::Location
& from_here
,
280 message_loop_proxy_
->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)),
390 new internal::MessageLoopProxyImpl(incoming_task_queue_
)) {
391 // If type is TYPE_CUSTOM non-null pump_factory must be given.
392 DCHECK_EQ(type_
== TYPE_CUSTOM
, !pump_factory_
.is_null());
395 void MessageLoop::BindToCurrentThread() {
397 if (!pump_factory_
.is_null())
398 pump_
= pump_factory_
.Run();
400 pump_
= CreateMessagePumpForType(type_
);
402 DCHECK(!current()) << "should only have one message loop per thread";
403 lazy_tls_ptr
.Pointer()->Set(this);
405 incoming_task_queue_
->StartScheduling();
406 message_loop_proxy_
->BindToCurrentThread();
407 thread_task_runner_handle_
.reset(
408 new ThreadTaskRunnerHandle(message_loop_proxy_
));
411 void MessageLoop::RunHandler() {
412 DCHECK_EQ(this, current());
417 if (run_loop_
->dispatcher_
&& type() == TYPE_UI
) {
418 static_cast<MessagePumpForUI
*>(pump_
.get())->
419 RunWithDispatcher(this, run_loop_
->dispatcher_
);
427 bool MessageLoop::ProcessNextDelayedNonNestableTask() {
428 if (run_loop_
->run_depth_
!= 1)
431 if (deferred_non_nestable_work_queue_
.empty())
434 PendingTask pending_task
= deferred_non_nestable_work_queue_
.front();
435 deferred_non_nestable_work_queue_
.pop();
437 RunTask(pending_task
);
441 void MessageLoop::RunTask(const PendingTask
& pending_task
) {
442 DCHECK(nestable_tasks_allowed_
);
445 if (pending_task
.is_high_res
) {
446 pending_high_res_tasks_
--;
447 CHECK_GE(pending_high_res_tasks_
, 0);
451 // Execute the task and assume the worst: It is probably not reentrant.
452 nestable_tasks_allowed_
= false;
454 HistogramEvent(kTaskRunEvent
);
456 FOR_EACH_OBSERVER(TaskObserver
, task_observers_
,
457 WillProcessTask(pending_task
));
458 task_annotator_
.RunTask(
459 "MessageLoop::PostTask", "MessageLoop::RunTask", pending_task
);
460 FOR_EACH_OBSERVER(TaskObserver
, task_observers_
,
461 DidProcessTask(pending_task
));
463 nestable_tasks_allowed_
= true;
466 bool MessageLoop::DeferOrRunPendingTask(const PendingTask
& pending_task
) {
467 if (pending_task
.nestable
|| run_loop_
->run_depth_
== 1) {
468 RunTask(pending_task
);
469 // Show that we ran a task (Note: a new one might arrive as a
474 // We couldn't run the task now because we're in a nested message loop
475 // and the task isn't nestable.
476 deferred_non_nestable_work_queue_
.push(pending_task
);
480 void MessageLoop::AddToDelayedWorkQueue(const PendingTask
& pending_task
) {
481 // Move to the delayed work queue.
482 delayed_work_queue_
.push(pending_task
);
485 bool MessageLoop::DeletePendingTasks() {
486 bool did_work
= !work_queue_
.empty();
487 while (!work_queue_
.empty()) {
488 PendingTask pending_task
= work_queue_
.front();
490 if (!pending_task
.delayed_run_time
.is_null()) {
491 // We want to delete delayed tasks in the same order in which they would
492 // normally be deleted in case of any funny dependencies between delayed
494 AddToDelayedWorkQueue(pending_task
);
497 did_work
|= !deferred_non_nestable_work_queue_
.empty();
498 while (!deferred_non_nestable_work_queue_
.empty()) {
499 deferred_non_nestable_work_queue_
.pop();
501 did_work
|= !delayed_work_queue_
.empty();
503 // Historically, we always delete the task regardless of valgrind status. It's
504 // not completely clear why we want to leak them in the loops above. This
505 // code is replicating legacy behavior, and should not be considered
506 // absolutely "correct" behavior. See TODO above about deleting all tasks
508 while (!delayed_work_queue_
.empty()) {
509 delayed_work_queue_
.pop();
514 void MessageLoop::ReloadWorkQueue() {
515 // We can improve performance of our loading tasks from the incoming queue to
516 // |*work_queue| by waiting until the last minute (|*work_queue| is empty) to
517 // load. That reduces the number of locks-per-task significantly when our
519 if (work_queue_
.empty()) {
521 pending_high_res_tasks_
+=
522 incoming_task_queue_
->ReloadWorkQueue(&work_queue_
);
524 incoming_task_queue_
->ReloadWorkQueue(&work_queue_
);
529 void MessageLoop::ScheduleWork() {
530 pump_
->ScheduleWork();
533 //------------------------------------------------------------------------------
534 // Method and data for histogramming events and actions taken by each instance
537 void MessageLoop::StartHistogrammer() {
538 #if !defined(OS_NACL) // NaCl build has no metrics code.
539 if (enable_histogrammer_
&& !message_histogram_
540 && StatisticsRecorder::IsActive()) {
541 DCHECK(!thread_name_
.empty());
542 message_histogram_
= LinearHistogram::FactoryGetWithRangeDescription(
543 "MsgLoop:" + thread_name_
,
544 kLeastNonZeroMessageId
, kMaxMessageId
,
545 kNumberOfDistinctMessagesDisplayed
,
546 message_histogram_
->kHexRangePrintingFlag
,
547 event_descriptions_
);
552 void MessageLoop::HistogramEvent(int event
) {
553 #if !defined(OS_NACL)
554 if (message_histogram_
)
555 message_histogram_
->Add(event
);
559 bool MessageLoop::DoWork() {
560 if (!nestable_tasks_allowed_
) {
561 // Task can't be executed right now.
567 if (work_queue_
.empty())
570 // Execute oldest task.
572 PendingTask pending_task
= work_queue_
.front();
574 if (!pending_task
.delayed_run_time
.is_null()) {
575 AddToDelayedWorkQueue(pending_task
);
576 // If we changed the topmost task, then it is time to reschedule.
577 if (delayed_work_queue_
.top().task
.Equals(pending_task
.task
))
578 pump_
->ScheduleDelayedWork(pending_task
.delayed_run_time
);
580 if (DeferOrRunPendingTask(pending_task
))
583 } while (!work_queue_
.empty());
590 bool MessageLoop::DoDelayedWork(TimeTicks
* next_delayed_work_time
) {
591 if (!nestable_tasks_allowed_
|| delayed_work_queue_
.empty()) {
592 recent_time_
= *next_delayed_work_time
= TimeTicks();
596 // When we "fall behind," there will be a lot of tasks in the delayed work
597 // queue that are ready to run. To increase efficiency when we fall behind,
598 // we will only call Time::Now() intermittently, and then process all tasks
599 // that are ready to run before calling it again. As a result, the more we
600 // fall behind (and have a lot of ready-to-run delayed tasks), the more
601 // efficient we'll be at handling the tasks.
603 TimeTicks next_run_time
= delayed_work_queue_
.top().delayed_run_time
;
604 if (next_run_time
> recent_time_
) {
605 recent_time_
= TimeTicks::Now(); // Get a better view of Now();
606 if (next_run_time
> recent_time_
) {
607 *next_delayed_work_time
= next_run_time
;
612 PendingTask pending_task
= delayed_work_queue_
.top();
613 delayed_work_queue_
.pop();
615 if (!delayed_work_queue_
.empty())
616 *next_delayed_work_time
= delayed_work_queue_
.top().delayed_run_time
;
618 return DeferOrRunPendingTask(pending_task
);
621 bool MessageLoop::DoIdleWork() {
622 if (ProcessNextDelayedNonNestableTask())
625 if (run_loop_
->quit_when_idle_received_
)
628 // When we return we will do a kernel wait for more tasks.
630 // On Windows we activate the high resolution timer so that the wait
631 // _if_ triggered by the timer happens with good resolution. If we don't
632 // do this the default resolution is 15ms which might not be acceptable
634 bool high_res
= pending_high_res_tasks_
> 0;
635 if (high_res
!= in_high_res_mode_
) {
636 in_high_res_mode_
= high_res
;
637 Time::ActivateHighResolutionTimer(in_high_res_mode_
);
643 void MessageLoop::DeleteSoonInternal(const tracked_objects::Location
& from_here
,
644 void(*deleter
)(const void*),
645 const void* object
) {
646 PostNonNestableTask(from_here
, Bind(deleter
, object
));
649 void MessageLoop::ReleaseSoonInternal(
650 const tracked_objects::Location
& from_here
,
651 void(*releaser
)(const void*),
652 const void* object
) {
653 PostNonNestableTask(from_here
, Bind(releaser
, object
));
656 #if !defined(OS_NACL)
657 //------------------------------------------------------------------------------
660 #if defined(OS_ANDROID)
661 void MessageLoopForUI::Start() {
662 // No Histogram support for UI message loop as it is managed by Java side
663 static_cast<MessagePumpForUI
*>(pump_
.get())->Start(this);
668 void MessageLoopForUI::Attach() {
669 static_cast<MessagePumpUIApplication
*>(pump_
.get())->Attach(this);
673 #if defined(USE_OZONE) || (defined(USE_X11) && !defined(USE_GLIB))
674 bool MessageLoopForUI::WatchFileDescriptor(
677 MessagePumpLibevent::Mode mode
,
678 MessagePumpLibevent::FileDescriptorWatcher
*controller
,
679 MessagePumpLibevent::Watcher
*delegate
) {
680 return static_cast<MessagePumpLibevent
*>(pump_
.get())->WatchFileDescriptor(
689 #endif // !defined(OS_NACL)
691 //------------------------------------------------------------------------------
694 #if !defined(OS_NACL_SFI)
695 void MessageLoopForIO::AddIOObserver(
696 MessageLoopForIO::IOObserver
* io_observer
) {
697 ToPumpIO(pump_
.get())->AddIOObserver(io_observer
);
700 void MessageLoopForIO::RemoveIOObserver(
701 MessageLoopForIO::IOObserver
* io_observer
) {
702 ToPumpIO(pump_
.get())->RemoveIOObserver(io_observer
);
706 void MessageLoopForIO::RegisterIOHandler(HANDLE file
, IOHandler
* handler
) {
707 ToPumpIO(pump_
.get())->RegisterIOHandler(file
, handler
);
710 bool MessageLoopForIO::RegisterJobObject(HANDLE job
, IOHandler
* handler
) {
711 return ToPumpIO(pump_
.get())->RegisterJobObject(job
, handler
);
714 bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout
, IOHandler
* filter
) {
715 return ToPumpIO(pump_
.get())->WaitForIOCompletion(timeout
, filter
);
717 #elif defined(OS_POSIX)
718 bool MessageLoopForIO::WatchFileDescriptor(int fd
,
721 FileDescriptorWatcher
* controller
,
723 return ToPumpIO(pump_
.get())->WatchFileDescriptor(
732 #endif // !defined(OS_NACL_SFI)