blob: 1668fd7a2ec0c4215bddbd6db8e0d0989b58d76d [file] [log] [blame]
thestig@chromium.org7016bac2010-04-15 10:04:29 +09001// Copyright (c) 2010 The Chromium Authors. All rights reserved.
license.botf003cfe2008-08-24 09:55:55 +09002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit3f4a7322008-07-27 06:49:38 +09004
darin@google.com6ddeb842008-08-15 16:31:20 +09005#include "base/message_loop.h"
6
darin@google.com981f3552008-08-16 12:09:05 +09007#include <algorithm>
8
mmentovai@google.comfa5f9932008-08-22 07:26:06 +09009#include "base/compiler_specific.h"
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090010#include "base/lazy_instance.h"
initial.commit3f4a7322008-07-27 06:49:38 +090011#include "base/logging.h"
darin@google.com12d40bb2008-08-20 03:36:23 +090012#include "base/message_pump_default.h"
initial.commit3f4a7322008-07-27 06:49:38 +090013#include "base/string_util.h"
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090014#include "base/thread_local.h"
initial.commit3f4a7322008-07-27 06:49:38 +090015
mark@chromium.org059d0492008-09-24 06:08:28 +090016#if defined(OS_MACOSX)
17#include "base/message_pump_mac.h"
18#endif
dkegel@google.com9e044ae2008-09-19 03:46:26 +090019#if defined(OS_POSIX)
20#include "base/message_pump_libevent.h"
kuchhal@chromium.orge3bd2eb2009-05-15 01:44:26 +090021#include "base/third_party/valgrind/valgrind.h"
dkegel@google.com9e044ae2008-09-19 03:46:26 +090022#endif
evan@chromium.org875bb6e2009-12-29 09:32:52 +090023#if defined(OS_POSIX) && !defined(OS_MACOSX)
dsh@google.com119a2522008-10-04 01:52:59 +090024#include "base/message_pump_glib.h"
25#endif
dkegel@google.com9e044ae2008-09-19 03:46:26 +090026
dsh@google.com0f8dd262008-10-28 05:43:33 +090027using base::Time;
28using base::TimeDelta;
29
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090030// A lazily created thread local storage for quick access to a thread's message
31// loop, if one exists. This should be safe and free of static constructors.
erg@chromium.org6f206e72010-07-15 03:58:17 +090032static base::LazyInstance<base::ThreadLocalPointer<MessageLoop> > lazy_tls_ptr(
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090033 base::LINKER_INITIALIZED);
initial.commit3f4a7322008-07-27 06:49:38 +090034
erg@chromium.org6f206e72010-07-15 03:58:17 +090035//------------------------------------------------------------------------------
36
initial.commit3f4a7322008-07-27 06:49:38 +090037// Logical events for Histogram profiling. Run with -message-loop-histogrammer
38// to get an accounting of messages and actions taken on each thread.
erg@chromium.org6f206e72010-07-15 03:58:17 +090039static const int kTaskRunEvent = 0x1;
40static const int kTimerEvent = 0x2;
initial.commit3f4a7322008-07-27 06:49:38 +090041
42// Provide range of message IDs for use in histogramming and debug display.
erg@chromium.org6f206e72010-07-15 03:58:17 +090043static const int kLeastNonZeroMessageId = 1;
44static const int kMaxMessageId = 1099;
45static const int kNumberOfDistinctMessagesDisplayed = 1100;
initial.commit3f4a7322008-07-27 06:49:38 +090046
47//------------------------------------------------------------------------------
48
darin@google.com981f3552008-08-16 12:09:05 +090049#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +090050
initial.commit3f4a7322008-07-27 06:49:38 +090051// Upon a SEH exception in this thread, it restores the original unhandled
52// exception filter.
53static int SEHFilter(LPTOP_LEVEL_EXCEPTION_FILTER old_filter) {
54 ::SetUnhandledExceptionFilter(old_filter);
55 return EXCEPTION_CONTINUE_SEARCH;
56}
57
58// Retrieves a pointer to the current unhandled exception filter. There
59// is no standalone getter method.
60static LPTOP_LEVEL_EXCEPTION_FILTER GetTopSEHFilter() {
61 LPTOP_LEVEL_EXCEPTION_FILTER top_filter = NULL;
62 top_filter = ::SetUnhandledExceptionFilter(0);
63 ::SetUnhandledExceptionFilter(top_filter);
64 return top_filter;
65}
66
darin@google.com981f3552008-08-16 12:09:05 +090067#endif // defined(OS_WIN)
68
initial.commit3f4a7322008-07-27 06:49:38 +090069//------------------------------------------------------------------------------
70
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090071// static
72MessageLoop* MessageLoop::current() {
73 // TODO(darin): sadly, we cannot enable this yet since people call us even
74 // when they have no intention of using us.
erg@google.combf6ce9f2010-01-27 08:08:02 +090075 // DCHECK(loop) << "Ouch, did you forget to initialize me?";
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090076 return lazy_tls_ptr.Pointer()->Get();
77}
78
darin@google.comd936b5b2008-08-26 14:53:57 +090079MessageLoop::MessageLoop(Type type)
80 : type_(type),
darin@google.comee6fa722008-08-13 08:25:43 +090081 nestable_tasks_allowed_(true),
darin@google.com12d40bb2008-08-20 03:36:23 +090082 exception_restoration_(false),
darin@google.combe165ae2008-09-07 17:08:29 +090083 state_(NULL),
84 next_sequence_num_(0) {
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090085 DCHECK(!current()) << "should only have one message loop per thread";
86 lazy_tls_ptr.Pointer()->Set(this);
darin@google.comd936b5b2008-08-26 14:53:57 +090087
thestig@chromium.org7016bac2010-04-15 10:04:29 +090088// TODO(rvargas): Get rid of the OS guards.
darin@google.com981f3552008-08-16 12:09:05 +090089#if defined(OS_WIN)
thestig@chromium.org7016bac2010-04-15 10:04:29 +090090#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
91#define MESSAGE_PUMP_IO new base::MessagePumpForIO()
92#elif defined(OS_MACOSX)
93#define MESSAGE_PUMP_UI base::MessagePumpMac::Create()
94#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
95#elif defined(OS_POSIX) // POSIX but not MACOSX.
96#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
97#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
evan@chromium.org875bb6e2009-12-29 09:32:52 +090098#else
thestig@chromium.org7016bac2010-04-15 10:04:29 +090099#error Not implemented
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900100#endif
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900101
102 if (type_ == TYPE_UI) {
103 pump_ = MESSAGE_PUMP_UI;
dsh@google.com119a2522008-10-04 01:52:59 +0900104 } else if (type_ == TYPE_IO) {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900105 pump_ = MESSAGE_PUMP_IO;
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900106 } else {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900107 DCHECK_EQ(TYPE_DEFAULT, type_);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900108 pump_ = new base::MessagePumpDefault();
109 }
initial.commit3f4a7322008-07-27 06:49:38 +0900110}
111
112MessageLoop::~MessageLoop() {
113 DCHECK(this == current());
darin@google.com965e5342008-08-06 08:16:41 +0900114
115 // Let interested parties have one last shot at accessing this.
116 FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
117 WillDestroyCurrentMessageLoop());
118
darin@google.com0e500502008-09-09 14:55:35 +0900119 DCHECK(!state_);
120
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900121 // Clean up any unprocessed tasks, but take care: deleting a task could
122 // result in the addition of more tasks (e.g., via DeleteSoon). We set a
123 // limit on the number of times we will allow a deleted task to generate more
124 // tasks. Normally, we should only pass through this loop once or twice. If
125 // we end up hitting the loop limit, then it is probably due to one task that
126 // is being stubborn. Inspect the queues to see who is left.
127 bool did_work;
128 for (int i = 0; i < 100; ++i) {
129 DeletePendingTasks();
130 ReloadWorkQueue();
131 // If we end up with empty queues, then break out of the loop.
132 did_work = DeletePendingTasks();
133 if (!did_work)
134 break;
darin@google.com0e500502008-09-09 14:55:35 +0900135 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900136 DCHECK(!did_work);
137
138 // OK, now make it so that no one can find us.
deanm@chromium.orge4cc5922008-09-10 20:14:56 +0900139 lazy_tls_ptr.Pointer()->Set(NULL);
initial.commit3f4a7322008-07-27 06:49:38 +0900140}
141
darin@google.com965e5342008-08-06 08:16:41 +0900142void MessageLoop::AddDestructionObserver(DestructionObserver *obs) {
143 DCHECK(this == current());
144 destruction_observers_.AddObserver(obs);
145}
146
147void MessageLoop::RemoveDestructionObserver(DestructionObserver *obs) {
148 DCHECK(this == current());
149 destruction_observers_.RemoveObserver(obs);
150}
151
willchan@chromium.orga9047632010-06-10 06:20:41 +0900152void MessageLoop::AddTaskObserver(TaskObserver *obs) {
153 DCHECK_EQ(this, current());
154 task_observers_.AddObserver(obs);
155}
156
157void MessageLoop::RemoveTaskObserver(TaskObserver *obs) {
158 DCHECK_EQ(this, current());
159 task_observers_.RemoveObserver(obs);
160}
161
darin@google.com6ddeb842008-08-15 16:31:20 +0900162void MessageLoop::Run() {
darin@google.com981f3552008-08-16 12:09:05 +0900163 AutoRunState save_state(this);
164 RunHandler();
darin@google.com6ddeb842008-08-15 16:31:20 +0900165}
166
jar@google.com9239e022008-07-31 22:10:20 +0900167void MessageLoop::RunAllPending() {
darin@google.com981f3552008-08-16 12:09:05 +0900168 AutoRunState save_state(this);
169 state_->quit_received = true; // Means run until we would otherwise block.
170 RunHandler();
initial.commit3f4a7322008-07-27 06:49:38 +0900171}
172
173// Runs the loop in two different SEH modes:
174// enable_SEH_restoration_ = false : any unhandled exception goes to the last
175// one that calls SetUnhandledExceptionFilter().
176// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
177// that was existed before the loop was run.
darin@google.com981f3552008-08-16 12:09:05 +0900178void MessageLoop::RunHandler() {
179#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +0900180 if (exception_restoration_) {
stoyan@google.com283facb2009-10-27 03:15:59 +0900181 RunInternalInSEHFrame();
darin@google.com981f3552008-08-16 12:09:05 +0900182 return;
initial.commit3f4a7322008-07-27 06:49:38 +0900183 }
darin@google.com981f3552008-08-16 12:09:05 +0900184#endif
185
186 RunInternal();
initial.commit3f4a7322008-07-27 06:49:38 +0900187}
stoyan@google.com283facb2009-10-27 03:15:59 +0900188//------------------------------------------------------------------------------
189#if defined(OS_WIN)
190__declspec(noinline) void MessageLoop::RunInternalInSEHFrame() {
191 LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
192 __try {
193 RunInternal();
194 } __except(SEHFilter(current_filter)) {
195 }
196 return;
197}
198#endif
initial.commit3f4a7322008-07-27 06:49:38 +0900199//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900200
darin@google.com981f3552008-08-16 12:09:05 +0900201void MessageLoop::RunInternal() {
202 DCHECK(this == current());
203
initial.commit3f4a7322008-07-27 06:49:38 +0900204 StartHistogrammer();
205
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900206#if !defined(OS_MACOSX)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900207 if (state_->dispatcher && type() == TYPE_UI) {
208 static_cast<base::MessagePumpForUI*>(pump_.get())->
209 RunWithDispatcher(this, state_->dispatcher);
darin@google.com981f3552008-08-16 12:09:05 +0900210 return;
jar@google.com9239e022008-07-31 22:10:20 +0900211 }
darin@google.com981f3552008-08-16 12:09:05 +0900212#endif
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900213
darin@google.com981f3552008-08-16 12:09:05 +0900214 pump_->Run(this);
jar@google.comfbaaf692008-07-30 16:50:53 +0900215}
jar@google.com7ff36e62008-07-30 15:58:56 +0900216
jar@google.comb4d1bff2008-07-31 04:03:59 +0900217//------------------------------------------------------------------------------
218// Wrapper functions for use in above message loop framework.
219
initial.commit3f4a7322008-07-27 06:49:38 +0900220bool MessageLoop::ProcessNextDelayedNonNestableTask() {
darin@google.com981f3552008-08-16 12:09:05 +0900221 if (state_->run_depth != 1)
initial.commit3f4a7322008-07-27 06:49:38 +0900222 return false;
223
darin@google.combe165ae2008-09-07 17:08:29 +0900224 if (deferred_non_nestable_work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900225 return false;
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900226
darin@google.combe165ae2008-09-07 17:08:29 +0900227 Task* task = deferred_non_nestable_work_queue_.front().task;
228 deferred_non_nestable_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900229
darin@google.combe165ae2008-09-07 17:08:29 +0900230 RunTask(task);
initial.commit3f4a7322008-07-27 06:49:38 +0900231 return true;
232}
233
initial.commit3f4a7322008-07-27 06:49:38 +0900234//------------------------------------------------------------------------------
235
236void MessageLoop::Quit() {
darin@google.com981f3552008-08-16 12:09:05 +0900237 DCHECK(current() == this);
238 if (state_) {
239 state_->quit_received = true;
240 } else {
241 NOTREACHED() << "Must be inside Run to call Quit";
initial.commit3f4a7322008-07-27 06:49:38 +0900242 }
initial.commit3f4a7322008-07-27 06:49:38 +0900243}
244
darin@chromium.orgd70a12c2010-02-23 16:12:22 +0900245void MessageLoop::QuitNow() {
246 DCHECK(current() == this);
247 if (state_) {
248 pump_->Quit();
249 } else {
250 NOTREACHED() << "Must be inside Run to call Quit";
251 }
252}
253
darin@google.combe165ae2008-09-07 17:08:29 +0900254void MessageLoop::PostTask(
255 const tracked_objects::Location& from_here, Task* task) {
256 PostTask_Helper(from_here, task, 0, true);
257}
258
259void MessageLoop::PostDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900260 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
darin@google.combe165ae2008-09-07 17:08:29 +0900261 PostTask_Helper(from_here, task, delay_ms, true);
262}
263
264void MessageLoop::PostNonNestableTask(
265 const tracked_objects::Location& from_here, Task* task) {
266 PostTask_Helper(from_here, task, 0, false);
267}
268
269void MessageLoop::PostNonNestableDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900270 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
darin@google.combe165ae2008-09-07 17:08:29 +0900271 PostTask_Helper(from_here, task, delay_ms, false);
272}
273
initial.commit3f4a7322008-07-27 06:49:38 +0900274// Possibly called on a background thread!
darin@google.combe165ae2008-09-07 17:08:29 +0900275void MessageLoop::PostTask_Helper(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900276 const tracked_objects::Location& from_here, Task* task, int64 delay_ms,
darin@google.combe165ae2008-09-07 17:08:29 +0900277 bool nestable) {
initial.commit3f4a7322008-07-27 06:49:38 +0900278 task->SetBirthPlace(from_here);
darin@google.com0795f572008-08-30 09:22:48 +0900279
darin@google.combe165ae2008-09-07 17:08:29 +0900280 PendingTask pending_task(task, nestable);
darin@google.com0795f572008-08-30 09:22:48 +0900281
282 if (delay_ms > 0) {
darin@google.combe165ae2008-09-07 17:08:29 +0900283 pending_task.delayed_run_time =
darin@google.com0795f572008-08-30 09:22:48 +0900284 Time::Now() + TimeDelta::FromMilliseconds(delay_ms);
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900285
286#if defined(OS_WIN)
287 if (high_resolution_timer_expiration_.is_null()) {
288 // Windows timers are granular to 15.6ms. If we only set high-res
289 // timers for those under 15.6ms, then a 18ms timer ticks at ~32ms,
290 // which as a percentage is pretty inaccurate. So enable high
291 // res timers for any timer which is within 2x of the granularity.
292 // This is a tradeoff between accuracy and power management.
293 bool needs_high_res_timers =
294 delay_ms < (2 * Time::kMinLowResolutionThresholdMs);
295 if (needs_high_res_timers) {
296 Time::ActivateHighResolutionTimer(true);
297 high_resolution_timer_expiration_ = base::TimeTicks::Now() +
298 TimeDelta::FromMilliseconds(kHighResolutionTimerModeLeaseTimeMs);
299 }
300 }
301#endif
darin@google.com0795f572008-08-30 09:22:48 +0900302 } else {
jar@chromium.orged5238a2009-12-28 15:59:52 +0900303 DCHECK_EQ(delay_ms, 0) << "delay should not be negative";
darin@google.com0795f572008-08-30 09:22:48 +0900304 }
305
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900306#if defined(OS_WIN)
307 if (!high_resolution_timer_expiration_.is_null()) {
308 if (base::TimeTicks::Now() > high_resolution_timer_expiration_) {
309 Time::ActivateHighResolutionTimer(false);
310 high_resolution_timer_expiration_ = base::TimeTicks();
311 }
312 }
313#endif
314
initial.commit3f4a7322008-07-27 06:49:38 +0900315 // Warning: Don't try to short-circuit, and handle this thread's tasks more
316 // directly, as it could starve handling of foreign threads. Put every task
317 // into this queue.
318
darin@google.com981f3552008-08-16 12:09:05 +0900319 scoped_refptr<base::MessagePump> pump;
initial.commit3f4a7322008-07-27 06:49:38 +0900320 {
darin@google.com981f3552008-08-16 12:09:05 +0900321 AutoLock locked(incoming_queue_lock_);
322
darin@google.combe165ae2008-09-07 17:08:29 +0900323 bool was_empty = incoming_queue_.empty();
324 incoming_queue_.push(pending_task);
initial.commit3f4a7322008-07-27 06:49:38 +0900325 if (!was_empty)
326 return; // Someone else should have started the sub-pump.
327
darin@google.com981f3552008-08-16 12:09:05 +0900328 pump = pump_;
darin@google.com6ddeb842008-08-15 16:31:20 +0900329 }
darin@google.com981f3552008-08-16 12:09:05 +0900330 // Since the incoming_queue_ may contain a task that destroys this message
331 // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
332 // We use a stack-based reference to the message pump so that we can call
333 // ScheduleWork outside of incoming_queue_lock_.
darin@google.com6ddeb842008-08-15 16:31:20 +0900334
darin@google.com981f3552008-08-16 12:09:05 +0900335 pump->ScheduleWork();
initial.commit3f4a7322008-07-27 06:49:38 +0900336}
337
338void MessageLoop::SetNestableTasksAllowed(bool allowed) {
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900339 if (nestable_tasks_allowed_ != allowed) {
340 nestable_tasks_allowed_ = allowed;
341 if (!nestable_tasks_allowed_)
342 return;
343 // Start the native pump if we are not already pumping.
darin@google.com981f3552008-08-16 12:09:05 +0900344 pump_->ScheduleWork();
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900345 }
initial.commit3f4a7322008-07-27 06:49:38 +0900346}
347
348bool MessageLoop::NestableTasksAllowed() const {
349 return nestable_tasks_allowed_;
350}
351
jcampan@chromium.orgeac57172009-07-02 04:53:59 +0900352bool MessageLoop::IsNested() {
353 return state_->run_depth > 1;
354}
355
initial.commit3f4a7322008-07-27 06:49:38 +0900356//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900357
initial.commit3f4a7322008-07-27 06:49:38 +0900358void MessageLoop::RunTask(Task* task) {
initial.commit3f4a7322008-07-27 06:49:38 +0900359 DCHECK(nestable_tasks_allowed_);
360 // Execute the task and assume the worst: It is probably not reentrant.
361 nestable_tasks_allowed_ = false;
darin@google.combe165ae2008-09-07 17:08:29 +0900362
363 HistogramEvent(kTaskRunEvent);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900364 FOR_EACH_OBSERVER(TaskObserver, task_observers_,
365 WillProcessTask(task->tracked_birth_time()));
darin@google.combe165ae2008-09-07 17:08:29 +0900366 task->Run();
willchan@chromium.orga9047632010-06-10 06:20:41 +0900367 FOR_EACH_OBSERVER(TaskObserver, task_observers_, DidProcessTask());
darin@google.combe165ae2008-09-07 17:08:29 +0900368 delete task;
369
370 nestable_tasks_allowed_ = true;
initial.commit3f4a7322008-07-27 06:49:38 +0900371}
372
darin@google.combe165ae2008-09-07 17:08:29 +0900373bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) {
374 if (pending_task.nestable || state_->run_depth == 1) {
375 RunTask(pending_task.task);
376 // Show that we ran a task (Note: a new one might arrive as a
377 // consequence!).
378 return true;
379 }
380
381 // We couldn't run the task now because we're in a nested message loop
382 // and the task isn't nestable.
383 deferred_non_nestable_work_queue_.push(pending_task);
384 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900385}
386
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900387void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
388 // Move to the delayed work queue. Initialize the sequence number
389 // before inserting into the delayed_work_queue_. The sequence number
390 // is used to faciliate FIFO sorting when two tasks have the same
391 // delayed_run_time value.
392 PendingTask new_pending_task(pending_task);
393 new_pending_task.sequence_num = next_sequence_num_++;
394 delayed_work_queue_.push(new_pending_task);
395}
396
initial.commit3f4a7322008-07-27 06:49:38 +0900397void MessageLoop::ReloadWorkQueue() {
398 // We can improve performance of our loading tasks from incoming_queue_ to
darin@google.com981f3552008-08-16 12:09:05 +0900399 // work_queue_ by waiting until the last minute (work_queue_ is empty) to
400 // load. That reduces the number of locks-per-task significantly when our
darin@google.combe165ae2008-09-07 17:08:29 +0900401 // queues get large.
402 if (!work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900403 return; // Wait till we *really* need to lock and load.
404
405 // Acquire all we can from the inter-thread queue with one lock acquisition.
initial.commit3f4a7322008-07-27 06:49:38 +0900406 {
407 AutoLock lock(incoming_queue_lock_);
darin@google.combe165ae2008-09-07 17:08:29 +0900408 if (incoming_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900409 return;
darin@chromium.orgb80ef1a2009-09-03 05:05:21 +0900410 incoming_queue_.Swap(&work_queue_); // Constant time
darin@google.combe165ae2008-09-07 17:08:29 +0900411 DCHECK(incoming_queue_.empty());
initial.commit3f4a7322008-07-27 06:49:38 +0900412 }
413}
414
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900415bool MessageLoop::DeletePendingTasks() {
416 bool did_work = !work_queue_.empty();
417 while (!work_queue_.empty()) {
418 PendingTask pending_task = work_queue_.front();
419 work_queue_.pop();
420 if (!pending_task.delayed_run_time.is_null()) {
421 // We want to delete delayed tasks in the same order in which they would
422 // normally be deleted in case of any funny dependencies between delayed
423 // tasks.
424 AddToDelayedWorkQueue(pending_task);
425 } else {
426 // TODO(darin): Delete all tasks once it is safe to do so.
kuchhal@chromium.orge3bd2eb2009-05-15 01:44:26 +0900427 // Until it is totally safe, just do it when running Purify or
428 // Valgrind.
kuchhal@chromium.org3a6242e2009-07-24 07:28:49 +0900429#if defined(PURIFY)
jar@chromium.org63772352009-03-12 05:06:02 +0900430 delete pending_task.task;
kuchhal@chromium.orge3bd2eb2009-05-15 01:44:26 +0900431#elif defined(OS_POSIX)
432 if (RUNNING_ON_VALGRIND)
433 delete pending_task.task;
434#endif // defined(OS_POSIX)
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900435 }
initial.commit3f4a7322008-07-27 06:49:38 +0900436 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900437 did_work |= !deferred_non_nestable_work_queue_.empty();
438 while (!deferred_non_nestable_work_queue_.empty()) {
jar@chromium.org47fb2852009-03-12 04:46:41 +0900439 // TODO(darin): Delete all tasks once it is safe to do so.
kuchhal@chromium.org3a6242e2009-07-24 07:28:49 +0900440 // Until it is totaly safe, only delete them under Purify and Valgrind.
441 Task* task = NULL;
442#if defined(PURIFY)
443 task = deferred_non_nestable_work_queue_.front().task;
444#elif defined(OS_POSIX)
445 if (RUNNING_ON_VALGRIND)
446 task = deferred_non_nestable_work_queue_.front().task;
jar@chromium.org2fa6b4b2009-03-12 04:53:50 +0900447#endif
448 deferred_non_nestable_work_queue_.pop();
kuchhal@chromium.org3a6242e2009-07-24 07:28:49 +0900449 if (task)
450 delete task;
initial.commit3f4a7322008-07-27 06:49:38 +0900451 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900452 did_work |= !delayed_work_queue_.empty();
453 while (!delayed_work_queue_.empty()) {
454 Task* task = delayed_work_queue_.top().task;
455 delayed_work_queue_.pop();
456 delete task;
457 }
458 return did_work;
initial.commit3f4a7322008-07-27 06:49:38 +0900459}
460
darin@google.com981f3552008-08-16 12:09:05 +0900461bool MessageLoop::DoWork() {
darin@google.combe165ae2008-09-07 17:08:29 +0900462 if (!nestable_tasks_allowed_) {
463 // Task can't be executed right now.
464 return false;
465 }
466
467 for (;;) {
468 ReloadWorkQueue();
469 if (work_queue_.empty())
470 break;
471
472 // Execute oldest task.
473 do {
474 PendingTask pending_task = work_queue_.front();
475 work_queue_.pop();
476 if (!pending_task.delayed_run_time.is_null()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900477 AddToDelayedWorkQueue(pending_task);
darin@chromium.orgb2d33452008-09-24 04:19:20 +0900478 // If we changed the topmost task, then it is time to re-schedule.
479 if (delayed_work_queue_.top().task == pending_task.task)
darin@google.combe165ae2008-09-07 17:08:29 +0900480 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
481 } else {
482 if (DeferOrRunPendingTask(pending_task))
483 return true;
484 }
485 } while (!work_queue_.empty());
486 }
487
488 // Nothing happened.
489 return false;
darin@google.com981f3552008-08-16 12:09:05 +0900490}
491
darin@google.com6393bed2008-08-20 15:30:58 +0900492bool MessageLoop::DoDelayedWork(Time* next_delayed_work_time) {
darin@google.combe165ae2008-09-07 17:08:29 +0900493 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
494 *next_delayed_work_time = Time();
495 return false;
496 }
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900497
darin@google.combe165ae2008-09-07 17:08:29 +0900498 if (delayed_work_queue_.top().delayed_run_time > Time::Now()) {
499 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
500 return false;
501 }
darin@google.com981f3552008-08-16 12:09:05 +0900502
darin@google.combe165ae2008-09-07 17:08:29 +0900503 PendingTask pending_task = delayed_work_queue_.top();
504 delayed_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900505
darin@google.combe165ae2008-09-07 17:08:29 +0900506 if (!delayed_work_queue_.empty())
507 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
darin@google.com981f3552008-08-16 12:09:05 +0900508
darin@google.combe165ae2008-09-07 17:08:29 +0900509 return DeferOrRunPendingTask(pending_task);
darin@google.com981f3552008-08-16 12:09:05 +0900510}
511
512bool MessageLoop::DoIdleWork() {
513 if (ProcessNextDelayedNonNestableTask())
514 return true;
515
516 if (state_->quit_received)
517 pump_->Quit();
518
519 return false;
520}
521
522//------------------------------------------------------------------------------
523// MessageLoop::AutoRunState
524
525MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
526 // Make the loop reference us.
527 previous_state_ = loop_->state_;
528 if (previous_state_) {
529 run_depth = previous_state_->run_depth + 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900530 } else {
darin@google.com981f3552008-08-16 12:09:05 +0900531 run_depth = 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900532 }
darin@google.com981f3552008-08-16 12:09:05 +0900533 loop_->state_ = this;
534
535 // Initialize the other fields:
536 quit_received = false;
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900537#if !defined(OS_MACOSX)
darin@google.com981f3552008-08-16 12:09:05 +0900538 dispatcher = NULL;
539#endif
540}
541
542MessageLoop::AutoRunState::~AutoRunState() {
543 loop_->state_ = previous_state_;
darin@google.comee6fa722008-08-13 08:25:43 +0900544}
545
initial.commit3f4a7322008-07-27 06:49:38 +0900546//------------------------------------------------------------------------------
darin@google.combe165ae2008-09-07 17:08:29 +0900547// MessageLoop::PendingTask
initial.commit3f4a7322008-07-27 06:49:38 +0900548
darin@google.combe165ae2008-09-07 17:08:29 +0900549bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
550 // Since the top of a priority queue is defined as the "greatest" element, we
551 // need to invert the comparison here. We want the smaller time to be at the
552 // top of the heap.
initial.commit3f4a7322008-07-27 06:49:38 +0900553
darin@google.combe165ae2008-09-07 17:08:29 +0900554 if (delayed_run_time < other.delayed_run_time)
555 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900556
darin@google.combe165ae2008-09-07 17:08:29 +0900557 if (delayed_run_time > other.delayed_run_time)
558 return true;
initial.commit3f4a7322008-07-27 06:49:38 +0900559
darin@google.combe165ae2008-09-07 17:08:29 +0900560 // If the times happen to match, then we use the sequence number to decide.
561 // Compare the difference to support integer roll-over.
562 return (sequence_num - other.sequence_num) > 0;
initial.commit3f4a7322008-07-27 06:49:38 +0900563}
564
565//------------------------------------------------------------------------------
566// Method and data for histogramming events and actions taken by each instance
567// on each thread.
568
569// static
erg@chromium.org6f206e72010-07-15 03:58:17 +0900570bool MessageLoop::enable_histogrammer_ = false;
571
572// static
initial.commit3f4a7322008-07-27 06:49:38 +0900573void MessageLoop::EnableHistogrammer(bool enable) {
574 enable_histogrammer_ = enable;
575}
576
577void MessageLoop::StartHistogrammer() {
578 if (enable_histogrammer_ && !message_histogram_.get()
579 && StatisticsRecorder::WasStarted()) {
darin@google.com981f3552008-08-16 12:09:05 +0900580 DCHECK(!thread_name_.empty());
jar@chromium.orged5238a2009-12-28 15:59:52 +0900581 message_histogram_ = LinearHistogram::FactoryGet("MsgLoop:" + thread_name_,
582 kLeastNonZeroMessageId, kMaxMessageId,
583 kNumberOfDistinctMessagesDisplayed,
584 message_histogram_->kHexRangePrintingFlag);
initial.commit3f4a7322008-07-27 06:49:38 +0900585 message_histogram_->SetRangeDescriptions(event_descriptions_);
586 }
587}
588
589void MessageLoop::HistogramEvent(int event) {
590 if (message_histogram_.get())
591 message_histogram_->Add(event);
592}
593
erg@chromium.org6f206e72010-07-15 03:58:17 +0900594// Provide a macro that takes an expression (such as a constant, or macro
595// constant) and creates a pair to initalize an array of pairs. In this case,
596// our pair consists of the expressions value, and the "stringized" version
597// of the expression (i.e., the exrpression put in quotes). For example, if
598// we have:
599// #define FOO 2
600// #define BAR 5
601// then the following:
602// VALUE_TO_NUMBER_AND_NAME(FOO + BAR)
603// will expand to:
604// {7, "FOO + BAR"}
605// We use the resulting array as an argument to our histogram, which reads the
606// number as a bucket identifier, and proceeds to use the corresponding name
607// in the pair (i.e., the quoted string) when printing out a histogram.
608#define VALUE_TO_NUMBER_AND_NAME(name) {name, #name},
609
610// static
611const LinearHistogram::DescriptionPair MessageLoop::event_descriptions_[] = {
612 // Provide some pretty print capability in our histogram for our internal
613 // messages.
614
615 // A few events we handle (kindred to messages), and used to profile actions.
616 VALUE_TO_NUMBER_AND_NAME(kTaskRunEvent)
617 VALUE_TO_NUMBER_AND_NAME(kTimerEvent)
618
619 {-1, NULL} // The list must be null terminated, per API to histogram.
620};
621
darin@google.comd936b5b2008-08-26 14:53:57 +0900622//------------------------------------------------------------------------------
623// MessageLoopForUI
624
625#if defined(OS_WIN)
darin@google.comd936b5b2008-08-26 14:53:57 +0900626void MessageLoopForUI::DidProcessMessage(const MSG& message) {
627 pump_win()->DidProcessMessage(message);
628}
darin@google.comd936b5b2008-08-26 14:53:57 +0900629#endif // defined(OS_WIN)
630
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900631#if !defined(OS_MACOSX)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900632void MessageLoopForUI::AddObserver(Observer* observer) {
633 pump_ui()->AddObserver(observer);
634}
635
636void MessageLoopForUI::RemoveObserver(Observer* observer) {
637 pump_ui()->RemoveObserver(observer);
638}
639
640void MessageLoopForUI::Run(Dispatcher* dispatcher) {
641 AutoRunState save_state(this);
642 state_->dispatcher = dispatcher;
643 RunHandler();
644}
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900645#endif // !defined(OS_MACOSX)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900646
darin@google.comd936b5b2008-08-26 14:53:57 +0900647//------------------------------------------------------------------------------
648// MessageLoopForIO
649
650#if defined(OS_WIN)
651
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900652void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
653 pump_io()->RegisterIOHandler(file, handler);
654}
655
rvargas@google.com73887542008-11-08 06:52:15 +0900656bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
657 return pump_io()->WaitForIOCompletion(timeout, filter);
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900658}
659
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900660#elif defined(OS_POSIX)
661
jeremy@chromium.orgefc0db02008-12-16 07:02:17 +0900662bool MessageLoopForIO::WatchFileDescriptor(int fd,
663 bool persistent,
664 Mode mode,
665 FileDescriptorWatcher *controller,
666 Watcher *delegate) {
667 return pump_libevent()->WatchFileDescriptor(
668 fd,
669 persistent,
670 static_cast<base::MessagePumpLibevent::Mode>(mode),
671 controller,
672 delegate);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900673}
674
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900675#endif