blob: 8f6c997b24afeecbf2597d863e45bfbda063f0f1 [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);
initial.commit3f4a7322008-07-27 06:49:38 +0900182}
183
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900184void MessageLoop::AddDestructionObserver(
185 DestructionObserver* destruction_observer) {
darin@google.com965e5342008-08-06 08:16:41 +0900186 DCHECK(this == current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900187 destruction_observers_.AddObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900188}
189
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900190void MessageLoop::RemoveDestructionObserver(
191 DestructionObserver* destruction_observer) {
darin@google.com965e5342008-08-06 08:16:41 +0900192 DCHECK(this == current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900193 destruction_observers_.RemoveObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900194}
195
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900196void MessageLoop::AddTaskObserver(TaskObserver* task_observer) {
willchan@chromium.orga9047632010-06-10 06:20:41 +0900197 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900198 task_observers_.AddObserver(task_observer);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900199}
200
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900201void MessageLoop::RemoveTaskObserver(TaskObserver* task_observer) {
willchan@chromium.orga9047632010-06-10 06:20:41 +0900202 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900203 task_observers_.RemoveObserver(task_observer);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900204}
205
darin@google.com6ddeb842008-08-15 16:31:20 +0900206void MessageLoop::Run() {
darin@google.com981f3552008-08-16 12:09:05 +0900207 AutoRunState save_state(this);
208 RunHandler();
darin@google.com6ddeb842008-08-15 16:31:20 +0900209}
210
jar@google.com9239e022008-07-31 22:10:20 +0900211void MessageLoop::RunAllPending() {
darin@google.com981f3552008-08-16 12:09:05 +0900212 AutoRunState save_state(this);
213 state_->quit_received = true; // Means run until we would otherwise block.
214 RunHandler();
initial.commit3f4a7322008-07-27 06:49:38 +0900215}
216
217// Runs the loop in two different SEH modes:
218// enable_SEH_restoration_ = false : any unhandled exception goes to the last
219// one that calls SetUnhandledExceptionFilter().
220// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
221// that was existed before the loop was run.
darin@google.com981f3552008-08-16 12:09:05 +0900222void MessageLoop::RunHandler() {
223#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +0900224 if (exception_restoration_) {
stoyan@google.com283facb2009-10-27 03:15:59 +0900225 RunInternalInSEHFrame();
darin@google.com981f3552008-08-16 12:09:05 +0900226 return;
initial.commit3f4a7322008-07-27 06:49:38 +0900227 }
darin@google.com981f3552008-08-16 12:09:05 +0900228#endif
229
230 RunInternal();
initial.commit3f4a7322008-07-27 06:49:38 +0900231}
stoyan@google.com283facb2009-10-27 03:15:59 +0900232//------------------------------------------------------------------------------
233#if defined(OS_WIN)
234__declspec(noinline) void MessageLoop::RunInternalInSEHFrame() {
235 LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
236 __try {
237 RunInternal();
238 } __except(SEHFilter(current_filter)) {
239 }
240 return;
241}
242#endif
initial.commit3f4a7322008-07-27 06:49:38 +0900243//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900244
darin@google.com981f3552008-08-16 12:09:05 +0900245void MessageLoop::RunInternal() {
246 DCHECK(this == current());
247
initial.commit3f4a7322008-07-27 06:49:38 +0900248 StartHistogrammer();
249
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900250#if !defined(OS_MACOSX)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900251 if (state_->dispatcher && type() == TYPE_UI) {
252 static_cast<base::MessagePumpForUI*>(pump_.get())->
253 RunWithDispatcher(this, state_->dispatcher);
darin@google.com981f3552008-08-16 12:09:05 +0900254 return;
jar@google.com9239e022008-07-31 22:10:20 +0900255 }
darin@google.com981f3552008-08-16 12:09:05 +0900256#endif
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900257
darin@google.com981f3552008-08-16 12:09:05 +0900258 pump_->Run(this);
jar@google.comfbaaf692008-07-30 16:50:53 +0900259}
jar@google.com7ff36e62008-07-30 15:58:56 +0900260
jar@google.comb4d1bff2008-07-31 04:03:59 +0900261//------------------------------------------------------------------------------
262// Wrapper functions for use in above message loop framework.
263
initial.commit3f4a7322008-07-27 06:49:38 +0900264bool MessageLoop::ProcessNextDelayedNonNestableTask() {
darin@google.com981f3552008-08-16 12:09:05 +0900265 if (state_->run_depth != 1)
initial.commit3f4a7322008-07-27 06:49:38 +0900266 return false;
267
darin@google.combe165ae2008-09-07 17:08:29 +0900268 if (deferred_non_nestable_work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900269 return false;
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900270
darin@google.combe165ae2008-09-07 17:08:29 +0900271 Task* task = deferred_non_nestable_work_queue_.front().task;
272 deferred_non_nestable_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900273
darin@google.combe165ae2008-09-07 17:08:29 +0900274 RunTask(task);
initial.commit3f4a7322008-07-27 06:49:38 +0900275 return true;
276}
277
initial.commit3f4a7322008-07-27 06:49:38 +0900278//------------------------------------------------------------------------------
279
280void MessageLoop::Quit() {
darin@google.com981f3552008-08-16 12:09:05 +0900281 DCHECK(current() == this);
282 if (state_) {
283 state_->quit_received = true;
284 } else {
285 NOTREACHED() << "Must be inside Run to call Quit";
initial.commit3f4a7322008-07-27 06:49:38 +0900286 }
initial.commit3f4a7322008-07-27 06:49:38 +0900287}
288
darin@chromium.orgd70a12c2010-02-23 16:12:22 +0900289void MessageLoop::QuitNow() {
290 DCHECK(current() == this);
291 if (state_) {
292 pump_->Quit();
293 } else {
294 NOTREACHED() << "Must be inside Run to call Quit";
295 }
296}
297
darin@google.combe165ae2008-09-07 17:08:29 +0900298void MessageLoop::PostTask(
299 const tracked_objects::Location& from_here, Task* task) {
300 PostTask_Helper(from_here, task, 0, true);
301}
302
303void MessageLoop::PostDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900304 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
darin@google.combe165ae2008-09-07 17:08:29 +0900305 PostTask_Helper(from_here, task, delay_ms, true);
306}
307
308void MessageLoop::PostNonNestableTask(
309 const tracked_objects::Location& from_here, Task* task) {
310 PostTask_Helper(from_here, task, 0, false);
311}
312
313void MessageLoop::PostNonNestableDelayedTask(
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, false);
316}
317
initial.commit3f4a7322008-07-27 06:49:38 +0900318// Possibly called on a background thread!
darin@google.combe165ae2008-09-07 17:08:29 +0900319void MessageLoop::PostTask_Helper(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900320 const tracked_objects::Location& from_here, Task* task, int64 delay_ms,
darin@google.combe165ae2008-09-07 17:08:29 +0900321 bool nestable) {
initial.commit3f4a7322008-07-27 06:49:38 +0900322 task->SetBirthPlace(from_here);
darin@google.com0795f572008-08-30 09:22:48 +0900323
darin@google.combe165ae2008-09-07 17:08:29 +0900324 PendingTask pending_task(task, nestable);
darin@google.com0795f572008-08-30 09:22:48 +0900325
326 if (delay_ms > 0) {
darin@google.combe165ae2008-09-07 17:08:29 +0900327 pending_task.delayed_run_time =
darin@google.com0795f572008-08-30 09:22:48 +0900328 Time::Now() + TimeDelta::FromMilliseconds(delay_ms);
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900329
330#if defined(OS_WIN)
331 if (high_resolution_timer_expiration_.is_null()) {
332 // Windows timers are granular to 15.6ms. If we only set high-res
333 // timers for those under 15.6ms, then a 18ms timer ticks at ~32ms,
334 // which as a percentage is pretty inaccurate. So enable high
335 // res timers for any timer which is within 2x of the granularity.
336 // This is a tradeoff between accuracy and power management.
337 bool needs_high_res_timers =
338 delay_ms < (2 * Time::kMinLowResolutionThresholdMs);
339 if (needs_high_res_timers) {
340 Time::ActivateHighResolutionTimer(true);
341 high_resolution_timer_expiration_ = base::TimeTicks::Now() +
342 TimeDelta::FromMilliseconds(kHighResolutionTimerModeLeaseTimeMs);
343 }
344 }
345#endif
darin@google.com0795f572008-08-30 09:22:48 +0900346 } else {
jar@chromium.orged5238a2009-12-28 15:59:52 +0900347 DCHECK_EQ(delay_ms, 0) << "delay should not be negative";
darin@google.com0795f572008-08-30 09:22:48 +0900348 }
349
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900350#if defined(OS_WIN)
351 if (!high_resolution_timer_expiration_.is_null()) {
352 if (base::TimeTicks::Now() > high_resolution_timer_expiration_) {
353 Time::ActivateHighResolutionTimer(false);
354 high_resolution_timer_expiration_ = base::TimeTicks();
355 }
356 }
357#endif
358
initial.commit3f4a7322008-07-27 06:49:38 +0900359 // Warning: Don't try to short-circuit, and handle this thread's tasks more
360 // directly, as it could starve handling of foreign threads. Put every task
361 // into this queue.
362
darin@google.com981f3552008-08-16 12:09:05 +0900363 scoped_refptr<base::MessagePump> pump;
initial.commit3f4a7322008-07-27 06:49:38 +0900364 {
darin@google.com981f3552008-08-16 12:09:05 +0900365 AutoLock locked(incoming_queue_lock_);
366
darin@google.combe165ae2008-09-07 17:08:29 +0900367 bool was_empty = incoming_queue_.empty();
368 incoming_queue_.push(pending_task);
initial.commit3f4a7322008-07-27 06:49:38 +0900369 if (!was_empty)
370 return; // Someone else should have started the sub-pump.
371
darin@google.com981f3552008-08-16 12:09:05 +0900372 pump = pump_;
darin@google.com6ddeb842008-08-15 16:31:20 +0900373 }
darin@google.com981f3552008-08-16 12:09:05 +0900374 // Since the incoming_queue_ may contain a task that destroys this message
375 // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
376 // We use a stack-based reference to the message pump so that we can call
377 // ScheduleWork outside of incoming_queue_lock_.
darin@google.com6ddeb842008-08-15 16:31:20 +0900378
darin@google.com981f3552008-08-16 12:09:05 +0900379 pump->ScheduleWork();
initial.commit3f4a7322008-07-27 06:49:38 +0900380}
381
382void MessageLoop::SetNestableTasksAllowed(bool allowed) {
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900383 if (nestable_tasks_allowed_ != allowed) {
384 nestable_tasks_allowed_ = allowed;
385 if (!nestable_tasks_allowed_)
386 return;
387 // Start the native pump if we are not already pumping.
darin@google.com981f3552008-08-16 12:09:05 +0900388 pump_->ScheduleWork();
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900389 }
initial.commit3f4a7322008-07-27 06:49:38 +0900390}
391
392bool MessageLoop::NestableTasksAllowed() const {
393 return nestable_tasks_allowed_;
394}
395
jcampan@chromium.orgeac57172009-07-02 04:53:59 +0900396bool MessageLoop::IsNested() {
397 return state_->run_depth > 1;
398}
399
initial.commit3f4a7322008-07-27 06:49:38 +0900400//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900401
initial.commit3f4a7322008-07-27 06:49:38 +0900402void MessageLoop::RunTask(Task* task) {
initial.commit3f4a7322008-07-27 06:49:38 +0900403 DCHECK(nestable_tasks_allowed_);
404 // Execute the task and assume the worst: It is probably not reentrant.
405 nestable_tasks_allowed_ = false;
darin@google.combe165ae2008-09-07 17:08:29 +0900406
407 HistogramEvent(kTaskRunEvent);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900408 FOR_EACH_OBSERVER(TaskObserver, task_observers_,
409 WillProcessTask(task->tracked_birth_time()));
darin@google.combe165ae2008-09-07 17:08:29 +0900410 task->Run();
willchan@chromium.orga9047632010-06-10 06:20:41 +0900411 FOR_EACH_OBSERVER(TaskObserver, task_observers_, DidProcessTask());
darin@google.combe165ae2008-09-07 17:08:29 +0900412 delete task;
413
414 nestable_tasks_allowed_ = true;
initial.commit3f4a7322008-07-27 06:49:38 +0900415}
416
darin@google.combe165ae2008-09-07 17:08:29 +0900417bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) {
418 if (pending_task.nestable || state_->run_depth == 1) {
419 RunTask(pending_task.task);
420 // Show that we ran a task (Note: a new one might arrive as a
421 // consequence!).
422 return true;
423 }
424
425 // We couldn't run the task now because we're in a nested message loop
426 // and the task isn't nestable.
427 deferred_non_nestable_work_queue_.push(pending_task);
428 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900429}
430
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900431void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
432 // Move to the delayed work queue. Initialize the sequence number
433 // before inserting into the delayed_work_queue_. The sequence number
434 // is used to faciliate FIFO sorting when two tasks have the same
435 // delayed_run_time value.
436 PendingTask new_pending_task(pending_task);
437 new_pending_task.sequence_num = next_sequence_num_++;
438 delayed_work_queue_.push(new_pending_task);
439}
440
initial.commit3f4a7322008-07-27 06:49:38 +0900441void MessageLoop::ReloadWorkQueue() {
442 // We can improve performance of our loading tasks from incoming_queue_ to
darin@google.com981f3552008-08-16 12:09:05 +0900443 // work_queue_ by waiting until the last minute (work_queue_ is empty) to
444 // load. That reduces the number of locks-per-task significantly when our
darin@google.combe165ae2008-09-07 17:08:29 +0900445 // queues get large.
446 if (!work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900447 return; // Wait till we *really* need to lock and load.
448
449 // Acquire all we can from the inter-thread queue with one lock acquisition.
initial.commit3f4a7322008-07-27 06:49:38 +0900450 {
451 AutoLock lock(incoming_queue_lock_);
darin@google.combe165ae2008-09-07 17:08:29 +0900452 if (incoming_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900453 return;
darin@chromium.orgb80ef1a2009-09-03 05:05:21 +0900454 incoming_queue_.Swap(&work_queue_); // Constant time
darin@google.combe165ae2008-09-07 17:08:29 +0900455 DCHECK(incoming_queue_.empty());
initial.commit3f4a7322008-07-27 06:49:38 +0900456 }
457}
458
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900459bool MessageLoop::DeletePendingTasks() {
460 bool did_work = !work_queue_.empty();
461 while (!work_queue_.empty()) {
462 PendingTask pending_task = work_queue_.front();
463 work_queue_.pop();
464 if (!pending_task.delayed_run_time.is_null()) {
465 // We want to delete delayed tasks in the same order in which they would
466 // normally be deleted in case of any funny dependencies between delayed
467 // tasks.
468 AddToDelayedWorkQueue(pending_task);
469 } else {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900470 // TODO(darin): Delete all tasks once it is safe to do so.
471 // Until it is totally safe, just do it when running Purify or
472 // Valgrind.
473#if defined(PURIFY)
jar@chromium.org63772352009-03-12 05:06:02 +0900474 delete pending_task.task;
akalin@chromium.org839060b2010-08-03 12:06:21 +0900475#elif defined(OS_POSIX)
476 if (RUNNING_ON_VALGRIND)
477 delete pending_task.task;
478#endif // defined(OS_POSIX)
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900479 }
initial.commit3f4a7322008-07-27 06:49:38 +0900480 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900481 did_work |= !deferred_non_nestable_work_queue_.empty();
482 while (!deferred_non_nestable_work_queue_.empty()) {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900483 // TODO(darin): Delete all tasks once it is safe to do so.
484 // Until it is totaly safe, only delete them under Purify and Valgrind.
485 Task* task = NULL;
486#if defined(PURIFY)
487 task = deferred_non_nestable_work_queue_.front().task;
488#elif defined(OS_POSIX)
489 if (RUNNING_ON_VALGRIND)
490 task = deferred_non_nestable_work_queue_.front().task;
491#endif
jar@chromium.org2fa6b4b2009-03-12 04:53:50 +0900492 deferred_non_nestable_work_queue_.pop();
akalin@chromium.org839060b2010-08-03 12:06:21 +0900493 if (task)
494 delete task;
initial.commit3f4a7322008-07-27 06:49:38 +0900495 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900496 did_work |= !delayed_work_queue_.empty();
497 while (!delayed_work_queue_.empty()) {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900498 Task* task = delayed_work_queue_.top().task;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900499 delayed_work_queue_.pop();
akalin@chromium.org839060b2010-08-03 12:06:21 +0900500 delete task;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900501 }
502 return did_work;
initial.commit3f4a7322008-07-27 06:49:38 +0900503}
504
darin@google.com981f3552008-08-16 12:09:05 +0900505bool MessageLoop::DoWork() {
darin@google.combe165ae2008-09-07 17:08:29 +0900506 if (!nestable_tasks_allowed_) {
507 // Task can't be executed right now.
508 return false;
509 }
510
511 for (;;) {
512 ReloadWorkQueue();
513 if (work_queue_.empty())
514 break;
515
516 // Execute oldest task.
517 do {
518 PendingTask pending_task = work_queue_.front();
519 work_queue_.pop();
520 if (!pending_task.delayed_run_time.is_null()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900521 AddToDelayedWorkQueue(pending_task);
darin@chromium.orgb2d33452008-09-24 04:19:20 +0900522 // If we changed the topmost task, then it is time to re-schedule.
523 if (delayed_work_queue_.top().task == pending_task.task)
darin@google.combe165ae2008-09-07 17:08:29 +0900524 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
525 } else {
526 if (DeferOrRunPendingTask(pending_task))
527 return true;
528 }
529 } while (!work_queue_.empty());
530 }
531
532 // Nothing happened.
533 return false;
darin@google.com981f3552008-08-16 12:09:05 +0900534}
535
darin@google.com6393bed2008-08-20 15:30:58 +0900536bool MessageLoop::DoDelayedWork(Time* next_delayed_work_time) {
darin@google.combe165ae2008-09-07 17:08:29 +0900537 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
538 *next_delayed_work_time = Time();
539 return false;
540 }
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900541
darin@google.combe165ae2008-09-07 17:08:29 +0900542 if (delayed_work_queue_.top().delayed_run_time > Time::Now()) {
543 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
544 return false;
545 }
darin@google.com981f3552008-08-16 12:09:05 +0900546
darin@google.combe165ae2008-09-07 17:08:29 +0900547 PendingTask pending_task = delayed_work_queue_.top();
548 delayed_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900549
darin@google.combe165ae2008-09-07 17:08:29 +0900550 if (!delayed_work_queue_.empty())
551 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
darin@google.com981f3552008-08-16 12:09:05 +0900552
darin@google.combe165ae2008-09-07 17:08:29 +0900553 return DeferOrRunPendingTask(pending_task);
darin@google.com981f3552008-08-16 12:09:05 +0900554}
555
556bool MessageLoop::DoIdleWork() {
557 if (ProcessNextDelayedNonNestableTask())
558 return true;
559
560 if (state_->quit_received)
561 pump_->Quit();
562
563 return false;
564}
565
566//------------------------------------------------------------------------------
567// MessageLoop::AutoRunState
568
569MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
570 // Make the loop reference us.
571 previous_state_ = loop_->state_;
572 if (previous_state_) {
573 run_depth = previous_state_->run_depth + 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900574 } else {
darin@google.com981f3552008-08-16 12:09:05 +0900575 run_depth = 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900576 }
darin@google.com981f3552008-08-16 12:09:05 +0900577 loop_->state_ = this;
578
579 // Initialize the other fields:
580 quit_received = false;
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900581#if !defined(OS_MACOSX)
darin@google.com981f3552008-08-16 12:09:05 +0900582 dispatcher = NULL;
583#endif
584}
585
586MessageLoop::AutoRunState::~AutoRunState() {
587 loop_->state_ = previous_state_;
darin@google.comee6fa722008-08-13 08:25:43 +0900588}
589
initial.commit3f4a7322008-07-27 06:49:38 +0900590//------------------------------------------------------------------------------
darin@google.combe165ae2008-09-07 17:08:29 +0900591// MessageLoop::PendingTask
initial.commit3f4a7322008-07-27 06:49:38 +0900592
darin@google.combe165ae2008-09-07 17:08:29 +0900593bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
594 // Since the top of a priority queue is defined as the "greatest" element, we
595 // need to invert the comparison here. We want the smaller time to be at the
596 // top of the heap.
initial.commit3f4a7322008-07-27 06:49:38 +0900597
darin@google.combe165ae2008-09-07 17:08:29 +0900598 if (delayed_run_time < other.delayed_run_time)
599 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900600
darin@google.combe165ae2008-09-07 17:08:29 +0900601 if (delayed_run_time > other.delayed_run_time)
602 return true;
initial.commit3f4a7322008-07-27 06:49:38 +0900603
darin@google.combe165ae2008-09-07 17:08:29 +0900604 // If the times happen to match, then we use the sequence number to decide.
605 // Compare the difference to support integer roll-over.
606 return (sequence_num - other.sequence_num) > 0;
initial.commit3f4a7322008-07-27 06:49:38 +0900607}
608
609//------------------------------------------------------------------------------
610// Method and data for histogramming events and actions taken by each instance
611// on each thread.
612
613// static
initial.commit3f4a7322008-07-27 06:49:38 +0900614void MessageLoop::EnableHistogrammer(bool enable) {
615 enable_histogrammer_ = enable;
616}
617
618void MessageLoop::StartHistogrammer() {
619 if (enable_histogrammer_ && !message_histogram_.get()
brettw@chromium.org275c2ec2010-10-14 13:38:38 +0900620 && base::StatisticsRecorder::WasStarted()) {
darin@google.com981f3552008-08-16 12:09:05 +0900621 DCHECK(!thread_name_.empty());
brettw@chromium.org275c2ec2010-10-14 13:38:38 +0900622 message_histogram_ = base::LinearHistogram::FactoryGet(
623 "MsgLoop:" + thread_name_,
jar@chromium.orged5238a2009-12-28 15:59:52 +0900624 kLeastNonZeroMessageId, kMaxMessageId,
625 kNumberOfDistinctMessagesDisplayed,
626 message_histogram_->kHexRangePrintingFlag);
initial.commit3f4a7322008-07-27 06:49:38 +0900627 message_histogram_->SetRangeDescriptions(event_descriptions_);
628 }
629}
630
631void MessageLoop::HistogramEvent(int event) {
632 if (message_histogram_.get())
633 message_histogram_->Add(event);
634}
635
darin@google.comd936b5b2008-08-26 14:53:57 +0900636//------------------------------------------------------------------------------
637// MessageLoopForUI
638
639#if defined(OS_WIN)
darin@google.comd936b5b2008-08-26 14:53:57 +0900640void MessageLoopForUI::DidProcessMessage(const MSG& message) {
641 pump_win()->DidProcessMessage(message);
642}
darin@google.comd936b5b2008-08-26 14:53:57 +0900643#endif // defined(OS_WIN)
644
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900645#if !defined(OS_MACOSX)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900646void MessageLoopForUI::AddObserver(Observer* observer) {
647 pump_ui()->AddObserver(observer);
648}
649
650void MessageLoopForUI::RemoveObserver(Observer* observer) {
651 pump_ui()->RemoveObserver(observer);
652}
653
654void MessageLoopForUI::Run(Dispatcher* dispatcher) {
655 AutoRunState save_state(this);
656 state_->dispatcher = dispatcher;
657 RunHandler();
658}
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900659#endif // !defined(OS_MACOSX)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900660
darin@google.comd936b5b2008-08-26 14:53:57 +0900661//------------------------------------------------------------------------------
662// MessageLoopForIO
663
664#if defined(OS_WIN)
665
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900666void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
667 pump_io()->RegisterIOHandler(file, handler);
668}
669
rvargas@google.com73887542008-11-08 06:52:15 +0900670bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
671 return pump_io()->WaitForIOCompletion(timeout, filter);
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900672}
673
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900674#elif defined(OS_POSIX)
675
jeremy@chromium.orgefc0db02008-12-16 07:02:17 +0900676bool MessageLoopForIO::WatchFileDescriptor(int fd,
677 bool persistent,
678 Mode mode,
679 FileDescriptorWatcher *controller,
680 Watcher *delegate) {
681 return pump_libevent()->WatchFileDescriptor(
682 fd,
683 persistent,
684 static_cast<base::MessagePumpLibevent::Mode>(mode),
685 controller,
686 delegate);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900687}
688
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900689#endif