blob: 0b03d3c043dbbcef1ffaf39f599482bdd3d8489a [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"
brettw@chromium.org275c2ec2010-10-14 13:38:38 +090013#include "base/metrics/histogram.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
erg@chromium.orga7528522010-07-16 02:23:23 +090030namespace {
31
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090032// A lazily created thread local storage for quick access to a thread's message
33// loop, if one exists. This should be safe and free of static constructors.
erg@chromium.orga7528522010-07-16 02:23:23 +090034base::LazyInstance<base::ThreadLocalPointer<MessageLoop> > lazy_tls_ptr(
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090035 base::LINKER_INITIALIZED);
initial.commit3f4a7322008-07-27 06:49:38 +090036
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.orga7528522010-07-16 02:23:23 +090039const int kTaskRunEvent = 0x1;
40const 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.orga7528522010-07-16 02:23:23 +090043const int kLeastNonZeroMessageId = 1;
44const int kMaxMessageId = 1099;
45const int kNumberOfDistinctMessagesDisplayed = 1100;
46
47// Provide a macro that takes an expression (such as a constant, or macro
48// constant) and creates a pair to initalize an array of pairs. In this case,
49// our pair consists of the expressions value, and the "stringized" version
50// of the expression (i.e., the exrpression put in quotes). For example, if
51// we have:
52// #define FOO 2
53// #define BAR 5
54// then the following:
55// VALUE_TO_NUMBER_AND_NAME(FOO + BAR)
56// will expand to:
57// {7, "FOO + BAR"}
58// We use the resulting array as an argument to our histogram, which reads the
59// number as a bucket identifier, and proceeds to use the corresponding name
60// in the pair (i.e., the quoted string) when printing out a histogram.
61#define VALUE_TO_NUMBER_AND_NAME(name) {name, #name},
62
brettw@chromium.org275c2ec2010-10-14 13:38:38 +090063const base::LinearHistogram::DescriptionPair event_descriptions_[] = {
erg@chromium.orga7528522010-07-16 02:23:23 +090064 // Provide some pretty print capability in our histogram for our internal
65 // messages.
66
67 // A few events we handle (kindred to messages), and used to profile actions.
68 VALUE_TO_NUMBER_AND_NAME(kTaskRunEvent)
69 VALUE_TO_NUMBER_AND_NAME(kTimerEvent)
70
71 {-1, NULL} // The list must be null terminated, per API to histogram.
72};
73
74bool enable_histogrammer_ = false;
75
76} // namespace
initial.commit3f4a7322008-07-27 06:49:38 +090077
78//------------------------------------------------------------------------------
79
darin@google.com981f3552008-08-16 12:09:05 +090080#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +090081
initial.commit3f4a7322008-07-27 06:49:38 +090082// Upon a SEH exception in this thread, it restores the original unhandled
83// exception filter.
84static int SEHFilter(LPTOP_LEVEL_EXCEPTION_FILTER old_filter) {
85 ::SetUnhandledExceptionFilter(old_filter);
86 return EXCEPTION_CONTINUE_SEARCH;
87}
88
89// Retrieves a pointer to the current unhandled exception filter. There
90// is no standalone getter method.
91static LPTOP_LEVEL_EXCEPTION_FILTER GetTopSEHFilter() {
92 LPTOP_LEVEL_EXCEPTION_FILTER top_filter = NULL;
93 top_filter = ::SetUnhandledExceptionFilter(0);
94 ::SetUnhandledExceptionFilter(top_filter);
95 return top_filter;
96}
97
darin@google.com981f3552008-08-16 12:09:05 +090098#endif // defined(OS_WIN)
99
initial.commit3f4a7322008-07-27 06:49:38 +0900100//------------------------------------------------------------------------------
101
erg@chromium.org493f5f62010-07-16 06:03:54 +0900102MessageLoop::TaskObserver::TaskObserver() {
103}
104
105MessageLoop::TaskObserver::~TaskObserver() {
106}
107
108MessageLoop::DestructionObserver::~DestructionObserver() {
109}
110
111//------------------------------------------------------------------------------
112
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +0900113// static
114MessageLoop* MessageLoop::current() {
115 // TODO(darin): sadly, we cannot enable this yet since people call us even
116 // when they have no intention of using us.
erg@google.combf6ce9f2010-01-27 08:08:02 +0900117 // DCHECK(loop) << "Ouch, did you forget to initialize me?";
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +0900118 return lazy_tls_ptr.Pointer()->Get();
119}
120
darin@google.comd936b5b2008-08-26 14:53:57 +0900121MessageLoop::MessageLoop(Type type)
122 : type_(type),
darin@google.comee6fa722008-08-13 08:25:43 +0900123 nestable_tasks_allowed_(true),
darin@google.com12d40bb2008-08-20 03:36:23 +0900124 exception_restoration_(false),
darin@google.combe165ae2008-09-07 17:08:29 +0900125 state_(NULL),
126 next_sequence_num_(0) {
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +0900127 DCHECK(!current()) << "should only have one message loop per thread";
128 lazy_tls_ptr.Pointer()->Set(this);
darin@google.comd936b5b2008-08-26 14:53:57 +0900129
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900130// TODO(rvargas): Get rid of the OS guards.
darin@google.com981f3552008-08-16 12:09:05 +0900131#if defined(OS_WIN)
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900132#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
133#define MESSAGE_PUMP_IO new base::MessagePumpForIO()
134#elif defined(OS_MACOSX)
135#define MESSAGE_PUMP_UI base::MessagePumpMac::Create()
136#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
137#elif defined(OS_POSIX) // POSIX but not MACOSX.
138#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
139#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900140#else
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900141#error Not implemented
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900142#endif
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900143
144 if (type_ == TYPE_UI) {
145 pump_ = MESSAGE_PUMP_UI;
dsh@google.com119a2522008-10-04 01:52:59 +0900146 } else if (type_ == TYPE_IO) {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900147 pump_ = MESSAGE_PUMP_IO;
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900148 } else {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900149 DCHECK_EQ(TYPE_DEFAULT, type_);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900150 pump_ = new base::MessagePumpDefault();
151 }
initial.commit3f4a7322008-07-27 06:49:38 +0900152}
153
154MessageLoop::~MessageLoop() {
155 DCHECK(this == current());
darin@google.com965e5342008-08-06 08:16:41 +0900156
157 // Let interested parties have one last shot at accessing this.
158 FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
159 WillDestroyCurrentMessageLoop());
160
darin@google.com0e500502008-09-09 14:55:35 +0900161 DCHECK(!state_);
162
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900163 // Clean up any unprocessed tasks, but take care: deleting a task could
164 // result in the addition of more tasks (e.g., via DeleteSoon). We set a
165 // limit on the number of times we will allow a deleted task to generate more
166 // tasks. Normally, we should only pass through this loop once or twice. If
167 // we end up hitting the loop limit, then it is probably due to one task that
168 // is being stubborn. Inspect the queues to see who is left.
169 bool did_work;
170 for (int i = 0; i < 100; ++i) {
171 DeletePendingTasks();
172 ReloadWorkQueue();
173 // If we end up with empty queues, then break out of the loop.
174 did_work = DeletePendingTasks();
175 if (!did_work)
176 break;
darin@google.com0e500502008-09-09 14:55:35 +0900177 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900178 DCHECK(!did_work);
179
180 // OK, now make it so that no one can find us.
deanm@chromium.orge4cc5922008-09-10 20:14:56 +0900181 lazy_tls_ptr.Pointer()->Set(NULL);
mbelshe@chromium.orgebe0e0a2010-10-20 17:52:32 +0900182
183#if defined(OS_WIN)
184 // If we left the high-resolution timer activated, deactivate it now.
185 // Doing this is not-critical, it is mainly to make sure we track
186 // the high resolution timer activations properly in our unit tests.
187 if (!high_resolution_timer_expiration_.is_null()) {
188 Time::ActivateHighResolutionTimer(false);
189 high_resolution_timer_expiration_ = base::TimeTicks();
190 }
191#endif
initial.commit3f4a7322008-07-27 06:49:38 +0900192}
193
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900194void MessageLoop::AddDestructionObserver(
195 DestructionObserver* destruction_observer) {
darin@google.com965e5342008-08-06 08:16:41 +0900196 DCHECK(this == current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900197 destruction_observers_.AddObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900198}
199
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900200void MessageLoop::RemoveDestructionObserver(
201 DestructionObserver* destruction_observer) {
darin@google.com965e5342008-08-06 08:16:41 +0900202 DCHECK(this == current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900203 destruction_observers_.RemoveObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900204}
205
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900206void MessageLoop::AddTaskObserver(TaskObserver* task_observer) {
willchan@chromium.orga9047632010-06-10 06:20:41 +0900207 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900208 task_observers_.AddObserver(task_observer);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900209}
210
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900211void MessageLoop::RemoveTaskObserver(TaskObserver* task_observer) {
willchan@chromium.orga9047632010-06-10 06:20:41 +0900212 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900213 task_observers_.RemoveObserver(task_observer);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900214}
215
darin@google.com6ddeb842008-08-15 16:31:20 +0900216void MessageLoop::Run() {
darin@google.com981f3552008-08-16 12:09:05 +0900217 AutoRunState save_state(this);
218 RunHandler();
darin@google.com6ddeb842008-08-15 16:31:20 +0900219}
220
jar@google.com9239e022008-07-31 22:10:20 +0900221void MessageLoop::RunAllPending() {
darin@google.com981f3552008-08-16 12:09:05 +0900222 AutoRunState save_state(this);
223 state_->quit_received = true; // Means run until we would otherwise block.
224 RunHandler();
initial.commit3f4a7322008-07-27 06:49:38 +0900225}
226
227// Runs the loop in two different SEH modes:
228// enable_SEH_restoration_ = false : any unhandled exception goes to the last
229// one that calls SetUnhandledExceptionFilter().
230// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
231// that was existed before the loop was run.
darin@google.com981f3552008-08-16 12:09:05 +0900232void MessageLoop::RunHandler() {
233#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +0900234 if (exception_restoration_) {
stoyan@google.com283facb2009-10-27 03:15:59 +0900235 RunInternalInSEHFrame();
darin@google.com981f3552008-08-16 12:09:05 +0900236 return;
initial.commit3f4a7322008-07-27 06:49:38 +0900237 }
darin@google.com981f3552008-08-16 12:09:05 +0900238#endif
239
240 RunInternal();
initial.commit3f4a7322008-07-27 06:49:38 +0900241}
stoyan@google.com283facb2009-10-27 03:15:59 +0900242//------------------------------------------------------------------------------
243#if defined(OS_WIN)
244__declspec(noinline) void MessageLoop::RunInternalInSEHFrame() {
245 LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
246 __try {
247 RunInternal();
248 } __except(SEHFilter(current_filter)) {
249 }
250 return;
251}
252#endif
initial.commit3f4a7322008-07-27 06:49:38 +0900253//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900254
darin@google.com981f3552008-08-16 12:09:05 +0900255void MessageLoop::RunInternal() {
256 DCHECK(this == current());
257
initial.commit3f4a7322008-07-27 06:49:38 +0900258 StartHistogrammer();
259
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900260#if !defined(OS_MACOSX)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900261 if (state_->dispatcher && type() == TYPE_UI) {
262 static_cast<base::MessagePumpForUI*>(pump_.get())->
263 RunWithDispatcher(this, state_->dispatcher);
darin@google.com981f3552008-08-16 12:09:05 +0900264 return;
jar@google.com9239e022008-07-31 22:10:20 +0900265 }
darin@google.com981f3552008-08-16 12:09:05 +0900266#endif
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900267
darin@google.com981f3552008-08-16 12:09:05 +0900268 pump_->Run(this);
jar@google.comfbaaf692008-07-30 16:50:53 +0900269}
jar@google.com7ff36e62008-07-30 15:58:56 +0900270
jar@google.comb4d1bff2008-07-31 04:03:59 +0900271//------------------------------------------------------------------------------
272// Wrapper functions for use in above message loop framework.
273
initial.commit3f4a7322008-07-27 06:49:38 +0900274bool MessageLoop::ProcessNextDelayedNonNestableTask() {
darin@google.com981f3552008-08-16 12:09:05 +0900275 if (state_->run_depth != 1)
initial.commit3f4a7322008-07-27 06:49:38 +0900276 return false;
277
darin@google.combe165ae2008-09-07 17:08:29 +0900278 if (deferred_non_nestable_work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900279 return false;
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900280
darin@google.combe165ae2008-09-07 17:08:29 +0900281 Task* task = deferred_non_nestable_work_queue_.front().task;
282 deferred_non_nestable_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900283
darin@google.combe165ae2008-09-07 17:08:29 +0900284 RunTask(task);
initial.commit3f4a7322008-07-27 06:49:38 +0900285 return true;
286}
287
initial.commit3f4a7322008-07-27 06:49:38 +0900288//------------------------------------------------------------------------------
289
290void MessageLoop::Quit() {
darin@google.com981f3552008-08-16 12:09:05 +0900291 DCHECK(current() == this);
292 if (state_) {
293 state_->quit_received = true;
294 } else {
295 NOTREACHED() << "Must be inside Run to call Quit";
initial.commit3f4a7322008-07-27 06:49:38 +0900296 }
initial.commit3f4a7322008-07-27 06:49:38 +0900297}
298
darin@chromium.orgd70a12c2010-02-23 16:12:22 +0900299void MessageLoop::QuitNow() {
300 DCHECK(current() == this);
301 if (state_) {
302 pump_->Quit();
303 } else {
304 NOTREACHED() << "Must be inside Run to call Quit";
305 }
306}
307
darin@google.combe165ae2008-09-07 17:08:29 +0900308void MessageLoop::PostTask(
309 const tracked_objects::Location& from_here, Task* task) {
310 PostTask_Helper(from_here, task, 0, true);
311}
312
313void MessageLoop::PostDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900314 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
darin@google.combe165ae2008-09-07 17:08:29 +0900315 PostTask_Helper(from_here, task, delay_ms, true);
316}
317
318void MessageLoop::PostNonNestableTask(
319 const tracked_objects::Location& from_here, Task* task) {
320 PostTask_Helper(from_here, task, 0, false);
321}
322
323void MessageLoop::PostNonNestableDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900324 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
darin@google.combe165ae2008-09-07 17:08:29 +0900325 PostTask_Helper(from_here, task, delay_ms, false);
326}
327
initial.commit3f4a7322008-07-27 06:49:38 +0900328// Possibly called on a background thread!
darin@google.combe165ae2008-09-07 17:08:29 +0900329void MessageLoop::PostTask_Helper(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900330 const tracked_objects::Location& from_here, Task* task, int64 delay_ms,
darin@google.combe165ae2008-09-07 17:08:29 +0900331 bool nestable) {
initial.commit3f4a7322008-07-27 06:49:38 +0900332 task->SetBirthPlace(from_here);
darin@google.com0795f572008-08-30 09:22:48 +0900333
darin@google.combe165ae2008-09-07 17:08:29 +0900334 PendingTask pending_task(task, nestable);
darin@google.com0795f572008-08-30 09:22:48 +0900335
336 if (delay_ms > 0) {
darin@google.combe165ae2008-09-07 17:08:29 +0900337 pending_task.delayed_run_time =
darin@google.com0795f572008-08-30 09:22:48 +0900338 Time::Now() + TimeDelta::FromMilliseconds(delay_ms);
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900339
340#if defined(OS_WIN)
341 if (high_resolution_timer_expiration_.is_null()) {
342 // Windows timers are granular to 15.6ms. If we only set high-res
343 // timers for those under 15.6ms, then a 18ms timer ticks at ~32ms,
344 // which as a percentage is pretty inaccurate. So enable high
345 // res timers for any timer which is within 2x of the granularity.
346 // This is a tradeoff between accuracy and power management.
347 bool needs_high_res_timers =
348 delay_ms < (2 * Time::kMinLowResolutionThresholdMs);
349 if (needs_high_res_timers) {
mbelshe@chromium.orgebe0e0a2010-10-20 17:52:32 +0900350 if (Time::ActivateHighResolutionTimer(true)) {
351 high_resolution_timer_expiration_ = base::TimeTicks::Now() +
352 TimeDelta::FromMilliseconds(kHighResolutionTimerModeLeaseTimeMs);
353 }
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900354 }
355 }
356#endif
darin@google.com0795f572008-08-30 09:22:48 +0900357 } else {
jar@chromium.orged5238a2009-12-28 15:59:52 +0900358 DCHECK_EQ(delay_ms, 0) << "delay should not be negative";
darin@google.com0795f572008-08-30 09:22:48 +0900359 }
360
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900361#if defined(OS_WIN)
362 if (!high_resolution_timer_expiration_.is_null()) {
363 if (base::TimeTicks::Now() > high_resolution_timer_expiration_) {
364 Time::ActivateHighResolutionTimer(false);
365 high_resolution_timer_expiration_ = base::TimeTicks();
366 }
367 }
368#endif
369
initial.commit3f4a7322008-07-27 06:49:38 +0900370 // Warning: Don't try to short-circuit, and handle this thread's tasks more
371 // directly, as it could starve handling of foreign threads. Put every task
372 // into this queue.
373
darin@google.com981f3552008-08-16 12:09:05 +0900374 scoped_refptr<base::MessagePump> pump;
initial.commit3f4a7322008-07-27 06:49:38 +0900375 {
darin@google.com981f3552008-08-16 12:09:05 +0900376 AutoLock locked(incoming_queue_lock_);
377
darin@google.combe165ae2008-09-07 17:08:29 +0900378 bool was_empty = incoming_queue_.empty();
379 incoming_queue_.push(pending_task);
initial.commit3f4a7322008-07-27 06:49:38 +0900380 if (!was_empty)
381 return; // Someone else should have started the sub-pump.
382
darin@google.com981f3552008-08-16 12:09:05 +0900383 pump = pump_;
darin@google.com6ddeb842008-08-15 16:31:20 +0900384 }
darin@google.com981f3552008-08-16 12:09:05 +0900385 // Since the incoming_queue_ may contain a task that destroys this message
386 // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
387 // We use a stack-based reference to the message pump so that we can call
388 // ScheduleWork outside of incoming_queue_lock_.
darin@google.com6ddeb842008-08-15 16:31:20 +0900389
darin@google.com981f3552008-08-16 12:09:05 +0900390 pump->ScheduleWork();
initial.commit3f4a7322008-07-27 06:49:38 +0900391}
392
393void MessageLoop::SetNestableTasksAllowed(bool allowed) {
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900394 if (nestable_tasks_allowed_ != allowed) {
395 nestable_tasks_allowed_ = allowed;
396 if (!nestable_tasks_allowed_)
397 return;
398 // Start the native pump if we are not already pumping.
darin@google.com981f3552008-08-16 12:09:05 +0900399 pump_->ScheduleWork();
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900400 }
initial.commit3f4a7322008-07-27 06:49:38 +0900401}
402
403bool MessageLoop::NestableTasksAllowed() const {
404 return nestable_tasks_allowed_;
405}
406
jcampan@chromium.orgeac57172009-07-02 04:53:59 +0900407bool MessageLoop::IsNested() {
408 return state_->run_depth > 1;
409}
410
initial.commit3f4a7322008-07-27 06:49:38 +0900411//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900412
initial.commit3f4a7322008-07-27 06:49:38 +0900413void MessageLoop::RunTask(Task* task) {
initial.commit3f4a7322008-07-27 06:49:38 +0900414 DCHECK(nestable_tasks_allowed_);
415 // Execute the task and assume the worst: It is probably not reentrant.
416 nestable_tasks_allowed_ = false;
darin@google.combe165ae2008-09-07 17:08:29 +0900417
418 HistogramEvent(kTaskRunEvent);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900419 FOR_EACH_OBSERVER(TaskObserver, task_observers_,
420 WillProcessTask(task->tracked_birth_time()));
darin@google.combe165ae2008-09-07 17:08:29 +0900421 task->Run();
willchan@chromium.orga9047632010-06-10 06:20:41 +0900422 FOR_EACH_OBSERVER(TaskObserver, task_observers_, DidProcessTask());
darin@google.combe165ae2008-09-07 17:08:29 +0900423 delete task;
424
425 nestable_tasks_allowed_ = true;
initial.commit3f4a7322008-07-27 06:49:38 +0900426}
427
darin@google.combe165ae2008-09-07 17:08:29 +0900428bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) {
429 if (pending_task.nestable || state_->run_depth == 1) {
430 RunTask(pending_task.task);
431 // Show that we ran a task (Note: a new one might arrive as a
432 // consequence!).
433 return true;
434 }
435
436 // We couldn't run the task now because we're in a nested message loop
437 // and the task isn't nestable.
438 deferred_non_nestable_work_queue_.push(pending_task);
439 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900440}
441
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900442void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
443 // Move to the delayed work queue. Initialize the sequence number
444 // before inserting into the delayed_work_queue_. The sequence number
445 // is used to faciliate FIFO sorting when two tasks have the same
446 // delayed_run_time value.
447 PendingTask new_pending_task(pending_task);
448 new_pending_task.sequence_num = next_sequence_num_++;
449 delayed_work_queue_.push(new_pending_task);
450}
451
initial.commit3f4a7322008-07-27 06:49:38 +0900452void MessageLoop::ReloadWorkQueue() {
453 // We can improve performance of our loading tasks from incoming_queue_ to
darin@google.com981f3552008-08-16 12:09:05 +0900454 // work_queue_ by waiting until the last minute (work_queue_ is empty) to
455 // load. That reduces the number of locks-per-task significantly when our
darin@google.combe165ae2008-09-07 17:08:29 +0900456 // queues get large.
457 if (!work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900458 return; // Wait till we *really* need to lock and load.
459
460 // Acquire all we can from the inter-thread queue with one lock acquisition.
initial.commit3f4a7322008-07-27 06:49:38 +0900461 {
462 AutoLock lock(incoming_queue_lock_);
darin@google.combe165ae2008-09-07 17:08:29 +0900463 if (incoming_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900464 return;
darin@chromium.orgb80ef1a2009-09-03 05:05:21 +0900465 incoming_queue_.Swap(&work_queue_); // Constant time
darin@google.combe165ae2008-09-07 17:08:29 +0900466 DCHECK(incoming_queue_.empty());
initial.commit3f4a7322008-07-27 06:49:38 +0900467 }
468}
469
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900470bool MessageLoop::DeletePendingTasks() {
471 bool did_work = !work_queue_.empty();
472 while (!work_queue_.empty()) {
473 PendingTask pending_task = work_queue_.front();
474 work_queue_.pop();
475 if (!pending_task.delayed_run_time.is_null()) {
476 // We want to delete delayed tasks in the same order in which they would
477 // normally be deleted in case of any funny dependencies between delayed
478 // tasks.
479 AddToDelayedWorkQueue(pending_task);
480 } else {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900481 // TODO(darin): Delete all tasks once it is safe to do so.
482 // Until it is totally safe, just do it when running Purify or
483 // Valgrind.
thestig@chromium.orgd4a0a922010-10-15 11:38:43 +0900484#if defined(PURIFY)
jar@chromium.org63772352009-03-12 05:06:02 +0900485 delete pending_task.task;
akalin@chromium.org839060b2010-08-03 12:06:21 +0900486#elif defined(OS_POSIX)
487 if (RUNNING_ON_VALGRIND)
488 delete pending_task.task;
489#endif // defined(OS_POSIX)
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900490 }
initial.commit3f4a7322008-07-27 06:49:38 +0900491 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900492 did_work |= !deferred_non_nestable_work_queue_.empty();
493 while (!deferred_non_nestable_work_queue_.empty()) {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900494 // TODO(darin): Delete all tasks once it is safe to do so.
495 // Until it is totaly safe, only delete them under Purify and Valgrind.
496 Task* task = NULL;
thestig@chromium.orgd4a0a922010-10-15 11:38:43 +0900497#if defined(PURIFY)
akalin@chromium.org839060b2010-08-03 12:06:21 +0900498 task = deferred_non_nestable_work_queue_.front().task;
499#elif defined(OS_POSIX)
500 if (RUNNING_ON_VALGRIND)
501 task = deferred_non_nestable_work_queue_.front().task;
502#endif
jar@chromium.org2fa6b4b2009-03-12 04:53:50 +0900503 deferred_non_nestable_work_queue_.pop();
akalin@chromium.org839060b2010-08-03 12:06:21 +0900504 if (task)
505 delete task;
initial.commit3f4a7322008-07-27 06:49:38 +0900506 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900507 did_work |= !delayed_work_queue_.empty();
508 while (!delayed_work_queue_.empty()) {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900509 Task* task = delayed_work_queue_.top().task;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900510 delayed_work_queue_.pop();
akalin@chromium.org839060b2010-08-03 12:06:21 +0900511 delete task;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900512 }
513 return did_work;
initial.commit3f4a7322008-07-27 06:49:38 +0900514}
515
darin@google.com981f3552008-08-16 12:09:05 +0900516bool MessageLoop::DoWork() {
darin@google.combe165ae2008-09-07 17:08:29 +0900517 if (!nestable_tasks_allowed_) {
518 // Task can't be executed right now.
519 return false;
520 }
521
522 for (;;) {
523 ReloadWorkQueue();
524 if (work_queue_.empty())
525 break;
526
527 // Execute oldest task.
528 do {
529 PendingTask pending_task = work_queue_.front();
530 work_queue_.pop();
531 if (!pending_task.delayed_run_time.is_null()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900532 AddToDelayedWorkQueue(pending_task);
darin@chromium.orgb2d33452008-09-24 04:19:20 +0900533 // If we changed the topmost task, then it is time to re-schedule.
534 if (delayed_work_queue_.top().task == pending_task.task)
darin@google.combe165ae2008-09-07 17:08:29 +0900535 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
536 } else {
537 if (DeferOrRunPendingTask(pending_task))
538 return true;
539 }
540 } while (!work_queue_.empty());
541 }
542
543 // Nothing happened.
544 return false;
darin@google.com981f3552008-08-16 12:09:05 +0900545}
546
darin@google.com6393bed2008-08-20 15:30:58 +0900547bool MessageLoop::DoDelayedWork(Time* next_delayed_work_time) {
darin@google.combe165ae2008-09-07 17:08:29 +0900548 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
549 *next_delayed_work_time = Time();
550 return false;
551 }
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900552
darin@google.combe165ae2008-09-07 17:08:29 +0900553 if (delayed_work_queue_.top().delayed_run_time > Time::Now()) {
554 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
555 return false;
556 }
darin@google.com981f3552008-08-16 12:09:05 +0900557
darin@google.combe165ae2008-09-07 17:08:29 +0900558 PendingTask pending_task = delayed_work_queue_.top();
559 delayed_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900560
darin@google.combe165ae2008-09-07 17:08:29 +0900561 if (!delayed_work_queue_.empty())
562 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
darin@google.com981f3552008-08-16 12:09:05 +0900563
darin@google.combe165ae2008-09-07 17:08:29 +0900564 return DeferOrRunPendingTask(pending_task);
darin@google.com981f3552008-08-16 12:09:05 +0900565}
566
567bool MessageLoop::DoIdleWork() {
568 if (ProcessNextDelayedNonNestableTask())
569 return true;
570
571 if (state_->quit_received)
572 pump_->Quit();
573
574 return false;
575}
576
577//------------------------------------------------------------------------------
578// MessageLoop::AutoRunState
579
580MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
581 // Make the loop reference us.
582 previous_state_ = loop_->state_;
583 if (previous_state_) {
584 run_depth = previous_state_->run_depth + 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900585 } else {
darin@google.com981f3552008-08-16 12:09:05 +0900586 run_depth = 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900587 }
darin@google.com981f3552008-08-16 12:09:05 +0900588 loop_->state_ = this;
589
590 // Initialize the other fields:
591 quit_received = false;
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900592#if !defined(OS_MACOSX)
darin@google.com981f3552008-08-16 12:09:05 +0900593 dispatcher = NULL;
594#endif
595}
596
597MessageLoop::AutoRunState::~AutoRunState() {
598 loop_->state_ = previous_state_;
darin@google.comee6fa722008-08-13 08:25:43 +0900599}
600
initial.commit3f4a7322008-07-27 06:49:38 +0900601//------------------------------------------------------------------------------
darin@google.combe165ae2008-09-07 17:08:29 +0900602// MessageLoop::PendingTask
initial.commit3f4a7322008-07-27 06:49:38 +0900603
darin@google.combe165ae2008-09-07 17:08:29 +0900604bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
605 // Since the top of a priority queue is defined as the "greatest" element, we
606 // need to invert the comparison here. We want the smaller time to be at the
607 // top of the heap.
initial.commit3f4a7322008-07-27 06:49:38 +0900608
darin@google.combe165ae2008-09-07 17:08:29 +0900609 if (delayed_run_time < other.delayed_run_time)
610 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900611
darin@google.combe165ae2008-09-07 17:08:29 +0900612 if (delayed_run_time > other.delayed_run_time)
613 return true;
initial.commit3f4a7322008-07-27 06:49:38 +0900614
darin@google.combe165ae2008-09-07 17:08:29 +0900615 // If the times happen to match, then we use the sequence number to decide.
616 // Compare the difference to support integer roll-over.
617 return (sequence_num - other.sequence_num) > 0;
initial.commit3f4a7322008-07-27 06:49:38 +0900618}
619
620//------------------------------------------------------------------------------
621// Method and data for histogramming events and actions taken by each instance
622// on each thread.
623
624// static
initial.commit3f4a7322008-07-27 06:49:38 +0900625void MessageLoop::EnableHistogrammer(bool enable) {
626 enable_histogrammer_ = enable;
627}
628
629void MessageLoop::StartHistogrammer() {
630 if (enable_histogrammer_ && !message_histogram_.get()
brettw@chromium.org275c2ec2010-10-14 13:38:38 +0900631 && base::StatisticsRecorder::WasStarted()) {
darin@google.com981f3552008-08-16 12:09:05 +0900632 DCHECK(!thread_name_.empty());
brettw@chromium.org275c2ec2010-10-14 13:38:38 +0900633 message_histogram_ = base::LinearHistogram::FactoryGet(
634 "MsgLoop:" + thread_name_,
jar@chromium.orged5238a2009-12-28 15:59:52 +0900635 kLeastNonZeroMessageId, kMaxMessageId,
636 kNumberOfDistinctMessagesDisplayed,
637 message_histogram_->kHexRangePrintingFlag);
initial.commit3f4a7322008-07-27 06:49:38 +0900638 message_histogram_->SetRangeDescriptions(event_descriptions_);
639 }
640}
641
642void MessageLoop::HistogramEvent(int event) {
643 if (message_histogram_.get())
644 message_histogram_->Add(event);
645}
646
darin@google.comd936b5b2008-08-26 14:53:57 +0900647//------------------------------------------------------------------------------
648// MessageLoopForUI
649
650#if defined(OS_WIN)
darin@google.comd936b5b2008-08-26 14:53:57 +0900651void MessageLoopForUI::DidProcessMessage(const MSG& message) {
652 pump_win()->DidProcessMessage(message);
653}
darin@google.comd936b5b2008-08-26 14:53:57 +0900654#endif // defined(OS_WIN)
655
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900656#if !defined(OS_MACOSX)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900657void MessageLoopForUI::AddObserver(Observer* observer) {
658 pump_ui()->AddObserver(observer);
659}
660
661void MessageLoopForUI::RemoveObserver(Observer* observer) {
662 pump_ui()->RemoveObserver(observer);
663}
664
665void MessageLoopForUI::Run(Dispatcher* dispatcher) {
666 AutoRunState save_state(this);
667 state_->dispatcher = dispatcher;
668 RunHandler();
669}
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900670#endif // !defined(OS_MACOSX)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900671
darin@google.comd936b5b2008-08-26 14:53:57 +0900672//------------------------------------------------------------------------------
673// MessageLoopForIO
674
675#if defined(OS_WIN)
676
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900677void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
678 pump_io()->RegisterIOHandler(file, handler);
679}
680
rvargas@google.com73887542008-11-08 06:52:15 +0900681bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
682 return pump_io()->WaitForIOCompletion(timeout, filter);
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900683}
684
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900685#elif defined(OS_POSIX)
686
jeremy@chromium.orgefc0db02008-12-16 07:02:17 +0900687bool MessageLoopForIO::WatchFileDescriptor(int fd,
688 bool persistent,
689 Mode mode,
690 FileDescriptorWatcher *controller,
691 Watcher *delegate) {
692 return pump_libevent()->WatchFileDescriptor(
693 fd,
694 persistent,
695 static_cast<base::MessagePumpLibevent::Mode>(mode),
696 controller,
697 delegate);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900698}
699
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900700#endif