blob: 218ff26b77f5b22306adb1cb868ce397fad12490 [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"
erg@chromium.orga7528522010-07-16 02:23:23 +090010#include "base/histogram.h"
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090011#include "base/lazy_instance.h"
initial.commit3f4a7322008-07-27 06:49:38 +090012#include "base/logging.h"
darin@google.com12d40bb2008-08-20 03:36:23 +090013#include "base/message_pump_default.h"
initial.commit3f4a7322008-07-27 06:49:38 +090014#include "base/string_util.h"
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090015#include "base/thread_local.h"
initial.commit3f4a7322008-07-27 06:49:38 +090016
mark@chromium.org059d0492008-09-24 06:08:28 +090017#if defined(OS_MACOSX)
18#include "base/message_pump_mac.h"
19#endif
dkegel@google.com9e044ae2008-09-19 03:46:26 +090020#if defined(OS_POSIX)
21#include "base/message_pump_libevent.h"
kuchhal@chromium.orge3bd2eb2009-05-15 01:44:26 +090022#include "base/third_party/valgrind/valgrind.h"
dkegel@google.com9e044ae2008-09-19 03:46:26 +090023#endif
evan@chromium.org875bb6e2009-12-29 09:32:52 +090024#if defined(OS_POSIX) && !defined(OS_MACOSX)
dsh@google.com119a2522008-10-04 01:52:59 +090025#include "base/message_pump_glib.h"
26#endif
dkegel@google.com9e044ae2008-09-19 03:46:26 +090027
dsh@google.com0f8dd262008-10-28 05:43:33 +090028using base::Time;
29using base::TimeDelta;
30
erg@chromium.orga7528522010-07-16 02:23:23 +090031namespace {
32
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090033// A lazily created thread local storage for quick access to a thread's message
34// loop, if one exists. This should be safe and free of static constructors.
erg@chromium.orga7528522010-07-16 02:23:23 +090035base::LazyInstance<base::ThreadLocalPointer<MessageLoop> > lazy_tls_ptr(
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090036 base::LINKER_INITIALIZED);
initial.commit3f4a7322008-07-27 06:49:38 +090037
initial.commit3f4a7322008-07-27 06:49:38 +090038// Logical events for Histogram profiling. Run with -message-loop-histogrammer
39// to get an accounting of messages and actions taken on each thread.
erg@chromium.orga7528522010-07-16 02:23:23 +090040const int kTaskRunEvent = 0x1;
41const int kTimerEvent = 0x2;
initial.commit3f4a7322008-07-27 06:49:38 +090042
43// Provide range of message IDs for use in histogramming and debug display.
erg@chromium.orga7528522010-07-16 02:23:23 +090044const int kLeastNonZeroMessageId = 1;
45const int kMaxMessageId = 1099;
46const int kNumberOfDistinctMessagesDisplayed = 1100;
47
48// Provide a macro that takes an expression (such as a constant, or macro
49// constant) and creates a pair to initalize an array of pairs. In this case,
50// our pair consists of the expressions value, and the "stringized" version
51// of the expression (i.e., the exrpression put in quotes). For example, if
52// we have:
53// #define FOO 2
54// #define BAR 5
55// then the following:
56// VALUE_TO_NUMBER_AND_NAME(FOO + BAR)
57// will expand to:
58// {7, "FOO + BAR"}
59// We use the resulting array as an argument to our histogram, which reads the
60// number as a bucket identifier, and proceeds to use the corresponding name
61// in the pair (i.e., the quoted string) when printing out a histogram.
62#define VALUE_TO_NUMBER_AND_NAME(name) {name, #name},
63
64const LinearHistogram::DescriptionPair event_descriptions_[] = {
65 // Provide some pretty print capability in our histogram for our internal
66 // messages.
67
68 // A few events we handle (kindred to messages), and used to profile actions.
69 VALUE_TO_NUMBER_AND_NAME(kTaskRunEvent)
70 VALUE_TO_NUMBER_AND_NAME(kTimerEvent)
71
72 {-1, NULL} // The list must be null terminated, per API to histogram.
73};
74
75bool enable_histogrammer_ = false;
76
77} // namespace
initial.commit3f4a7322008-07-27 06:49:38 +090078
79//------------------------------------------------------------------------------
80
darin@google.com981f3552008-08-16 12:09:05 +090081#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +090082
initial.commit3f4a7322008-07-27 06:49:38 +090083// Upon a SEH exception in this thread, it restores the original unhandled
84// exception filter.
85static int SEHFilter(LPTOP_LEVEL_EXCEPTION_FILTER old_filter) {
86 ::SetUnhandledExceptionFilter(old_filter);
87 return EXCEPTION_CONTINUE_SEARCH;
88}
89
90// Retrieves a pointer to the current unhandled exception filter. There
91// is no standalone getter method.
92static LPTOP_LEVEL_EXCEPTION_FILTER GetTopSEHFilter() {
93 LPTOP_LEVEL_EXCEPTION_FILTER top_filter = NULL;
94 top_filter = ::SetUnhandledExceptionFilter(0);
95 ::SetUnhandledExceptionFilter(top_filter);
96 return top_filter;
97}
98
darin@google.com981f3552008-08-16 12:09:05 +090099#endif // defined(OS_WIN)
100
initial.commit3f4a7322008-07-27 06:49:38 +0900101//------------------------------------------------------------------------------
102
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +0900103// static
104MessageLoop* MessageLoop::current() {
105 // TODO(darin): sadly, we cannot enable this yet since people call us even
106 // when they have no intention of using us.
erg@google.combf6ce9f2010-01-27 08:08:02 +0900107 // DCHECK(loop) << "Ouch, did you forget to initialize me?";
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +0900108 return lazy_tls_ptr.Pointer()->Get();
109}
110
darin@google.comd936b5b2008-08-26 14:53:57 +0900111MessageLoop::MessageLoop(Type type)
112 : type_(type),
darin@google.comee6fa722008-08-13 08:25:43 +0900113 nestable_tasks_allowed_(true),
darin@google.com12d40bb2008-08-20 03:36:23 +0900114 exception_restoration_(false),
darin@google.combe165ae2008-09-07 17:08:29 +0900115 state_(NULL),
116 next_sequence_num_(0) {
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +0900117 DCHECK(!current()) << "should only have one message loop per thread";
118 lazy_tls_ptr.Pointer()->Set(this);
darin@google.comd936b5b2008-08-26 14:53:57 +0900119
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900120// TODO(rvargas): Get rid of the OS guards.
darin@google.com981f3552008-08-16 12:09:05 +0900121#if defined(OS_WIN)
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900122#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
123#define MESSAGE_PUMP_IO new base::MessagePumpForIO()
124#elif defined(OS_MACOSX)
125#define MESSAGE_PUMP_UI base::MessagePumpMac::Create()
126#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
127#elif defined(OS_POSIX) // POSIX but not MACOSX.
128#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
129#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900130#else
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900131#error Not implemented
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900132#endif
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900133
134 if (type_ == TYPE_UI) {
135 pump_ = MESSAGE_PUMP_UI;
dsh@google.com119a2522008-10-04 01:52:59 +0900136 } else if (type_ == TYPE_IO) {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900137 pump_ = MESSAGE_PUMP_IO;
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900138 } else {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900139 DCHECK_EQ(TYPE_DEFAULT, type_);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900140 pump_ = new base::MessagePumpDefault();
141 }
initial.commit3f4a7322008-07-27 06:49:38 +0900142}
143
144MessageLoop::~MessageLoop() {
145 DCHECK(this == current());
darin@google.com965e5342008-08-06 08:16:41 +0900146
147 // Let interested parties have one last shot at accessing this.
148 FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
149 WillDestroyCurrentMessageLoop());
150
darin@google.com0e500502008-09-09 14:55:35 +0900151 DCHECK(!state_);
152
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900153 // Clean up any unprocessed tasks, but take care: deleting a task could
154 // result in the addition of more tasks (e.g., via DeleteSoon). We set a
155 // limit on the number of times we will allow a deleted task to generate more
156 // tasks. Normally, we should only pass through this loop once or twice. If
157 // we end up hitting the loop limit, then it is probably due to one task that
158 // is being stubborn. Inspect the queues to see who is left.
159 bool did_work;
160 for (int i = 0; i < 100; ++i) {
161 DeletePendingTasks();
162 ReloadWorkQueue();
163 // If we end up with empty queues, then break out of the loop.
164 did_work = DeletePendingTasks();
165 if (!did_work)
166 break;
darin@google.com0e500502008-09-09 14:55:35 +0900167 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900168 DCHECK(!did_work);
169
170 // OK, now make it so that no one can find us.
deanm@chromium.orge4cc5922008-09-10 20:14:56 +0900171 lazy_tls_ptr.Pointer()->Set(NULL);
initial.commit3f4a7322008-07-27 06:49:38 +0900172}
173
darin@google.com965e5342008-08-06 08:16:41 +0900174void MessageLoop::AddDestructionObserver(DestructionObserver *obs) {
175 DCHECK(this == current());
176 destruction_observers_.AddObserver(obs);
177}
178
179void MessageLoop::RemoveDestructionObserver(DestructionObserver *obs) {
180 DCHECK(this == current());
181 destruction_observers_.RemoveObserver(obs);
182}
183
willchan@chromium.orga9047632010-06-10 06:20:41 +0900184void MessageLoop::AddTaskObserver(TaskObserver *obs) {
185 DCHECK_EQ(this, current());
186 task_observers_.AddObserver(obs);
187}
188
189void MessageLoop::RemoveTaskObserver(TaskObserver *obs) {
190 DCHECK_EQ(this, current());
191 task_observers_.RemoveObserver(obs);
192}
193
darin@google.com6ddeb842008-08-15 16:31:20 +0900194void MessageLoop::Run() {
darin@google.com981f3552008-08-16 12:09:05 +0900195 AutoRunState save_state(this);
196 RunHandler();
darin@google.com6ddeb842008-08-15 16:31:20 +0900197}
198
jar@google.com9239e022008-07-31 22:10:20 +0900199void MessageLoop::RunAllPending() {
darin@google.com981f3552008-08-16 12:09:05 +0900200 AutoRunState save_state(this);
201 state_->quit_received = true; // Means run until we would otherwise block.
202 RunHandler();
initial.commit3f4a7322008-07-27 06:49:38 +0900203}
204
205// Runs the loop in two different SEH modes:
206// enable_SEH_restoration_ = false : any unhandled exception goes to the last
207// one that calls SetUnhandledExceptionFilter().
208// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
209// that was existed before the loop was run.
darin@google.com981f3552008-08-16 12:09:05 +0900210void MessageLoop::RunHandler() {
211#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +0900212 if (exception_restoration_) {
stoyan@google.com283facb2009-10-27 03:15:59 +0900213 RunInternalInSEHFrame();
darin@google.com981f3552008-08-16 12:09:05 +0900214 return;
initial.commit3f4a7322008-07-27 06:49:38 +0900215 }
darin@google.com981f3552008-08-16 12:09:05 +0900216#endif
217
218 RunInternal();
initial.commit3f4a7322008-07-27 06:49:38 +0900219}
stoyan@google.com283facb2009-10-27 03:15:59 +0900220//------------------------------------------------------------------------------
221#if defined(OS_WIN)
222__declspec(noinline) void MessageLoop::RunInternalInSEHFrame() {
223 LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
224 __try {
225 RunInternal();
226 } __except(SEHFilter(current_filter)) {
227 }
228 return;
229}
230#endif
initial.commit3f4a7322008-07-27 06:49:38 +0900231//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900232
darin@google.com981f3552008-08-16 12:09:05 +0900233void MessageLoop::RunInternal() {
234 DCHECK(this == current());
235
initial.commit3f4a7322008-07-27 06:49:38 +0900236 StartHistogrammer();
237
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900238#if !defined(OS_MACOSX)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900239 if (state_->dispatcher && type() == TYPE_UI) {
240 static_cast<base::MessagePumpForUI*>(pump_.get())->
241 RunWithDispatcher(this, state_->dispatcher);
darin@google.com981f3552008-08-16 12:09:05 +0900242 return;
jar@google.com9239e022008-07-31 22:10:20 +0900243 }
darin@google.com981f3552008-08-16 12:09:05 +0900244#endif
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900245
darin@google.com981f3552008-08-16 12:09:05 +0900246 pump_->Run(this);
jar@google.comfbaaf692008-07-30 16:50:53 +0900247}
jar@google.com7ff36e62008-07-30 15:58:56 +0900248
jar@google.comb4d1bff2008-07-31 04:03:59 +0900249//------------------------------------------------------------------------------
250// Wrapper functions for use in above message loop framework.
251
initial.commit3f4a7322008-07-27 06:49:38 +0900252bool MessageLoop::ProcessNextDelayedNonNestableTask() {
darin@google.com981f3552008-08-16 12:09:05 +0900253 if (state_->run_depth != 1)
initial.commit3f4a7322008-07-27 06:49:38 +0900254 return false;
255
darin@google.combe165ae2008-09-07 17:08:29 +0900256 if (deferred_non_nestable_work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900257 return false;
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900258
darin@google.combe165ae2008-09-07 17:08:29 +0900259 Task* task = deferred_non_nestable_work_queue_.front().task;
260 deferred_non_nestable_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900261
darin@google.combe165ae2008-09-07 17:08:29 +0900262 RunTask(task);
initial.commit3f4a7322008-07-27 06:49:38 +0900263 return true;
264}
265
initial.commit3f4a7322008-07-27 06:49:38 +0900266//------------------------------------------------------------------------------
267
268void MessageLoop::Quit() {
darin@google.com981f3552008-08-16 12:09:05 +0900269 DCHECK(current() == this);
270 if (state_) {
271 state_->quit_received = true;
272 } else {
273 NOTREACHED() << "Must be inside Run to call Quit";
initial.commit3f4a7322008-07-27 06:49:38 +0900274 }
initial.commit3f4a7322008-07-27 06:49:38 +0900275}
276
darin@chromium.orgd70a12c2010-02-23 16:12:22 +0900277void MessageLoop::QuitNow() {
278 DCHECK(current() == this);
279 if (state_) {
280 pump_->Quit();
281 } else {
282 NOTREACHED() << "Must be inside Run to call Quit";
283 }
284}
285
darin@google.combe165ae2008-09-07 17:08:29 +0900286void MessageLoop::PostTask(
287 const tracked_objects::Location& from_here, Task* task) {
288 PostTask_Helper(from_here, task, 0, true);
289}
290
291void MessageLoop::PostDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900292 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
darin@google.combe165ae2008-09-07 17:08:29 +0900293 PostTask_Helper(from_here, task, delay_ms, true);
294}
295
296void MessageLoop::PostNonNestableTask(
297 const tracked_objects::Location& from_here, Task* task) {
298 PostTask_Helper(from_here, task, 0, false);
299}
300
301void MessageLoop::PostNonNestableDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900302 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
darin@google.combe165ae2008-09-07 17:08:29 +0900303 PostTask_Helper(from_here, task, delay_ms, false);
304}
305
initial.commit3f4a7322008-07-27 06:49:38 +0900306// Possibly called on a background thread!
darin@google.combe165ae2008-09-07 17:08:29 +0900307void MessageLoop::PostTask_Helper(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900308 const tracked_objects::Location& from_here, Task* task, int64 delay_ms,
darin@google.combe165ae2008-09-07 17:08:29 +0900309 bool nestable) {
initial.commit3f4a7322008-07-27 06:49:38 +0900310 task->SetBirthPlace(from_here);
darin@google.com0795f572008-08-30 09:22:48 +0900311
darin@google.combe165ae2008-09-07 17:08:29 +0900312 PendingTask pending_task(task, nestable);
darin@google.com0795f572008-08-30 09:22:48 +0900313
314 if (delay_ms > 0) {
darin@google.combe165ae2008-09-07 17:08:29 +0900315 pending_task.delayed_run_time =
darin@google.com0795f572008-08-30 09:22:48 +0900316 Time::Now() + TimeDelta::FromMilliseconds(delay_ms);
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900317
318#if defined(OS_WIN)
319 if (high_resolution_timer_expiration_.is_null()) {
320 // Windows timers are granular to 15.6ms. If we only set high-res
321 // timers for those under 15.6ms, then a 18ms timer ticks at ~32ms,
322 // which as a percentage is pretty inaccurate. So enable high
323 // res timers for any timer which is within 2x of the granularity.
324 // This is a tradeoff between accuracy and power management.
325 bool needs_high_res_timers =
326 delay_ms < (2 * Time::kMinLowResolutionThresholdMs);
327 if (needs_high_res_timers) {
328 Time::ActivateHighResolutionTimer(true);
329 high_resolution_timer_expiration_ = base::TimeTicks::Now() +
330 TimeDelta::FromMilliseconds(kHighResolutionTimerModeLeaseTimeMs);
331 }
332 }
333#endif
darin@google.com0795f572008-08-30 09:22:48 +0900334 } else {
jar@chromium.orged5238a2009-12-28 15:59:52 +0900335 DCHECK_EQ(delay_ms, 0) << "delay should not be negative";
darin@google.com0795f572008-08-30 09:22:48 +0900336 }
337
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900338#if defined(OS_WIN)
339 if (!high_resolution_timer_expiration_.is_null()) {
340 if (base::TimeTicks::Now() > high_resolution_timer_expiration_) {
341 Time::ActivateHighResolutionTimer(false);
342 high_resolution_timer_expiration_ = base::TimeTicks();
343 }
344 }
345#endif
346
initial.commit3f4a7322008-07-27 06:49:38 +0900347 // Warning: Don't try to short-circuit, and handle this thread's tasks more
348 // directly, as it could starve handling of foreign threads. Put every task
349 // into this queue.
350
darin@google.com981f3552008-08-16 12:09:05 +0900351 scoped_refptr<base::MessagePump> pump;
initial.commit3f4a7322008-07-27 06:49:38 +0900352 {
darin@google.com981f3552008-08-16 12:09:05 +0900353 AutoLock locked(incoming_queue_lock_);
354
darin@google.combe165ae2008-09-07 17:08:29 +0900355 bool was_empty = incoming_queue_.empty();
356 incoming_queue_.push(pending_task);
initial.commit3f4a7322008-07-27 06:49:38 +0900357 if (!was_empty)
358 return; // Someone else should have started the sub-pump.
359
darin@google.com981f3552008-08-16 12:09:05 +0900360 pump = pump_;
darin@google.com6ddeb842008-08-15 16:31:20 +0900361 }
darin@google.com981f3552008-08-16 12:09:05 +0900362 // Since the incoming_queue_ may contain a task that destroys this message
363 // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
364 // We use a stack-based reference to the message pump so that we can call
365 // ScheduleWork outside of incoming_queue_lock_.
darin@google.com6ddeb842008-08-15 16:31:20 +0900366
darin@google.com981f3552008-08-16 12:09:05 +0900367 pump->ScheduleWork();
initial.commit3f4a7322008-07-27 06:49:38 +0900368}
369
370void MessageLoop::SetNestableTasksAllowed(bool allowed) {
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900371 if (nestable_tasks_allowed_ != allowed) {
372 nestable_tasks_allowed_ = allowed;
373 if (!nestable_tasks_allowed_)
374 return;
375 // Start the native pump if we are not already pumping.
darin@google.com981f3552008-08-16 12:09:05 +0900376 pump_->ScheduleWork();
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900377 }
initial.commit3f4a7322008-07-27 06:49:38 +0900378}
379
380bool MessageLoop::NestableTasksAllowed() const {
381 return nestable_tasks_allowed_;
382}
383
jcampan@chromium.orgeac57172009-07-02 04:53:59 +0900384bool MessageLoop::IsNested() {
385 return state_->run_depth > 1;
386}
387
initial.commit3f4a7322008-07-27 06:49:38 +0900388//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900389
initial.commit3f4a7322008-07-27 06:49:38 +0900390void MessageLoop::RunTask(Task* task) {
initial.commit3f4a7322008-07-27 06:49:38 +0900391 DCHECK(nestable_tasks_allowed_);
392 // Execute the task and assume the worst: It is probably not reentrant.
393 nestable_tasks_allowed_ = false;
darin@google.combe165ae2008-09-07 17:08:29 +0900394
395 HistogramEvent(kTaskRunEvent);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900396 FOR_EACH_OBSERVER(TaskObserver, task_observers_,
397 WillProcessTask(task->tracked_birth_time()));
darin@google.combe165ae2008-09-07 17:08:29 +0900398 task->Run();
willchan@chromium.orga9047632010-06-10 06:20:41 +0900399 FOR_EACH_OBSERVER(TaskObserver, task_observers_, DidProcessTask());
darin@google.combe165ae2008-09-07 17:08:29 +0900400 delete task;
401
402 nestable_tasks_allowed_ = true;
initial.commit3f4a7322008-07-27 06:49:38 +0900403}
404
darin@google.combe165ae2008-09-07 17:08:29 +0900405bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) {
406 if (pending_task.nestable || state_->run_depth == 1) {
407 RunTask(pending_task.task);
408 // Show that we ran a task (Note: a new one might arrive as a
409 // consequence!).
410 return true;
411 }
412
413 // We couldn't run the task now because we're in a nested message loop
414 // and the task isn't nestable.
415 deferred_non_nestable_work_queue_.push(pending_task);
416 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900417}
418
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900419void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
420 // Move to the delayed work queue. Initialize the sequence number
421 // before inserting into the delayed_work_queue_. The sequence number
422 // is used to faciliate FIFO sorting when two tasks have the same
423 // delayed_run_time value.
424 PendingTask new_pending_task(pending_task);
425 new_pending_task.sequence_num = next_sequence_num_++;
426 delayed_work_queue_.push(new_pending_task);
427}
428
initial.commit3f4a7322008-07-27 06:49:38 +0900429void MessageLoop::ReloadWorkQueue() {
430 // We can improve performance of our loading tasks from incoming_queue_ to
darin@google.com981f3552008-08-16 12:09:05 +0900431 // work_queue_ by waiting until the last minute (work_queue_ is empty) to
432 // load. That reduces the number of locks-per-task significantly when our
darin@google.combe165ae2008-09-07 17:08:29 +0900433 // queues get large.
434 if (!work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900435 return; // Wait till we *really* need to lock and load.
436
437 // Acquire all we can from the inter-thread queue with one lock acquisition.
initial.commit3f4a7322008-07-27 06:49:38 +0900438 {
439 AutoLock lock(incoming_queue_lock_);
darin@google.combe165ae2008-09-07 17:08:29 +0900440 if (incoming_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900441 return;
darin@chromium.orgb80ef1a2009-09-03 05:05:21 +0900442 incoming_queue_.Swap(&work_queue_); // Constant time
darin@google.combe165ae2008-09-07 17:08:29 +0900443 DCHECK(incoming_queue_.empty());
initial.commit3f4a7322008-07-27 06:49:38 +0900444 }
445}
446
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900447bool MessageLoop::DeletePendingTasks() {
448 bool did_work = !work_queue_.empty();
449 while (!work_queue_.empty()) {
450 PendingTask pending_task = work_queue_.front();
451 work_queue_.pop();
452 if (!pending_task.delayed_run_time.is_null()) {
453 // We want to delete delayed tasks in the same order in which they would
454 // normally be deleted in case of any funny dependencies between delayed
455 // tasks.
456 AddToDelayedWorkQueue(pending_task);
457 } else {
458 // TODO(darin): Delete all tasks once it is safe to do so.
kuchhal@chromium.orge3bd2eb2009-05-15 01:44:26 +0900459 // Until it is totally safe, just do it when running Purify or
460 // Valgrind.
kuchhal@chromium.org3a6242e2009-07-24 07:28:49 +0900461#if defined(PURIFY)
jar@chromium.org63772352009-03-12 05:06:02 +0900462 delete pending_task.task;
kuchhal@chromium.orge3bd2eb2009-05-15 01:44:26 +0900463#elif defined(OS_POSIX)
464 if (RUNNING_ON_VALGRIND)
465 delete pending_task.task;
466#endif // defined(OS_POSIX)
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900467 }
initial.commit3f4a7322008-07-27 06:49:38 +0900468 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900469 did_work |= !deferred_non_nestable_work_queue_.empty();
470 while (!deferred_non_nestable_work_queue_.empty()) {
jar@chromium.org47fb2852009-03-12 04:46:41 +0900471 // TODO(darin): Delete all tasks once it is safe to do so.
kuchhal@chromium.org3a6242e2009-07-24 07:28:49 +0900472 // Until it is totaly safe, only delete them under Purify and Valgrind.
473 Task* task = NULL;
474#if defined(PURIFY)
475 task = deferred_non_nestable_work_queue_.front().task;
476#elif defined(OS_POSIX)
477 if (RUNNING_ON_VALGRIND)
478 task = deferred_non_nestable_work_queue_.front().task;
jar@chromium.org2fa6b4b2009-03-12 04:53:50 +0900479#endif
480 deferred_non_nestable_work_queue_.pop();
kuchhal@chromium.org3a6242e2009-07-24 07:28:49 +0900481 if (task)
482 delete task;
initial.commit3f4a7322008-07-27 06:49:38 +0900483 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900484 did_work |= !delayed_work_queue_.empty();
485 while (!delayed_work_queue_.empty()) {
486 Task* task = delayed_work_queue_.top().task;
487 delayed_work_queue_.pop();
488 delete task;
489 }
490 return did_work;
initial.commit3f4a7322008-07-27 06:49:38 +0900491}
492
darin@google.com981f3552008-08-16 12:09:05 +0900493bool MessageLoop::DoWork() {
darin@google.combe165ae2008-09-07 17:08:29 +0900494 if (!nestable_tasks_allowed_) {
495 // Task can't be executed right now.
496 return false;
497 }
498
499 for (;;) {
500 ReloadWorkQueue();
501 if (work_queue_.empty())
502 break;
503
504 // Execute oldest task.
505 do {
506 PendingTask pending_task = work_queue_.front();
507 work_queue_.pop();
508 if (!pending_task.delayed_run_time.is_null()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900509 AddToDelayedWorkQueue(pending_task);
darin@chromium.orgb2d33452008-09-24 04:19:20 +0900510 // If we changed the topmost task, then it is time to re-schedule.
511 if (delayed_work_queue_.top().task == pending_task.task)
darin@google.combe165ae2008-09-07 17:08:29 +0900512 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
513 } else {
514 if (DeferOrRunPendingTask(pending_task))
515 return true;
516 }
517 } while (!work_queue_.empty());
518 }
519
520 // Nothing happened.
521 return false;
darin@google.com981f3552008-08-16 12:09:05 +0900522}
523
darin@google.com6393bed2008-08-20 15:30:58 +0900524bool MessageLoop::DoDelayedWork(Time* next_delayed_work_time) {
darin@google.combe165ae2008-09-07 17:08:29 +0900525 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
526 *next_delayed_work_time = Time();
527 return false;
528 }
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900529
darin@google.combe165ae2008-09-07 17:08:29 +0900530 if (delayed_work_queue_.top().delayed_run_time > Time::Now()) {
531 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
532 return false;
533 }
darin@google.com981f3552008-08-16 12:09:05 +0900534
darin@google.combe165ae2008-09-07 17:08:29 +0900535 PendingTask pending_task = delayed_work_queue_.top();
536 delayed_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900537
darin@google.combe165ae2008-09-07 17:08:29 +0900538 if (!delayed_work_queue_.empty())
539 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
darin@google.com981f3552008-08-16 12:09:05 +0900540
darin@google.combe165ae2008-09-07 17:08:29 +0900541 return DeferOrRunPendingTask(pending_task);
darin@google.com981f3552008-08-16 12:09:05 +0900542}
543
544bool MessageLoop::DoIdleWork() {
545 if (ProcessNextDelayedNonNestableTask())
546 return true;
547
548 if (state_->quit_received)
549 pump_->Quit();
550
551 return false;
552}
553
554//------------------------------------------------------------------------------
555// MessageLoop::AutoRunState
556
557MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
558 // Make the loop reference us.
559 previous_state_ = loop_->state_;
560 if (previous_state_) {
561 run_depth = previous_state_->run_depth + 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900562 } else {
darin@google.com981f3552008-08-16 12:09:05 +0900563 run_depth = 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900564 }
darin@google.com981f3552008-08-16 12:09:05 +0900565 loop_->state_ = this;
566
567 // Initialize the other fields:
568 quit_received = false;
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900569#if !defined(OS_MACOSX)
darin@google.com981f3552008-08-16 12:09:05 +0900570 dispatcher = NULL;
571#endif
572}
573
574MessageLoop::AutoRunState::~AutoRunState() {
575 loop_->state_ = previous_state_;
darin@google.comee6fa722008-08-13 08:25:43 +0900576}
577
initial.commit3f4a7322008-07-27 06:49:38 +0900578//------------------------------------------------------------------------------
darin@google.combe165ae2008-09-07 17:08:29 +0900579// MessageLoop::PendingTask
initial.commit3f4a7322008-07-27 06:49:38 +0900580
darin@google.combe165ae2008-09-07 17:08:29 +0900581bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
582 // Since the top of a priority queue is defined as the "greatest" element, we
583 // need to invert the comparison here. We want the smaller time to be at the
584 // top of the heap.
initial.commit3f4a7322008-07-27 06:49:38 +0900585
darin@google.combe165ae2008-09-07 17:08:29 +0900586 if (delayed_run_time < other.delayed_run_time)
587 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900588
darin@google.combe165ae2008-09-07 17:08:29 +0900589 if (delayed_run_time > other.delayed_run_time)
590 return true;
initial.commit3f4a7322008-07-27 06:49:38 +0900591
darin@google.combe165ae2008-09-07 17:08:29 +0900592 // If the times happen to match, then we use the sequence number to decide.
593 // Compare the difference to support integer roll-over.
594 return (sequence_num - other.sequence_num) > 0;
initial.commit3f4a7322008-07-27 06:49:38 +0900595}
596
597//------------------------------------------------------------------------------
598// Method and data for histogramming events and actions taken by each instance
599// on each thread.
600
601// static
initial.commit3f4a7322008-07-27 06:49:38 +0900602void MessageLoop::EnableHistogrammer(bool enable) {
603 enable_histogrammer_ = enable;
604}
605
606void MessageLoop::StartHistogrammer() {
607 if (enable_histogrammer_ && !message_histogram_.get()
608 && StatisticsRecorder::WasStarted()) {
darin@google.com981f3552008-08-16 12:09:05 +0900609 DCHECK(!thread_name_.empty());
jar@chromium.orged5238a2009-12-28 15:59:52 +0900610 message_histogram_ = LinearHistogram::FactoryGet("MsgLoop:" + thread_name_,
611 kLeastNonZeroMessageId, kMaxMessageId,
612 kNumberOfDistinctMessagesDisplayed,
613 message_histogram_->kHexRangePrintingFlag);
initial.commit3f4a7322008-07-27 06:49:38 +0900614 message_histogram_->SetRangeDescriptions(event_descriptions_);
615 }
616}
617
618void MessageLoop::HistogramEvent(int event) {
619 if (message_histogram_.get())
620 message_histogram_->Add(event);
621}
622
darin@google.comd936b5b2008-08-26 14:53:57 +0900623//------------------------------------------------------------------------------
624// MessageLoopForUI
625
626#if defined(OS_WIN)
darin@google.comd936b5b2008-08-26 14:53:57 +0900627void MessageLoopForUI::DidProcessMessage(const MSG& message) {
628 pump_win()->DidProcessMessage(message);
629}
darin@google.comd936b5b2008-08-26 14:53:57 +0900630#endif // defined(OS_WIN)
631
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900632#if !defined(OS_MACOSX)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900633void MessageLoopForUI::AddObserver(Observer* observer) {
634 pump_ui()->AddObserver(observer);
635}
636
637void MessageLoopForUI::RemoveObserver(Observer* observer) {
638 pump_ui()->RemoveObserver(observer);
639}
640
641void MessageLoopForUI::Run(Dispatcher* dispatcher) {
642 AutoRunState save_state(this);
643 state_->dispatcher = dispatcher;
644 RunHandler();
645}
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900646#endif // !defined(OS_MACOSX)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900647
darin@google.comd936b5b2008-08-26 14:53:57 +0900648//------------------------------------------------------------------------------
649// MessageLoopForIO
650
651#if defined(OS_WIN)
652
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900653void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
654 pump_io()->RegisterIOHandler(file, handler);
655}
656
rvargas@google.com73887542008-11-08 06:52:15 +0900657bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
658 return pump_io()->WaitForIOCompletion(timeout, filter);
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900659}
660
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900661#elif defined(OS_POSIX)
662
jeremy@chromium.orgefc0db02008-12-16 07:02:17 +0900663bool MessageLoopForIO::WatchFileDescriptor(int fd,
664 bool persistent,
665 Mode mode,
666 FileDescriptorWatcher *controller,
667 Watcher *delegate) {
668 return pump_libevent()->WatchFileDescriptor(
669 fd,
670 persistent,
671 static_cast<base::MessagePumpLibevent::Mode>(mode),
672 controller,
673 delegate);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900674}
675
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900676#endif