blob: f335ca1dba8168c336f119bdc84ec82d02f0b09c [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
rjkroege@google.com3080f442010-10-23 01:17:47 +090026#if defined(TOUCH_UI)
27#include "base/message_pump_glib_x.h"
28#endif
dkegel@google.com9e044ae2008-09-19 03:46:26 +090029
dsh@google.com0f8dd262008-10-28 05:43:33 +090030using base::Time;
31using base::TimeDelta;
32
erg@chromium.orga7528522010-07-16 02:23:23 +090033namespace {
34
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090035// A lazily created thread local storage for quick access to a thread's message
36// loop, if one exists. This should be safe and free of static constructors.
erg@chromium.orga7528522010-07-16 02:23:23 +090037base::LazyInstance<base::ThreadLocalPointer<MessageLoop> > lazy_tls_ptr(
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090038 base::LINKER_INITIALIZED);
initial.commit3f4a7322008-07-27 06:49:38 +090039
initial.commit3f4a7322008-07-27 06:49:38 +090040// Logical events for Histogram profiling. Run with -message-loop-histogrammer
41// to get an accounting of messages and actions taken on each thread.
erg@chromium.orga7528522010-07-16 02:23:23 +090042const int kTaskRunEvent = 0x1;
43const int kTimerEvent = 0x2;
initial.commit3f4a7322008-07-27 06:49:38 +090044
45// Provide range of message IDs for use in histogramming and debug display.
erg@chromium.orga7528522010-07-16 02:23:23 +090046const int kLeastNonZeroMessageId = 1;
47const int kMaxMessageId = 1099;
48const int kNumberOfDistinctMessagesDisplayed = 1100;
49
50// Provide a macro that takes an expression (such as a constant, or macro
51// constant) and creates a pair to initalize an array of pairs. In this case,
52// our pair consists of the expressions value, and the "stringized" version
53// of the expression (i.e., the exrpression put in quotes). For example, if
54// we have:
55// #define FOO 2
56// #define BAR 5
57// then the following:
58// VALUE_TO_NUMBER_AND_NAME(FOO + BAR)
59// will expand to:
60// {7, "FOO + BAR"}
61// We use the resulting array as an argument to our histogram, which reads the
62// number as a bucket identifier, and proceeds to use the corresponding name
63// in the pair (i.e., the quoted string) when printing out a histogram.
64#define VALUE_TO_NUMBER_AND_NAME(name) {name, #name},
65
brettw@chromium.org275c2ec2010-10-14 13:38:38 +090066const base::LinearHistogram::DescriptionPair event_descriptions_[] = {
erg@chromium.orga7528522010-07-16 02:23:23 +090067 // Provide some pretty print capability in our histogram for our internal
68 // messages.
69
70 // A few events we handle (kindred to messages), and used to profile actions.
71 VALUE_TO_NUMBER_AND_NAME(kTaskRunEvent)
72 VALUE_TO_NUMBER_AND_NAME(kTimerEvent)
73
74 {-1, NULL} // The list must be null terminated, per API to histogram.
75};
76
77bool enable_histogrammer_ = false;
78
79} // namespace
initial.commit3f4a7322008-07-27 06:49:38 +090080
81//------------------------------------------------------------------------------
82
darin@google.com981f3552008-08-16 12:09:05 +090083#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +090084
initial.commit3f4a7322008-07-27 06:49:38 +090085// Upon a SEH exception in this thread, it restores the original unhandled
86// exception filter.
87static int SEHFilter(LPTOP_LEVEL_EXCEPTION_FILTER old_filter) {
88 ::SetUnhandledExceptionFilter(old_filter);
89 return EXCEPTION_CONTINUE_SEARCH;
90}
91
92// Retrieves a pointer to the current unhandled exception filter. There
93// is no standalone getter method.
94static LPTOP_LEVEL_EXCEPTION_FILTER GetTopSEHFilter() {
95 LPTOP_LEVEL_EXCEPTION_FILTER top_filter = NULL;
96 top_filter = ::SetUnhandledExceptionFilter(0);
97 ::SetUnhandledExceptionFilter(top_filter);
98 return top_filter;
99}
100
darin@google.com981f3552008-08-16 12:09:05 +0900101#endif // defined(OS_WIN)
102
initial.commit3f4a7322008-07-27 06:49:38 +0900103//------------------------------------------------------------------------------
104
erg@chromium.org493f5f62010-07-16 06:03:54 +0900105MessageLoop::TaskObserver::TaskObserver() {
106}
107
108MessageLoop::TaskObserver::~TaskObserver() {
109}
110
111MessageLoop::DestructionObserver::~DestructionObserver() {
112}
113
114//------------------------------------------------------------------------------
115
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +0900116// static
117MessageLoop* MessageLoop::current() {
118 // TODO(darin): sadly, we cannot enable this yet since people call us even
119 // when they have no intention of using us.
erg@google.combf6ce9f2010-01-27 08:08:02 +0900120 // DCHECK(loop) << "Ouch, did you forget to initialize me?";
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +0900121 return lazy_tls_ptr.Pointer()->Get();
122}
123
darin@google.comd936b5b2008-08-26 14:53:57 +0900124MessageLoop::MessageLoop(Type type)
125 : type_(type),
darin@google.comee6fa722008-08-13 08:25:43 +0900126 nestable_tasks_allowed_(true),
darin@google.com12d40bb2008-08-20 03:36:23 +0900127 exception_restoration_(false),
darin@google.combe165ae2008-09-07 17:08:29 +0900128 state_(NULL),
129 next_sequence_num_(0) {
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +0900130 DCHECK(!current()) << "should only have one message loop per thread";
131 lazy_tls_ptr.Pointer()->Set(this);
darin@google.comd936b5b2008-08-26 14:53:57 +0900132
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900133// TODO(rvargas): Get rid of the OS guards.
darin@google.com981f3552008-08-16 12:09:05 +0900134#if defined(OS_WIN)
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900135#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
136#define MESSAGE_PUMP_IO new base::MessagePumpForIO()
137#elif defined(OS_MACOSX)
138#define MESSAGE_PUMP_UI base::MessagePumpMac::Create()
139#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
rjkroege@google.com3080f442010-10-23 01:17:47 +0900140#elif defined(TOUCH_UI)
141#define MESSAGE_PUMP_UI new base::MessagePumpGlibX()
142#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900143#elif defined(OS_POSIX) // POSIX but not MACOSX.
144#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
145#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900146#else
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900147#error Not implemented
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900148#endif
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900149
150 if (type_ == TYPE_UI) {
151 pump_ = MESSAGE_PUMP_UI;
dsh@google.com119a2522008-10-04 01:52:59 +0900152 } else if (type_ == TYPE_IO) {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900153 pump_ = MESSAGE_PUMP_IO;
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900154 } else {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900155 DCHECK_EQ(TYPE_DEFAULT, type_);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900156 pump_ = new base::MessagePumpDefault();
157 }
initial.commit3f4a7322008-07-27 06:49:38 +0900158}
159
160MessageLoop::~MessageLoop() {
161 DCHECK(this == current());
darin@google.com965e5342008-08-06 08:16:41 +0900162
163 // Let interested parties have one last shot at accessing this.
164 FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
165 WillDestroyCurrentMessageLoop());
166
darin@google.com0e500502008-09-09 14:55:35 +0900167 DCHECK(!state_);
168
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900169 // Clean up any unprocessed tasks, but take care: deleting a task could
170 // result in the addition of more tasks (e.g., via DeleteSoon). We set a
171 // limit on the number of times we will allow a deleted task to generate more
172 // tasks. Normally, we should only pass through this loop once or twice. If
173 // we end up hitting the loop limit, then it is probably due to one task that
174 // is being stubborn. Inspect the queues to see who is left.
175 bool did_work;
176 for (int i = 0; i < 100; ++i) {
177 DeletePendingTasks();
178 ReloadWorkQueue();
179 // If we end up with empty queues, then break out of the loop.
180 did_work = DeletePendingTasks();
181 if (!did_work)
182 break;
darin@google.com0e500502008-09-09 14:55:35 +0900183 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900184 DCHECK(!did_work);
185
186 // OK, now make it so that no one can find us.
deanm@chromium.orge4cc5922008-09-10 20:14:56 +0900187 lazy_tls_ptr.Pointer()->Set(NULL);
initial.commit3f4a7322008-07-27 06:49:38 +0900188}
189
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900190void MessageLoop::AddDestructionObserver(
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_.AddObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900194}
195
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900196void MessageLoop::RemoveDestructionObserver(
197 DestructionObserver* destruction_observer) {
darin@google.com965e5342008-08-06 08:16:41 +0900198 DCHECK(this == current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900199 destruction_observers_.RemoveObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900200}
201
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900202void MessageLoop::AddTaskObserver(TaskObserver* task_observer) {
willchan@chromium.orga9047632010-06-10 06:20:41 +0900203 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900204 task_observers_.AddObserver(task_observer);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900205}
206
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900207void MessageLoop::RemoveTaskObserver(TaskObserver* task_observer) {
willchan@chromium.orga9047632010-06-10 06:20:41 +0900208 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900209 task_observers_.RemoveObserver(task_observer);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900210}
211
darin@google.com6ddeb842008-08-15 16:31:20 +0900212void MessageLoop::Run() {
darin@google.com981f3552008-08-16 12:09:05 +0900213 AutoRunState save_state(this);
214 RunHandler();
darin@google.com6ddeb842008-08-15 16:31:20 +0900215}
216
jar@google.com9239e022008-07-31 22:10:20 +0900217void MessageLoop::RunAllPending() {
darin@google.com981f3552008-08-16 12:09:05 +0900218 AutoRunState save_state(this);
219 state_->quit_received = true; // Means run until we would otherwise block.
220 RunHandler();
initial.commit3f4a7322008-07-27 06:49:38 +0900221}
222
223// Runs the loop in two different SEH modes:
224// enable_SEH_restoration_ = false : any unhandled exception goes to the last
225// one that calls SetUnhandledExceptionFilter().
226// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
227// that was existed before the loop was run.
darin@google.com981f3552008-08-16 12:09:05 +0900228void MessageLoop::RunHandler() {
229#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +0900230 if (exception_restoration_) {
stoyan@google.com283facb2009-10-27 03:15:59 +0900231 RunInternalInSEHFrame();
darin@google.com981f3552008-08-16 12:09:05 +0900232 return;
initial.commit3f4a7322008-07-27 06:49:38 +0900233 }
darin@google.com981f3552008-08-16 12:09:05 +0900234#endif
235
236 RunInternal();
initial.commit3f4a7322008-07-27 06:49:38 +0900237}
stoyan@google.com283facb2009-10-27 03:15:59 +0900238//------------------------------------------------------------------------------
239#if defined(OS_WIN)
240__declspec(noinline) void MessageLoop::RunInternalInSEHFrame() {
241 LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
242 __try {
243 RunInternal();
244 } __except(SEHFilter(current_filter)) {
245 }
246 return;
247}
248#endif
initial.commit3f4a7322008-07-27 06:49:38 +0900249//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900250
darin@google.com981f3552008-08-16 12:09:05 +0900251void MessageLoop::RunInternal() {
252 DCHECK(this == current());
253
initial.commit3f4a7322008-07-27 06:49:38 +0900254 StartHistogrammer();
255
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900256#if !defined(OS_MACOSX)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900257 if (state_->dispatcher && type() == TYPE_UI) {
258 static_cast<base::MessagePumpForUI*>(pump_.get())->
259 RunWithDispatcher(this, state_->dispatcher);
darin@google.com981f3552008-08-16 12:09:05 +0900260 return;
jar@google.com9239e022008-07-31 22:10:20 +0900261 }
darin@google.com981f3552008-08-16 12:09:05 +0900262#endif
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900263
darin@google.com981f3552008-08-16 12:09:05 +0900264 pump_->Run(this);
jar@google.comfbaaf692008-07-30 16:50:53 +0900265}
jar@google.com7ff36e62008-07-30 15:58:56 +0900266
jar@google.comb4d1bff2008-07-31 04:03:59 +0900267//------------------------------------------------------------------------------
268// Wrapper functions for use in above message loop framework.
269
initial.commit3f4a7322008-07-27 06:49:38 +0900270bool MessageLoop::ProcessNextDelayedNonNestableTask() {
darin@google.com981f3552008-08-16 12:09:05 +0900271 if (state_->run_depth != 1)
initial.commit3f4a7322008-07-27 06:49:38 +0900272 return false;
273
darin@google.combe165ae2008-09-07 17:08:29 +0900274 if (deferred_non_nestable_work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900275 return false;
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900276
darin@google.combe165ae2008-09-07 17:08:29 +0900277 Task* task = deferred_non_nestable_work_queue_.front().task;
278 deferred_non_nestable_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900279
darin@google.combe165ae2008-09-07 17:08:29 +0900280 RunTask(task);
initial.commit3f4a7322008-07-27 06:49:38 +0900281 return true;
282}
283
initial.commit3f4a7322008-07-27 06:49:38 +0900284//------------------------------------------------------------------------------
285
286void MessageLoop::Quit() {
darin@google.com981f3552008-08-16 12:09:05 +0900287 DCHECK(current() == this);
288 if (state_) {
289 state_->quit_received = true;
290 } else {
291 NOTREACHED() << "Must be inside Run to call Quit";
initial.commit3f4a7322008-07-27 06:49:38 +0900292 }
initial.commit3f4a7322008-07-27 06:49:38 +0900293}
294
darin@chromium.orgd70a12c2010-02-23 16:12:22 +0900295void MessageLoop::QuitNow() {
296 DCHECK(current() == this);
297 if (state_) {
298 pump_->Quit();
299 } else {
300 NOTREACHED() << "Must be inside Run to call Quit";
301 }
302}
303
darin@google.combe165ae2008-09-07 17:08:29 +0900304void MessageLoop::PostTask(
305 const tracked_objects::Location& from_here, Task* task) {
306 PostTask_Helper(from_here, task, 0, true);
307}
308
309void MessageLoop::PostDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900310 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
darin@google.combe165ae2008-09-07 17:08:29 +0900311 PostTask_Helper(from_here, task, delay_ms, true);
312}
313
314void MessageLoop::PostNonNestableTask(
315 const tracked_objects::Location& from_here, Task* task) {
316 PostTask_Helper(from_here, task, 0, false);
317}
318
319void MessageLoop::PostNonNestableDelayedTask(
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 PostTask_Helper(from_here, task, delay_ms, false);
322}
323
initial.commit3f4a7322008-07-27 06:49:38 +0900324// Possibly called on a background thread!
darin@google.combe165ae2008-09-07 17:08:29 +0900325void MessageLoop::PostTask_Helper(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900326 const tracked_objects::Location& from_here, Task* task, int64 delay_ms,
darin@google.combe165ae2008-09-07 17:08:29 +0900327 bool nestable) {
initial.commit3f4a7322008-07-27 06:49:38 +0900328 task->SetBirthPlace(from_here);
darin@google.com0795f572008-08-30 09:22:48 +0900329
darin@google.combe165ae2008-09-07 17:08:29 +0900330 PendingTask pending_task(task, nestable);
darin@google.com0795f572008-08-30 09:22:48 +0900331
332 if (delay_ms > 0) {
darin@google.combe165ae2008-09-07 17:08:29 +0900333 pending_task.delayed_run_time =
darin@google.com0795f572008-08-30 09:22:48 +0900334 Time::Now() + TimeDelta::FromMilliseconds(delay_ms);
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900335
336#if defined(OS_WIN)
337 if (high_resolution_timer_expiration_.is_null()) {
338 // Windows timers are granular to 15.6ms. If we only set high-res
339 // timers for those under 15.6ms, then a 18ms timer ticks at ~32ms,
340 // which as a percentage is pretty inaccurate. So enable high
341 // res timers for any timer which is within 2x of the granularity.
342 // This is a tradeoff between accuracy and power management.
343 bool needs_high_res_timers =
344 delay_ms < (2 * Time::kMinLowResolutionThresholdMs);
345 if (needs_high_res_timers) {
phajdan.jr@chromium.org3337f3d2010-10-20 19:50:38 +0900346 Time::ActivateHighResolutionTimer(true);
347 high_resolution_timer_expiration_ = base::TimeTicks::Now() +
348 TimeDelta::FromMilliseconds(kHighResolutionTimerModeLeaseTimeMs);
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900349 }
350 }
351#endif
darin@google.com0795f572008-08-30 09:22:48 +0900352 } else {
jar@chromium.orged5238a2009-12-28 15:59:52 +0900353 DCHECK_EQ(delay_ms, 0) << "delay should not be negative";
darin@google.com0795f572008-08-30 09:22:48 +0900354 }
355
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900356#if defined(OS_WIN)
357 if (!high_resolution_timer_expiration_.is_null()) {
358 if (base::TimeTicks::Now() > high_resolution_timer_expiration_) {
359 Time::ActivateHighResolutionTimer(false);
360 high_resolution_timer_expiration_ = base::TimeTicks();
361 }
362 }
363#endif
364
initial.commit3f4a7322008-07-27 06:49:38 +0900365 // Warning: Don't try to short-circuit, and handle this thread's tasks more
366 // directly, as it could starve handling of foreign threads. Put every task
367 // into this queue.
368
darin@google.com981f3552008-08-16 12:09:05 +0900369 scoped_refptr<base::MessagePump> pump;
initial.commit3f4a7322008-07-27 06:49:38 +0900370 {
darin@google.com981f3552008-08-16 12:09:05 +0900371 AutoLock locked(incoming_queue_lock_);
372
darin@google.combe165ae2008-09-07 17:08:29 +0900373 bool was_empty = incoming_queue_.empty();
374 incoming_queue_.push(pending_task);
initial.commit3f4a7322008-07-27 06:49:38 +0900375 if (!was_empty)
376 return; // Someone else should have started the sub-pump.
377
darin@google.com981f3552008-08-16 12:09:05 +0900378 pump = pump_;
darin@google.com6ddeb842008-08-15 16:31:20 +0900379 }
darin@google.com981f3552008-08-16 12:09:05 +0900380 // Since the incoming_queue_ may contain a task that destroys this message
381 // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
382 // We use a stack-based reference to the message pump so that we can call
383 // ScheduleWork outside of incoming_queue_lock_.
darin@google.com6ddeb842008-08-15 16:31:20 +0900384
darin@google.com981f3552008-08-16 12:09:05 +0900385 pump->ScheduleWork();
initial.commit3f4a7322008-07-27 06:49:38 +0900386}
387
388void MessageLoop::SetNestableTasksAllowed(bool allowed) {
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900389 if (nestable_tasks_allowed_ != allowed) {
390 nestable_tasks_allowed_ = allowed;
391 if (!nestable_tasks_allowed_)
392 return;
393 // Start the native pump if we are not already pumping.
darin@google.com981f3552008-08-16 12:09:05 +0900394 pump_->ScheduleWork();
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900395 }
initial.commit3f4a7322008-07-27 06:49:38 +0900396}
397
398bool MessageLoop::NestableTasksAllowed() const {
399 return nestable_tasks_allowed_;
400}
401
jcampan@chromium.orgeac57172009-07-02 04:53:59 +0900402bool MessageLoop::IsNested() {
403 return state_->run_depth > 1;
404}
405
initial.commit3f4a7322008-07-27 06:49:38 +0900406//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900407
initial.commit3f4a7322008-07-27 06:49:38 +0900408void MessageLoop::RunTask(Task* task) {
initial.commit3f4a7322008-07-27 06:49:38 +0900409 DCHECK(nestable_tasks_allowed_);
410 // Execute the task and assume the worst: It is probably not reentrant.
411 nestable_tasks_allowed_ = false;
darin@google.combe165ae2008-09-07 17:08:29 +0900412
413 HistogramEvent(kTaskRunEvent);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900414 FOR_EACH_OBSERVER(TaskObserver, task_observers_,
415 WillProcessTask(task->tracked_birth_time()));
darin@google.combe165ae2008-09-07 17:08:29 +0900416 task->Run();
willchan@chromium.orga9047632010-06-10 06:20:41 +0900417 FOR_EACH_OBSERVER(TaskObserver, task_observers_, DidProcessTask());
darin@google.combe165ae2008-09-07 17:08:29 +0900418 delete task;
419
420 nestable_tasks_allowed_ = true;
initial.commit3f4a7322008-07-27 06:49:38 +0900421}
422
darin@google.combe165ae2008-09-07 17:08:29 +0900423bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) {
424 if (pending_task.nestable || state_->run_depth == 1) {
425 RunTask(pending_task.task);
426 // Show that we ran a task (Note: a new one might arrive as a
427 // consequence!).
428 return true;
429 }
430
431 // We couldn't run the task now because we're in a nested message loop
432 // and the task isn't nestable.
433 deferred_non_nestable_work_queue_.push(pending_task);
434 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900435}
436
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900437void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
438 // Move to the delayed work queue. Initialize the sequence number
439 // before inserting into the delayed_work_queue_. The sequence number
440 // is used to faciliate FIFO sorting when two tasks have the same
441 // delayed_run_time value.
442 PendingTask new_pending_task(pending_task);
443 new_pending_task.sequence_num = next_sequence_num_++;
444 delayed_work_queue_.push(new_pending_task);
445}
446
initial.commit3f4a7322008-07-27 06:49:38 +0900447void MessageLoop::ReloadWorkQueue() {
448 // We can improve performance of our loading tasks from incoming_queue_ to
darin@google.com981f3552008-08-16 12:09:05 +0900449 // work_queue_ by waiting until the last minute (work_queue_ is empty) to
450 // load. That reduces the number of locks-per-task significantly when our
darin@google.combe165ae2008-09-07 17:08:29 +0900451 // queues get large.
452 if (!work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900453 return; // Wait till we *really* need to lock and load.
454
455 // Acquire all we can from the inter-thread queue with one lock acquisition.
initial.commit3f4a7322008-07-27 06:49:38 +0900456 {
457 AutoLock lock(incoming_queue_lock_);
darin@google.combe165ae2008-09-07 17:08:29 +0900458 if (incoming_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900459 return;
darin@chromium.orgb80ef1a2009-09-03 05:05:21 +0900460 incoming_queue_.Swap(&work_queue_); // Constant time
darin@google.combe165ae2008-09-07 17:08:29 +0900461 DCHECK(incoming_queue_.empty());
initial.commit3f4a7322008-07-27 06:49:38 +0900462 }
463}
464
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900465bool MessageLoop::DeletePendingTasks() {
466 bool did_work = !work_queue_.empty();
467 while (!work_queue_.empty()) {
468 PendingTask pending_task = work_queue_.front();
469 work_queue_.pop();
470 if (!pending_task.delayed_run_time.is_null()) {
471 // We want to delete delayed tasks in the same order in which they would
472 // normally be deleted in case of any funny dependencies between delayed
473 // tasks.
474 AddToDelayedWorkQueue(pending_task);
475 } else {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900476 // TODO(darin): Delete all tasks once it is safe to do so.
477 // Until it is totally safe, just do it when running Purify or
478 // Valgrind.
thestig@chromium.orgd4a0a922010-10-15 11:38:43 +0900479#if defined(PURIFY)
jar@chromium.org63772352009-03-12 05:06:02 +0900480 delete pending_task.task;
akalin@chromium.org839060b2010-08-03 12:06:21 +0900481#elif defined(OS_POSIX)
482 if (RUNNING_ON_VALGRIND)
483 delete pending_task.task;
484#endif // defined(OS_POSIX)
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900485 }
initial.commit3f4a7322008-07-27 06:49:38 +0900486 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900487 did_work |= !deferred_non_nestable_work_queue_.empty();
488 while (!deferred_non_nestable_work_queue_.empty()) {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900489 // TODO(darin): Delete all tasks once it is safe to do so.
490 // Until it is totaly safe, only delete them under Purify and Valgrind.
491 Task* task = NULL;
thestig@chromium.orgd4a0a922010-10-15 11:38:43 +0900492#if defined(PURIFY)
akalin@chromium.org839060b2010-08-03 12:06:21 +0900493 task = deferred_non_nestable_work_queue_.front().task;
494#elif defined(OS_POSIX)
495 if (RUNNING_ON_VALGRIND)
496 task = deferred_non_nestable_work_queue_.front().task;
497#endif
jar@chromium.org2fa6b4b2009-03-12 04:53:50 +0900498 deferred_non_nestable_work_queue_.pop();
akalin@chromium.org839060b2010-08-03 12:06:21 +0900499 if (task)
500 delete task;
initial.commit3f4a7322008-07-27 06:49:38 +0900501 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900502 did_work |= !delayed_work_queue_.empty();
503 while (!delayed_work_queue_.empty()) {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900504 Task* task = delayed_work_queue_.top().task;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900505 delayed_work_queue_.pop();
akalin@chromium.org839060b2010-08-03 12:06:21 +0900506 delete task;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900507 }
508 return did_work;
initial.commit3f4a7322008-07-27 06:49:38 +0900509}
510
darin@google.com981f3552008-08-16 12:09:05 +0900511bool MessageLoop::DoWork() {
darin@google.combe165ae2008-09-07 17:08:29 +0900512 if (!nestable_tasks_allowed_) {
513 // Task can't be executed right now.
514 return false;
515 }
516
517 for (;;) {
518 ReloadWorkQueue();
519 if (work_queue_.empty())
520 break;
521
522 // Execute oldest task.
523 do {
524 PendingTask pending_task = work_queue_.front();
525 work_queue_.pop();
526 if (!pending_task.delayed_run_time.is_null()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900527 AddToDelayedWorkQueue(pending_task);
darin@chromium.orgb2d33452008-09-24 04:19:20 +0900528 // If we changed the topmost task, then it is time to re-schedule.
jar@chromium.org40355072010-10-21 15:32:33 +0900529 if (delayed_work_queue_.top().task == pending_task.task)
darin@google.combe165ae2008-09-07 17:08:29 +0900530 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
531 } else {
532 if (DeferOrRunPendingTask(pending_task))
533 return true;
534 }
535 } while (!work_queue_.empty());
536 }
537
538 // Nothing happened.
539 return false;
darin@google.com981f3552008-08-16 12:09:05 +0900540}
541
rjkroege@google.com3080f442010-10-23 01:17:47 +0900542bool MessageLoop::DoDelayedWork(base::Time* next_delayed_work_time) {
jar@chromium.org40355072010-10-21 15:32:33 +0900543 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
rjkroege@google.com3080f442010-10-23 01:17:47 +0900544 *next_delayed_work_time = base::Time();
darin@google.combe165ae2008-09-07 17:08:29 +0900545 return false;
546 }
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900547
jar@chromium.org40355072010-10-21 15:32:33 +0900548 if (delayed_work_queue_.top().delayed_run_time > Time::Now()) {
549 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
550 return false;
darin@google.combe165ae2008-09-07 17:08:29 +0900551 }
darin@google.com981f3552008-08-16 12:09:05 +0900552
jar@chromium.org40355072010-10-21 15:32:33 +0900553 PendingTask pending_task = delayed_work_queue_.top();
554 delayed_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900555
jar@chromium.org40355072010-10-21 15:32:33 +0900556 if (!delayed_work_queue_.empty())
darin@google.combe165ae2008-09-07 17:08:29 +0900557 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
darin@google.com981f3552008-08-16 12:09:05 +0900558
darin@google.combe165ae2008-09-07 17:08:29 +0900559 return DeferOrRunPendingTask(pending_task);
darin@google.com981f3552008-08-16 12:09:05 +0900560}
561
562bool MessageLoop::DoIdleWork() {
563 if (ProcessNextDelayedNonNestableTask())
564 return true;
565
566 if (state_->quit_received)
567 pump_->Quit();
568
569 return false;
570}
571
572//------------------------------------------------------------------------------
573// MessageLoop::AutoRunState
574
575MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
576 // Make the loop reference us.
577 previous_state_ = loop_->state_;
578 if (previous_state_) {
579 run_depth = previous_state_->run_depth + 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900580 } else {
darin@google.com981f3552008-08-16 12:09:05 +0900581 run_depth = 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900582 }
darin@google.com981f3552008-08-16 12:09:05 +0900583 loop_->state_ = this;
584
585 // Initialize the other fields:
586 quit_received = false;
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900587#if !defined(OS_MACOSX)
darin@google.com981f3552008-08-16 12:09:05 +0900588 dispatcher = NULL;
589#endif
590}
591
592MessageLoop::AutoRunState::~AutoRunState() {
593 loop_->state_ = previous_state_;
darin@google.comee6fa722008-08-13 08:25:43 +0900594}
595
initial.commit3f4a7322008-07-27 06:49:38 +0900596//------------------------------------------------------------------------------
darin@google.combe165ae2008-09-07 17:08:29 +0900597// MessageLoop::PendingTask
initial.commit3f4a7322008-07-27 06:49:38 +0900598
darin@google.combe165ae2008-09-07 17:08:29 +0900599bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
600 // Since the top of a priority queue is defined as the "greatest" element, we
601 // need to invert the comparison here. We want the smaller time to be at the
602 // top of the heap.
initial.commit3f4a7322008-07-27 06:49:38 +0900603
darin@google.combe165ae2008-09-07 17:08:29 +0900604 if (delayed_run_time < other.delayed_run_time)
605 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900606
darin@google.combe165ae2008-09-07 17:08:29 +0900607 if (delayed_run_time > other.delayed_run_time)
608 return true;
initial.commit3f4a7322008-07-27 06:49:38 +0900609
darin@google.combe165ae2008-09-07 17:08:29 +0900610 // If the times happen to match, then we use the sequence number to decide.
611 // Compare the difference to support integer roll-over.
612 return (sequence_num - other.sequence_num) > 0;
initial.commit3f4a7322008-07-27 06:49:38 +0900613}
614
615//------------------------------------------------------------------------------
616// Method and data for histogramming events and actions taken by each instance
617// on each thread.
618
619// static
initial.commit3f4a7322008-07-27 06:49:38 +0900620void MessageLoop::EnableHistogrammer(bool enable) {
621 enable_histogrammer_ = enable;
622}
623
624void MessageLoop::StartHistogrammer() {
625 if (enable_histogrammer_ && !message_histogram_.get()
brettw@chromium.org275c2ec2010-10-14 13:38:38 +0900626 && base::StatisticsRecorder::WasStarted()) {
darin@google.com981f3552008-08-16 12:09:05 +0900627 DCHECK(!thread_name_.empty());
brettw@chromium.org275c2ec2010-10-14 13:38:38 +0900628 message_histogram_ = base::LinearHistogram::FactoryGet(
629 "MsgLoop:" + thread_name_,
jar@chromium.orged5238a2009-12-28 15:59:52 +0900630 kLeastNonZeroMessageId, kMaxMessageId,
631 kNumberOfDistinctMessagesDisplayed,
632 message_histogram_->kHexRangePrintingFlag);
initial.commit3f4a7322008-07-27 06:49:38 +0900633 message_histogram_->SetRangeDescriptions(event_descriptions_);
634 }
635}
636
637void MessageLoop::HistogramEvent(int event) {
638 if (message_histogram_.get())
639 message_histogram_->Add(event);
640}
641
darin@google.comd936b5b2008-08-26 14:53:57 +0900642//------------------------------------------------------------------------------
643// MessageLoopForUI
644
645#if defined(OS_WIN)
darin@google.comd936b5b2008-08-26 14:53:57 +0900646void MessageLoopForUI::DidProcessMessage(const MSG& message) {
647 pump_win()->DidProcessMessage(message);
648}
darin@google.comd936b5b2008-08-26 14:53:57 +0900649#endif // defined(OS_WIN)
650
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900651#if !defined(OS_MACOSX)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900652void MessageLoopForUI::AddObserver(Observer* observer) {
653 pump_ui()->AddObserver(observer);
654}
655
656void MessageLoopForUI::RemoveObserver(Observer* observer) {
657 pump_ui()->RemoveObserver(observer);
658}
659
660void MessageLoopForUI::Run(Dispatcher* dispatcher) {
661 AutoRunState save_state(this);
662 state_->dispatcher = dispatcher;
663 RunHandler();
664}
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900665#endif // !defined(OS_MACOSX)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900666
darin@google.comd936b5b2008-08-26 14:53:57 +0900667//------------------------------------------------------------------------------
668// MessageLoopForIO
669
670#if defined(OS_WIN)
671
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900672void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
673 pump_io()->RegisterIOHandler(file, handler);
674}
675
rvargas@google.com73887542008-11-08 06:52:15 +0900676bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
677 return pump_io()->WaitForIOCompletion(timeout, filter);
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900678}
679
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900680#elif defined(OS_POSIX)
681
jeremy@chromium.orgefc0db02008-12-16 07:02:17 +0900682bool MessageLoopForIO::WatchFileDescriptor(int fd,
683 bool persistent,
684 Mode mode,
685 FileDescriptorWatcher *controller,
686 Watcher *delegate) {
687 return pump_libevent()->WatchFileDescriptor(
688 fd,
689 persistent,
690 static_cast<base::MessagePumpLibevent::Mode>(mode),
691 controller,
692 delegate);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900693}
694
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900695#endif