blob: b20e6b6cf44c59af37a87f4b034017cc6ecff81e [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)
bryeung@google.come6bb34b2010-11-04 07:11:41 +0900141// TODO(sadrul): enable the new message pump when ready
142#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
rjkroege@google.com3080f442010-10-23 01:17:47 +0900143#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900144#elif defined(OS_POSIX) // POSIX but not MACOSX.
145#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
146#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900147#else
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900148#error Not implemented
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900149#endif
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900150
151 if (type_ == TYPE_UI) {
152 pump_ = MESSAGE_PUMP_UI;
dsh@google.com119a2522008-10-04 01:52:59 +0900153 } else if (type_ == TYPE_IO) {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900154 pump_ = MESSAGE_PUMP_IO;
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900155 } else {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900156 DCHECK_EQ(TYPE_DEFAULT, type_);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900157 pump_ = new base::MessagePumpDefault();
158 }
initial.commit3f4a7322008-07-27 06:49:38 +0900159}
160
161MessageLoop::~MessageLoop() {
162 DCHECK(this == current());
darin@google.com965e5342008-08-06 08:16:41 +0900163
164 // Let interested parties have one last shot at accessing this.
165 FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
166 WillDestroyCurrentMessageLoop());
167
darin@google.com0e500502008-09-09 14:55:35 +0900168 DCHECK(!state_);
169
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900170 // Clean up any unprocessed tasks, but take care: deleting a task could
171 // result in the addition of more tasks (e.g., via DeleteSoon). We set a
172 // limit on the number of times we will allow a deleted task to generate more
173 // tasks. Normally, we should only pass through this loop once or twice. If
174 // we end up hitting the loop limit, then it is probably due to one task that
175 // is being stubborn. Inspect the queues to see who is left.
176 bool did_work;
177 for (int i = 0; i < 100; ++i) {
178 DeletePendingTasks();
179 ReloadWorkQueue();
180 // If we end up with empty queues, then break out of the loop.
181 did_work = DeletePendingTasks();
182 if (!did_work)
183 break;
darin@google.com0e500502008-09-09 14:55:35 +0900184 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900185 DCHECK(!did_work);
186
187 // OK, now make it so that no one can find us.
deanm@chromium.orge4cc5922008-09-10 20:14:56 +0900188 lazy_tls_ptr.Pointer()->Set(NULL);
initial.commit3f4a7322008-07-27 06:49:38 +0900189}
190
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900191void MessageLoop::AddDestructionObserver(
192 DestructionObserver* destruction_observer) {
darin@google.com965e5342008-08-06 08:16:41 +0900193 DCHECK(this == current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900194 destruction_observers_.AddObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900195}
196
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900197void MessageLoop::RemoveDestructionObserver(
198 DestructionObserver* destruction_observer) {
darin@google.com965e5342008-08-06 08:16:41 +0900199 DCHECK(this == current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900200 destruction_observers_.RemoveObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900201}
202
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900203void MessageLoop::AddTaskObserver(TaskObserver* task_observer) {
willchan@chromium.orga9047632010-06-10 06:20:41 +0900204 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900205 task_observers_.AddObserver(task_observer);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900206}
207
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900208void MessageLoop::RemoveTaskObserver(TaskObserver* task_observer) {
willchan@chromium.orga9047632010-06-10 06:20:41 +0900209 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900210 task_observers_.RemoveObserver(task_observer);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900211}
212
darin@google.com6ddeb842008-08-15 16:31:20 +0900213void MessageLoop::Run() {
darin@google.com981f3552008-08-16 12:09:05 +0900214 AutoRunState save_state(this);
215 RunHandler();
darin@google.com6ddeb842008-08-15 16:31:20 +0900216}
217
jar@google.com9239e022008-07-31 22:10:20 +0900218void MessageLoop::RunAllPending() {
darin@google.com981f3552008-08-16 12:09:05 +0900219 AutoRunState save_state(this);
220 state_->quit_received = true; // Means run until we would otherwise block.
221 RunHandler();
initial.commit3f4a7322008-07-27 06:49:38 +0900222}
223
224// Runs the loop in two different SEH modes:
225// enable_SEH_restoration_ = false : any unhandled exception goes to the last
226// one that calls SetUnhandledExceptionFilter().
227// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
228// that was existed before the loop was run.
darin@google.com981f3552008-08-16 12:09:05 +0900229void MessageLoop::RunHandler() {
230#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +0900231 if (exception_restoration_) {
stoyan@google.com283facb2009-10-27 03:15:59 +0900232 RunInternalInSEHFrame();
darin@google.com981f3552008-08-16 12:09:05 +0900233 return;
initial.commit3f4a7322008-07-27 06:49:38 +0900234 }
darin@google.com981f3552008-08-16 12:09:05 +0900235#endif
236
237 RunInternal();
initial.commit3f4a7322008-07-27 06:49:38 +0900238}
stoyan@google.com283facb2009-10-27 03:15:59 +0900239//------------------------------------------------------------------------------
240#if defined(OS_WIN)
241__declspec(noinline) void MessageLoop::RunInternalInSEHFrame() {
242 LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
243 __try {
244 RunInternal();
245 } __except(SEHFilter(current_filter)) {
246 }
247 return;
248}
249#endif
initial.commit3f4a7322008-07-27 06:49:38 +0900250//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900251
darin@google.com981f3552008-08-16 12:09:05 +0900252void MessageLoop::RunInternal() {
253 DCHECK(this == current());
254
initial.commit3f4a7322008-07-27 06:49:38 +0900255 StartHistogrammer();
256
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900257#if !defined(OS_MACOSX)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900258 if (state_->dispatcher && type() == TYPE_UI) {
259 static_cast<base::MessagePumpForUI*>(pump_.get())->
260 RunWithDispatcher(this, state_->dispatcher);
darin@google.com981f3552008-08-16 12:09:05 +0900261 return;
jar@google.com9239e022008-07-31 22:10:20 +0900262 }
darin@google.com981f3552008-08-16 12:09:05 +0900263#endif
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900264
darin@google.com981f3552008-08-16 12:09:05 +0900265 pump_->Run(this);
jar@google.comfbaaf692008-07-30 16:50:53 +0900266}
jar@google.com7ff36e62008-07-30 15:58:56 +0900267
jar@google.comb4d1bff2008-07-31 04:03:59 +0900268//------------------------------------------------------------------------------
269// Wrapper functions for use in above message loop framework.
270
initial.commit3f4a7322008-07-27 06:49:38 +0900271bool MessageLoop::ProcessNextDelayedNonNestableTask() {
darin@google.com981f3552008-08-16 12:09:05 +0900272 if (state_->run_depth != 1)
initial.commit3f4a7322008-07-27 06:49:38 +0900273 return false;
274
darin@google.combe165ae2008-09-07 17:08:29 +0900275 if (deferred_non_nestable_work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900276 return false;
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900277
darin@google.combe165ae2008-09-07 17:08:29 +0900278 Task* task = deferred_non_nestable_work_queue_.front().task;
279 deferred_non_nestable_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900280
darin@google.combe165ae2008-09-07 17:08:29 +0900281 RunTask(task);
initial.commit3f4a7322008-07-27 06:49:38 +0900282 return true;
283}
284
initial.commit3f4a7322008-07-27 06:49:38 +0900285//------------------------------------------------------------------------------
286
287void MessageLoop::Quit() {
darin@google.com981f3552008-08-16 12:09:05 +0900288 DCHECK(current() == this);
289 if (state_) {
290 state_->quit_received = true;
291 } else {
292 NOTREACHED() << "Must be inside Run to call Quit";
initial.commit3f4a7322008-07-27 06:49:38 +0900293 }
initial.commit3f4a7322008-07-27 06:49:38 +0900294}
295
darin@chromium.orgd70a12c2010-02-23 16:12:22 +0900296void MessageLoop::QuitNow() {
297 DCHECK(current() == this);
298 if (state_) {
299 pump_->Quit();
300 } else {
301 NOTREACHED() << "Must be inside Run to call Quit";
302 }
303}
304
darin@google.combe165ae2008-09-07 17:08:29 +0900305void MessageLoop::PostTask(
306 const tracked_objects::Location& from_here, Task* task) {
307 PostTask_Helper(from_here, task, 0, true);
308}
309
310void MessageLoop::PostDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900311 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
darin@google.combe165ae2008-09-07 17:08:29 +0900312 PostTask_Helper(from_here, task, delay_ms, true);
313}
314
315void MessageLoop::PostNonNestableTask(
316 const tracked_objects::Location& from_here, Task* task) {
317 PostTask_Helper(from_here, task, 0, false);
318}
319
320void MessageLoop::PostNonNestableDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900321 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
darin@google.combe165ae2008-09-07 17:08:29 +0900322 PostTask_Helper(from_here, task, delay_ms, false);
323}
324
initial.commit3f4a7322008-07-27 06:49:38 +0900325// Possibly called on a background thread!
darin@google.combe165ae2008-09-07 17:08:29 +0900326void MessageLoop::PostTask_Helper(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900327 const tracked_objects::Location& from_here, Task* task, int64 delay_ms,
darin@google.combe165ae2008-09-07 17:08:29 +0900328 bool nestable) {
initial.commit3f4a7322008-07-27 06:49:38 +0900329 task->SetBirthPlace(from_here);
darin@google.com0795f572008-08-30 09:22:48 +0900330
darin@google.combe165ae2008-09-07 17:08:29 +0900331 PendingTask pending_task(task, nestable);
darin@google.com0795f572008-08-30 09:22:48 +0900332
333 if (delay_ms > 0) {
darin@google.combe165ae2008-09-07 17:08:29 +0900334 pending_task.delayed_run_time =
darin@google.com0795f572008-08-30 09:22:48 +0900335 Time::Now() + TimeDelta::FromMilliseconds(delay_ms);
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900336
337#if defined(OS_WIN)
338 if (high_resolution_timer_expiration_.is_null()) {
339 // Windows timers are granular to 15.6ms. If we only set high-res
340 // timers for those under 15.6ms, then a 18ms timer ticks at ~32ms,
341 // which as a percentage is pretty inaccurate. So enable high
342 // res timers for any timer which is within 2x of the granularity.
343 // This is a tradeoff between accuracy and power management.
344 bool needs_high_res_timers =
345 delay_ms < (2 * Time::kMinLowResolutionThresholdMs);
346 if (needs_high_res_timers) {
phajdan.jr@chromium.org3337f3d2010-10-20 19:50:38 +0900347 Time::ActivateHighResolutionTimer(true);
348 high_resolution_timer_expiration_ = base::TimeTicks::Now() +
349 TimeDelta::FromMilliseconds(kHighResolutionTimerModeLeaseTimeMs);
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900350 }
351 }
352#endif
darin@google.com0795f572008-08-30 09:22:48 +0900353 } else {
jar@chromium.orged5238a2009-12-28 15:59:52 +0900354 DCHECK_EQ(delay_ms, 0) << "delay should not be negative";
darin@google.com0795f572008-08-30 09:22:48 +0900355 }
356
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900357#if defined(OS_WIN)
358 if (!high_resolution_timer_expiration_.is_null()) {
359 if (base::TimeTicks::Now() > high_resolution_timer_expiration_) {
360 Time::ActivateHighResolutionTimer(false);
361 high_resolution_timer_expiration_ = base::TimeTicks();
362 }
363 }
364#endif
365
initial.commit3f4a7322008-07-27 06:49:38 +0900366 // Warning: Don't try to short-circuit, and handle this thread's tasks more
367 // directly, as it could starve handling of foreign threads. Put every task
368 // into this queue.
369
darin@google.com981f3552008-08-16 12:09:05 +0900370 scoped_refptr<base::MessagePump> pump;
initial.commit3f4a7322008-07-27 06:49:38 +0900371 {
darin@google.com981f3552008-08-16 12:09:05 +0900372 AutoLock locked(incoming_queue_lock_);
373
darin@google.combe165ae2008-09-07 17:08:29 +0900374 bool was_empty = incoming_queue_.empty();
375 incoming_queue_.push(pending_task);
initial.commit3f4a7322008-07-27 06:49:38 +0900376 if (!was_empty)
377 return; // Someone else should have started the sub-pump.
378
darin@google.com981f3552008-08-16 12:09:05 +0900379 pump = pump_;
darin@google.com6ddeb842008-08-15 16:31:20 +0900380 }
darin@google.com981f3552008-08-16 12:09:05 +0900381 // Since the incoming_queue_ may contain a task that destroys this message
382 // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
383 // We use a stack-based reference to the message pump so that we can call
384 // ScheduleWork outside of incoming_queue_lock_.
darin@google.com6ddeb842008-08-15 16:31:20 +0900385
darin@google.com981f3552008-08-16 12:09:05 +0900386 pump->ScheduleWork();
initial.commit3f4a7322008-07-27 06:49:38 +0900387}
388
389void MessageLoop::SetNestableTasksAllowed(bool allowed) {
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900390 if (nestable_tasks_allowed_ != allowed) {
391 nestable_tasks_allowed_ = allowed;
392 if (!nestable_tasks_allowed_)
393 return;
394 // Start the native pump if we are not already pumping.
darin@google.com981f3552008-08-16 12:09:05 +0900395 pump_->ScheduleWork();
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900396 }
initial.commit3f4a7322008-07-27 06:49:38 +0900397}
398
399bool MessageLoop::NestableTasksAllowed() const {
400 return nestable_tasks_allowed_;
401}
402
jcampan@chromium.orgeac57172009-07-02 04:53:59 +0900403bool MessageLoop::IsNested() {
404 return state_->run_depth > 1;
405}
406
initial.commit3f4a7322008-07-27 06:49:38 +0900407//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900408
initial.commit3f4a7322008-07-27 06:49:38 +0900409void MessageLoop::RunTask(Task* task) {
initial.commit3f4a7322008-07-27 06:49:38 +0900410 DCHECK(nestable_tasks_allowed_);
411 // Execute the task and assume the worst: It is probably not reentrant.
412 nestable_tasks_allowed_ = false;
darin@google.combe165ae2008-09-07 17:08:29 +0900413
414 HistogramEvent(kTaskRunEvent);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900415 FOR_EACH_OBSERVER(TaskObserver, task_observers_,
davemoore@chromium.orgeb5f68f2010-10-27 08:40:48 +0900416 WillProcessTask(task));
darin@google.combe165ae2008-09-07 17:08:29 +0900417 task->Run();
davemoore@chromium.orgeb5f68f2010-10-27 08:40:48 +0900418 FOR_EACH_OBSERVER(TaskObserver, task_observers_, DidProcessTask(task));
darin@google.combe165ae2008-09-07 17:08:29 +0900419 delete task;
420
421 nestable_tasks_allowed_ = true;
initial.commit3f4a7322008-07-27 06:49:38 +0900422}
423
darin@google.combe165ae2008-09-07 17:08:29 +0900424bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) {
425 if (pending_task.nestable || state_->run_depth == 1) {
426 RunTask(pending_task.task);
427 // Show that we ran a task (Note: a new one might arrive as a
428 // consequence!).
429 return true;
430 }
431
432 // We couldn't run the task now because we're in a nested message loop
433 // and the task isn't nestable.
434 deferred_non_nestable_work_queue_.push(pending_task);
435 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900436}
437
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900438void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
439 // Move to the delayed work queue. Initialize the sequence number
440 // before inserting into the delayed_work_queue_. The sequence number
441 // is used to faciliate FIFO sorting when two tasks have the same
442 // delayed_run_time value.
443 PendingTask new_pending_task(pending_task);
444 new_pending_task.sequence_num = next_sequence_num_++;
445 delayed_work_queue_.push(new_pending_task);
446}
447
initial.commit3f4a7322008-07-27 06:49:38 +0900448void MessageLoop::ReloadWorkQueue() {
449 // We can improve performance of our loading tasks from incoming_queue_ to
darin@google.com981f3552008-08-16 12:09:05 +0900450 // work_queue_ by waiting until the last minute (work_queue_ is empty) to
451 // load. That reduces the number of locks-per-task significantly when our
darin@google.combe165ae2008-09-07 17:08:29 +0900452 // queues get large.
453 if (!work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900454 return; // Wait till we *really* need to lock and load.
455
456 // Acquire all we can from the inter-thread queue with one lock acquisition.
initial.commit3f4a7322008-07-27 06:49:38 +0900457 {
458 AutoLock lock(incoming_queue_lock_);
darin@google.combe165ae2008-09-07 17:08:29 +0900459 if (incoming_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900460 return;
darin@chromium.orgb80ef1a2009-09-03 05:05:21 +0900461 incoming_queue_.Swap(&work_queue_); // Constant time
darin@google.combe165ae2008-09-07 17:08:29 +0900462 DCHECK(incoming_queue_.empty());
initial.commit3f4a7322008-07-27 06:49:38 +0900463 }
464}
465
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900466bool MessageLoop::DeletePendingTasks() {
467 bool did_work = !work_queue_.empty();
468 while (!work_queue_.empty()) {
469 PendingTask pending_task = work_queue_.front();
470 work_queue_.pop();
471 if (!pending_task.delayed_run_time.is_null()) {
472 // We want to delete delayed tasks in the same order in which they would
473 // normally be deleted in case of any funny dependencies between delayed
474 // tasks.
475 AddToDelayedWorkQueue(pending_task);
476 } else {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900477 // TODO(darin): Delete all tasks once it is safe to do so.
478 // Until it is totally safe, just do it when running Purify or
479 // Valgrind.
thestig@chromium.orgddb849c2010-10-28 05:03:42 +0900480#if defined(PURIFY) || defined(USE_HEAPCHECKER)
jar@chromium.org63772352009-03-12 05:06:02 +0900481 delete pending_task.task;
akalin@chromium.org839060b2010-08-03 12:06:21 +0900482#elif defined(OS_POSIX)
483 if (RUNNING_ON_VALGRIND)
484 delete pending_task.task;
485#endif // defined(OS_POSIX)
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900486 }
initial.commit3f4a7322008-07-27 06:49:38 +0900487 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900488 did_work |= !deferred_non_nestable_work_queue_.empty();
489 while (!deferred_non_nestable_work_queue_.empty()) {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900490 // TODO(darin): Delete all tasks once it is safe to do so.
491 // Until it is totaly safe, only delete them under Purify and Valgrind.
492 Task* task = NULL;
thestig@chromium.orgddb849c2010-10-28 05:03:42 +0900493#if defined(PURIFY) || defined(USE_HEAPCHECKER)
akalin@chromium.org839060b2010-08-03 12:06:21 +0900494 task = deferred_non_nestable_work_queue_.front().task;
495#elif defined(OS_POSIX)
496 if (RUNNING_ON_VALGRIND)
497 task = deferred_non_nestable_work_queue_.front().task;
498#endif
jar@chromium.org2fa6b4b2009-03-12 04:53:50 +0900499 deferred_non_nestable_work_queue_.pop();
akalin@chromium.org839060b2010-08-03 12:06:21 +0900500 if (task)
501 delete task;
initial.commit3f4a7322008-07-27 06:49:38 +0900502 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900503 did_work |= !delayed_work_queue_.empty();
504 while (!delayed_work_queue_.empty()) {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900505 Task* task = delayed_work_queue_.top().task;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900506 delayed_work_queue_.pop();
akalin@chromium.org839060b2010-08-03 12:06:21 +0900507 delete task;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900508 }
509 return did_work;
initial.commit3f4a7322008-07-27 06:49:38 +0900510}
511
darin@google.com981f3552008-08-16 12:09:05 +0900512bool MessageLoop::DoWork() {
darin@google.combe165ae2008-09-07 17:08:29 +0900513 if (!nestable_tasks_allowed_) {
514 // Task can't be executed right now.
515 return false;
516 }
517
518 for (;;) {
519 ReloadWorkQueue();
520 if (work_queue_.empty())
521 break;
522
523 // Execute oldest task.
524 do {
525 PendingTask pending_task = work_queue_.front();
526 work_queue_.pop();
527 if (!pending_task.delayed_run_time.is_null()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900528 AddToDelayedWorkQueue(pending_task);
darin@chromium.orgb2d33452008-09-24 04:19:20 +0900529 // If we changed the topmost task, then it is time to re-schedule.
jar@chromium.org40355072010-10-21 15:32:33 +0900530 if (delayed_work_queue_.top().task == pending_task.task)
darin@google.combe165ae2008-09-07 17:08:29 +0900531 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
532 } else {
533 if (DeferOrRunPendingTask(pending_task))
534 return true;
535 }
536 } while (!work_queue_.empty());
537 }
538
539 // Nothing happened.
540 return false;
darin@google.com981f3552008-08-16 12:09:05 +0900541}
542
rjkroege@google.com3080f442010-10-23 01:17:47 +0900543bool MessageLoop::DoDelayedWork(base::Time* next_delayed_work_time) {
jar@chromium.org40355072010-10-21 15:32:33 +0900544 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
rjkroege@google.com3080f442010-10-23 01:17:47 +0900545 *next_delayed_work_time = base::Time();
darin@google.combe165ae2008-09-07 17:08:29 +0900546 return false;
547 }
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900548
jar@chromium.org40355072010-10-21 15:32:33 +0900549 if (delayed_work_queue_.top().delayed_run_time > Time::Now()) {
550 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
551 return false;
darin@google.combe165ae2008-09-07 17:08:29 +0900552 }
darin@google.com981f3552008-08-16 12:09:05 +0900553
jar@chromium.org40355072010-10-21 15:32:33 +0900554 PendingTask pending_task = delayed_work_queue_.top();
555 delayed_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900556
jar@chromium.org40355072010-10-21 15:32:33 +0900557 if (!delayed_work_queue_.empty())
darin@google.combe165ae2008-09-07 17:08:29 +0900558 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
darin@google.com981f3552008-08-16 12:09:05 +0900559
darin@google.combe165ae2008-09-07 17:08:29 +0900560 return DeferOrRunPendingTask(pending_task);
darin@google.com981f3552008-08-16 12:09:05 +0900561}
562
563bool MessageLoop::DoIdleWork() {
564 if (ProcessNextDelayedNonNestableTask())
565 return true;
566
567 if (state_->quit_received)
568 pump_->Quit();
569
570 return false;
571}
572
573//------------------------------------------------------------------------------
574// MessageLoop::AutoRunState
575
576MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
577 // Make the loop reference us.
578 previous_state_ = loop_->state_;
579 if (previous_state_) {
580 run_depth = previous_state_->run_depth + 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900581 } else {
darin@google.com981f3552008-08-16 12:09:05 +0900582 run_depth = 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900583 }
darin@google.com981f3552008-08-16 12:09:05 +0900584 loop_->state_ = this;
585
586 // Initialize the other fields:
587 quit_received = false;
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900588#if !defined(OS_MACOSX)
darin@google.com981f3552008-08-16 12:09:05 +0900589 dispatcher = NULL;
590#endif
591}
592
593MessageLoop::AutoRunState::~AutoRunState() {
594 loop_->state_ = previous_state_;
darin@google.comee6fa722008-08-13 08:25:43 +0900595}
596
initial.commit3f4a7322008-07-27 06:49:38 +0900597//------------------------------------------------------------------------------
darin@google.combe165ae2008-09-07 17:08:29 +0900598// MessageLoop::PendingTask
initial.commit3f4a7322008-07-27 06:49:38 +0900599
darin@google.combe165ae2008-09-07 17:08:29 +0900600bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
601 // Since the top of a priority queue is defined as the "greatest" element, we
602 // need to invert the comparison here. We want the smaller time to be at the
603 // top of the heap.
initial.commit3f4a7322008-07-27 06:49:38 +0900604
darin@google.combe165ae2008-09-07 17:08:29 +0900605 if (delayed_run_time < other.delayed_run_time)
606 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900607
darin@google.combe165ae2008-09-07 17:08:29 +0900608 if (delayed_run_time > other.delayed_run_time)
609 return true;
initial.commit3f4a7322008-07-27 06:49:38 +0900610
darin@google.combe165ae2008-09-07 17:08:29 +0900611 // If the times happen to match, then we use the sequence number to decide.
612 // Compare the difference to support integer roll-over.
613 return (sequence_num - other.sequence_num) > 0;
initial.commit3f4a7322008-07-27 06:49:38 +0900614}
615
616//------------------------------------------------------------------------------
617// Method and data for histogramming events and actions taken by each instance
618// on each thread.
619
620// static
initial.commit3f4a7322008-07-27 06:49:38 +0900621void MessageLoop::EnableHistogrammer(bool enable) {
622 enable_histogrammer_ = enable;
623}
624
625void MessageLoop::StartHistogrammer() {
626 if (enable_histogrammer_ && !message_histogram_.get()
brettw@chromium.org275c2ec2010-10-14 13:38:38 +0900627 && base::StatisticsRecorder::WasStarted()) {
darin@google.com981f3552008-08-16 12:09:05 +0900628 DCHECK(!thread_name_.empty());
brettw@chromium.org275c2ec2010-10-14 13:38:38 +0900629 message_histogram_ = base::LinearHistogram::FactoryGet(
630 "MsgLoop:" + thread_name_,
jar@chromium.orged5238a2009-12-28 15:59:52 +0900631 kLeastNonZeroMessageId, kMaxMessageId,
632 kNumberOfDistinctMessagesDisplayed,
633 message_histogram_->kHexRangePrintingFlag);
initial.commit3f4a7322008-07-27 06:49:38 +0900634 message_histogram_->SetRangeDescriptions(event_descriptions_);
635 }
636}
637
638void MessageLoop::HistogramEvent(int event) {
639 if (message_histogram_.get())
640 message_histogram_->Add(event);
641}
642
darin@google.comd936b5b2008-08-26 14:53:57 +0900643//------------------------------------------------------------------------------
644// MessageLoopForUI
645
646#if defined(OS_WIN)
darin@google.comd936b5b2008-08-26 14:53:57 +0900647void MessageLoopForUI::DidProcessMessage(const MSG& message) {
648 pump_win()->DidProcessMessage(message);
649}
darin@google.comd936b5b2008-08-26 14:53:57 +0900650#endif // defined(OS_WIN)
651
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900652#if !defined(OS_MACOSX)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900653void MessageLoopForUI::AddObserver(Observer* observer) {
654 pump_ui()->AddObserver(observer);
655}
656
657void MessageLoopForUI::RemoveObserver(Observer* observer) {
658 pump_ui()->RemoveObserver(observer);
659}
660
661void MessageLoopForUI::Run(Dispatcher* dispatcher) {
662 AutoRunState save_state(this);
663 state_->dispatcher = dispatcher;
664 RunHandler();
665}
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900666#endif // !defined(OS_MACOSX)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900667
darin@google.comd936b5b2008-08-26 14:53:57 +0900668//------------------------------------------------------------------------------
669// MessageLoopForIO
670
671#if defined(OS_WIN)
672
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900673void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
674 pump_io()->RegisterIOHandler(file, handler);
675}
676
rvargas@google.com73887542008-11-08 06:52:15 +0900677bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
678 return pump_io()->WaitForIOCompletion(timeout, filter);
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900679}
680
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900681#elif defined(OS_POSIX)
682
jeremy@chromium.orgefc0db02008-12-16 07:02:17 +0900683bool MessageLoopForIO::WatchFileDescriptor(int fd,
684 bool persistent,
685 Mode mode,
686 FileDescriptorWatcher *controller,
687 Watcher *delegate) {
688 return pump_libevent()->WatchFileDescriptor(
689 fd,
690 persistent,
691 static_cast<base::MessagePumpLibevent::Mode>(mode),
692 controller,
693 delegate);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900694}
695
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900696#endif