blob: 49d76a03bfed8c8ad9d8775b83fc4ecac67759fe [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::TimeDelta;
jar@chromium.org9b0fb062010-11-07 07:23:29 +090031using base::TimeTicks;
dsh@google.com0f8dd262008-10-28 05:43:33 +090032
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)
sadrul@chromium.orgcff2c642010-12-17 04:43:30 +0900141#define MESSAGE_PUMP_UI new base::MessagePumpGlibX()
rjkroege@google.com3080f442010-10-23 01:17:47 +0900142#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900143#elif defined(OS_NACL)
144// Currently NaCl doesn't have a UI or an IO MessageLoop.
145// TODO(abarth): Figure out if we need these.
146#define MESSAGE_PUMP_UI NULL
147#define MESSAGE_PUMP_IO NULL
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900148#elif defined(OS_POSIX) // POSIX but not MACOSX.
149#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
150#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900151#else
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900152#error Not implemented
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900153#endif
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900154
155 if (type_ == TYPE_UI) {
156 pump_ = MESSAGE_PUMP_UI;
dsh@google.com119a2522008-10-04 01:52:59 +0900157 } else if (type_ == TYPE_IO) {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900158 pump_ = MESSAGE_PUMP_IO;
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900159 } else {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900160 DCHECK_EQ(TYPE_DEFAULT, type_);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900161 pump_ = new base::MessagePumpDefault();
162 }
initial.commit3f4a7322008-07-27 06:49:38 +0900163}
164
165MessageLoop::~MessageLoop() {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900166 DCHECK_EQ(this, current());
darin@google.com965e5342008-08-06 08:16:41 +0900167
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
sanjeevr@chromium.org03b44d52010-11-30 09:25:29 +0900187 // Let interested parties have one last shot at accessing this.
188 FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
189 WillDestroyCurrentMessageLoop());
190
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900191 // OK, now make it so that no one can find us.
deanm@chromium.orge4cc5922008-09-10 20:14:56 +0900192 lazy_tls_ptr.Pointer()->Set(NULL);
initial.commit3f4a7322008-07-27 06:49:38 +0900193}
194
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900195void MessageLoop::AddDestructionObserver(
196 DestructionObserver* destruction_observer) {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900197 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900198 destruction_observers_.AddObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900199}
200
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900201void MessageLoop::RemoveDestructionObserver(
202 DestructionObserver* destruction_observer) {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900203 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900204 destruction_observers_.RemoveObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900205}
206
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900207void MessageLoop::AddTaskObserver(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_.AddObserver(task_observer);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900210}
211
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900212void MessageLoop::RemoveTaskObserver(TaskObserver* task_observer) {
willchan@chromium.orga9047632010-06-10 06:20:41 +0900213 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900214 task_observers_.RemoveObserver(task_observer);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900215}
216
darin@google.com6ddeb842008-08-15 16:31:20 +0900217void MessageLoop::Run() {
darin@google.com981f3552008-08-16 12:09:05 +0900218 AutoRunState save_state(this);
219 RunHandler();
darin@google.com6ddeb842008-08-15 16:31:20 +0900220}
221
jar@google.com9239e022008-07-31 22:10:20 +0900222void MessageLoop::RunAllPending() {
darin@google.com981f3552008-08-16 12:09:05 +0900223 AutoRunState save_state(this);
224 state_->quit_received = true; // Means run until we would otherwise block.
225 RunHandler();
initial.commit3f4a7322008-07-27 06:49:38 +0900226}
227
228// Runs the loop in two different SEH modes:
229// enable_SEH_restoration_ = false : any unhandled exception goes to the last
230// one that calls SetUnhandledExceptionFilter().
231// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
232// that was existed before the loop was run.
darin@google.com981f3552008-08-16 12:09:05 +0900233void MessageLoop::RunHandler() {
234#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +0900235 if (exception_restoration_) {
stoyan@google.com283facb2009-10-27 03:15:59 +0900236 RunInternalInSEHFrame();
darin@google.com981f3552008-08-16 12:09:05 +0900237 return;
initial.commit3f4a7322008-07-27 06:49:38 +0900238 }
darin@google.com981f3552008-08-16 12:09:05 +0900239#endif
240
241 RunInternal();
initial.commit3f4a7322008-07-27 06:49:38 +0900242}
stoyan@google.com283facb2009-10-27 03:15:59 +0900243//------------------------------------------------------------------------------
244#if defined(OS_WIN)
245__declspec(noinline) void MessageLoop::RunInternalInSEHFrame() {
246 LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
247 __try {
248 RunInternal();
249 } __except(SEHFilter(current_filter)) {
250 }
251 return;
252}
253#endif
initial.commit3f4a7322008-07-27 06:49:38 +0900254//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900255
darin@google.com981f3552008-08-16 12:09:05 +0900256void MessageLoop::RunInternal() {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900257 DCHECK_EQ(this, current());
darin@google.com981f3552008-08-16 12:09:05 +0900258
initial.commit3f4a7322008-07-27 06:49:38 +0900259 StartHistogrammer();
260
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900261#if !defined(OS_MACOSX)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900262 if (state_->dispatcher && type() == TYPE_UI) {
263 static_cast<base::MessagePumpForUI*>(pump_.get())->
264 RunWithDispatcher(this, state_->dispatcher);
darin@google.com981f3552008-08-16 12:09:05 +0900265 return;
jar@google.com9239e022008-07-31 22:10:20 +0900266 }
darin@google.com981f3552008-08-16 12:09:05 +0900267#endif
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900268
darin@google.com981f3552008-08-16 12:09:05 +0900269 pump_->Run(this);
jar@google.comfbaaf692008-07-30 16:50:53 +0900270}
jar@google.com7ff36e62008-07-30 15:58:56 +0900271
jar@google.comb4d1bff2008-07-31 04:03:59 +0900272//------------------------------------------------------------------------------
273// Wrapper functions for use in above message loop framework.
274
initial.commit3f4a7322008-07-27 06:49:38 +0900275bool MessageLoop::ProcessNextDelayedNonNestableTask() {
darin@google.com981f3552008-08-16 12:09:05 +0900276 if (state_->run_depth != 1)
initial.commit3f4a7322008-07-27 06:49:38 +0900277 return false;
278
darin@google.combe165ae2008-09-07 17:08:29 +0900279 if (deferred_non_nestable_work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900280 return false;
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900281
darin@google.combe165ae2008-09-07 17:08:29 +0900282 Task* task = deferred_non_nestable_work_queue_.front().task;
283 deferred_non_nestable_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900284
darin@google.combe165ae2008-09-07 17:08:29 +0900285 RunTask(task);
initial.commit3f4a7322008-07-27 06:49:38 +0900286 return true;
287}
288
initial.commit3f4a7322008-07-27 06:49:38 +0900289//------------------------------------------------------------------------------
290
291void MessageLoop::Quit() {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900292 DCHECK_EQ(this, current());
darin@google.com981f3552008-08-16 12:09:05 +0900293 if (state_) {
294 state_->quit_received = true;
295 } else {
296 NOTREACHED() << "Must be inside Run to call Quit";
initial.commit3f4a7322008-07-27 06:49:38 +0900297 }
initial.commit3f4a7322008-07-27 06:49:38 +0900298}
299
darin@chromium.orgd70a12c2010-02-23 16:12:22 +0900300void MessageLoop::QuitNow() {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900301 DCHECK_EQ(this, current());
darin@chromium.orgd70a12c2010-02-23 16:12:22 +0900302 if (state_) {
303 pump_->Quit();
304 } else {
305 NOTREACHED() << "Must be inside Run to call Quit";
306 }
307}
308
darin@google.combe165ae2008-09-07 17:08:29 +0900309void MessageLoop::PostTask(
310 const tracked_objects::Location& from_here, Task* task) {
311 PostTask_Helper(from_here, task, 0, true);
312}
313
314void MessageLoop::PostDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900315 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
darin@google.combe165ae2008-09-07 17:08:29 +0900316 PostTask_Helper(from_here, task, delay_ms, true);
317}
318
319void MessageLoop::PostNonNestableTask(
320 const tracked_objects::Location& from_here, Task* task) {
321 PostTask_Helper(from_here, task, 0, false);
322}
323
324void MessageLoop::PostNonNestableDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900325 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
darin@google.combe165ae2008-09-07 17:08:29 +0900326 PostTask_Helper(from_here, task, delay_ms, false);
327}
328
initial.commit3f4a7322008-07-27 06:49:38 +0900329// Possibly called on a background thread!
darin@google.combe165ae2008-09-07 17:08:29 +0900330void MessageLoop::PostTask_Helper(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900331 const tracked_objects::Location& from_here, Task* task, int64 delay_ms,
darin@google.combe165ae2008-09-07 17:08:29 +0900332 bool nestable) {
initial.commit3f4a7322008-07-27 06:49:38 +0900333 task->SetBirthPlace(from_here);
darin@google.com0795f572008-08-30 09:22:48 +0900334
darin@google.combe165ae2008-09-07 17:08:29 +0900335 PendingTask pending_task(task, nestable);
darin@google.com0795f572008-08-30 09:22:48 +0900336
337 if (delay_ms > 0) {
darin@google.combe165ae2008-09-07 17:08:29 +0900338 pending_task.delayed_run_time =
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900339 TimeTicks::Now() + TimeDelta::FromMilliseconds(delay_ms);
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900340
341#if defined(OS_WIN)
342 if (high_resolution_timer_expiration_.is_null()) {
343 // Windows timers are granular to 15.6ms. If we only set high-res
344 // timers for those under 15.6ms, then a 18ms timer ticks at ~32ms,
345 // which as a percentage is pretty inaccurate. So enable high
346 // res timers for any timer which is within 2x of the granularity.
347 // This is a tradeoff between accuracy and power management.
348 bool needs_high_res_timers =
sadrul@chromium.org3495d4a2010-12-21 07:00:02 +0900349 delay_ms < (2 * base::Time::kMinLowResolutionThresholdMs);
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900350 if (needs_high_res_timers) {
sadrul@chromium.org3495d4a2010-12-21 07:00:02 +0900351 base::Time::ActivateHighResolutionTimer(true);
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900352 high_resolution_timer_expiration_ = TimeTicks::Now() +
phajdan.jr@chromium.org3337f3d2010-10-20 19:50:38 +0900353 TimeDelta::FromMilliseconds(kHighResolutionTimerModeLeaseTimeMs);
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900354 }
355 }
356#endif
darin@google.com0795f572008-08-30 09:22:48 +0900357 } else {
jar@chromium.orged5238a2009-12-28 15:59:52 +0900358 DCHECK_EQ(delay_ms, 0) << "delay should not be negative";
darin@google.com0795f572008-08-30 09:22:48 +0900359 }
360
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900361#if defined(OS_WIN)
362 if (!high_resolution_timer_expiration_.is_null()) {
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900363 if (TimeTicks::Now() > high_resolution_timer_expiration_) {
sadrul@chromium.org3495d4a2010-12-21 07:00:02 +0900364 base::Time::ActivateHighResolutionTimer(false);
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900365 high_resolution_timer_expiration_ = TimeTicks();
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900366 }
367 }
368#endif
369
initial.commit3f4a7322008-07-27 06:49:38 +0900370 // Warning: Don't try to short-circuit, and handle this thread's tasks more
371 // directly, as it could starve handling of foreign threads. Put every task
372 // into this queue.
373
darin@google.com981f3552008-08-16 12:09:05 +0900374 scoped_refptr<base::MessagePump> pump;
initial.commit3f4a7322008-07-27 06:49:38 +0900375 {
darin@google.com981f3552008-08-16 12:09:05 +0900376 AutoLock locked(incoming_queue_lock_);
377
darin@google.combe165ae2008-09-07 17:08:29 +0900378 bool was_empty = incoming_queue_.empty();
379 incoming_queue_.push(pending_task);
initial.commit3f4a7322008-07-27 06:49:38 +0900380 if (!was_empty)
381 return; // Someone else should have started the sub-pump.
382
darin@google.com981f3552008-08-16 12:09:05 +0900383 pump = pump_;
darin@google.com6ddeb842008-08-15 16:31:20 +0900384 }
darin@google.com981f3552008-08-16 12:09:05 +0900385 // Since the incoming_queue_ may contain a task that destroys this message
386 // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
387 // We use a stack-based reference to the message pump so that we can call
388 // ScheduleWork outside of incoming_queue_lock_.
darin@google.com6ddeb842008-08-15 16:31:20 +0900389
darin@google.com981f3552008-08-16 12:09:05 +0900390 pump->ScheduleWork();
initial.commit3f4a7322008-07-27 06:49:38 +0900391}
392
393void MessageLoop::SetNestableTasksAllowed(bool allowed) {
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900394 if (nestable_tasks_allowed_ != allowed) {
395 nestable_tasks_allowed_ = allowed;
396 if (!nestable_tasks_allowed_)
397 return;
398 // Start the native pump if we are not already pumping.
darin@google.com981f3552008-08-16 12:09:05 +0900399 pump_->ScheduleWork();
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900400 }
initial.commit3f4a7322008-07-27 06:49:38 +0900401}
402
403bool MessageLoop::NestableTasksAllowed() const {
404 return nestable_tasks_allowed_;
405}
406
jcampan@chromium.orgeac57172009-07-02 04:53:59 +0900407bool MessageLoop::IsNested() {
408 return state_->run_depth > 1;
409}
410
initial.commit3f4a7322008-07-27 06:49:38 +0900411//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900412
initial.commit3f4a7322008-07-27 06:49:38 +0900413void MessageLoop::RunTask(Task* task) {
initial.commit3f4a7322008-07-27 06:49:38 +0900414 DCHECK(nestable_tasks_allowed_);
415 // Execute the task and assume the worst: It is probably not reentrant.
416 nestable_tasks_allowed_ = false;
darin@google.combe165ae2008-09-07 17:08:29 +0900417
418 HistogramEvent(kTaskRunEvent);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900419 FOR_EACH_OBSERVER(TaskObserver, task_observers_,
davemoore@chromium.orgeb5f68f2010-10-27 08:40:48 +0900420 WillProcessTask(task));
darin@google.combe165ae2008-09-07 17:08:29 +0900421 task->Run();
davemoore@chromium.orgeb5f68f2010-10-27 08:40:48 +0900422 FOR_EACH_OBSERVER(TaskObserver, task_observers_, DidProcessTask(task));
darin@google.combe165ae2008-09-07 17:08:29 +0900423 delete task;
424
425 nestable_tasks_allowed_ = true;
initial.commit3f4a7322008-07-27 06:49:38 +0900426}
427
darin@google.combe165ae2008-09-07 17:08:29 +0900428bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) {
429 if (pending_task.nestable || state_->run_depth == 1) {
430 RunTask(pending_task.task);
431 // Show that we ran a task (Note: a new one might arrive as a
432 // consequence!).
433 return true;
434 }
435
436 // We couldn't run the task now because we're in a nested message loop
437 // and the task isn't nestable.
438 deferred_non_nestable_work_queue_.push(pending_task);
439 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900440}
441
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900442void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
443 // Move to the delayed work queue. Initialize the sequence number
444 // before inserting into the delayed_work_queue_. The sequence number
445 // is used to faciliate FIFO sorting when two tasks have the same
446 // delayed_run_time value.
447 PendingTask new_pending_task(pending_task);
448 new_pending_task.sequence_num = next_sequence_num_++;
449 delayed_work_queue_.push(new_pending_task);
450}
451
initial.commit3f4a7322008-07-27 06:49:38 +0900452void MessageLoop::ReloadWorkQueue() {
453 // We can improve performance of our loading tasks from incoming_queue_ to
darin@google.com981f3552008-08-16 12:09:05 +0900454 // work_queue_ by waiting until the last minute (work_queue_ is empty) to
455 // load. That reduces the number of locks-per-task significantly when our
darin@google.combe165ae2008-09-07 17:08:29 +0900456 // queues get large.
457 if (!work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900458 return; // Wait till we *really* need to lock and load.
459
460 // Acquire all we can from the inter-thread queue with one lock acquisition.
initial.commit3f4a7322008-07-27 06:49:38 +0900461 {
462 AutoLock lock(incoming_queue_lock_);
darin@google.combe165ae2008-09-07 17:08:29 +0900463 if (incoming_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900464 return;
darin@chromium.orgb80ef1a2009-09-03 05:05:21 +0900465 incoming_queue_.Swap(&work_queue_); // Constant time
darin@google.combe165ae2008-09-07 17:08:29 +0900466 DCHECK(incoming_queue_.empty());
initial.commit3f4a7322008-07-27 06:49:38 +0900467 }
468}
469
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900470bool MessageLoop::DeletePendingTasks() {
471 bool did_work = !work_queue_.empty();
472 while (!work_queue_.empty()) {
473 PendingTask pending_task = work_queue_.front();
474 work_queue_.pop();
475 if (!pending_task.delayed_run_time.is_null()) {
476 // We want to delete delayed tasks in the same order in which they would
477 // normally be deleted in case of any funny dependencies between delayed
478 // tasks.
479 AddToDelayedWorkQueue(pending_task);
480 } else {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900481 // TODO(darin): Delete all tasks once it is safe to do so.
482 // Until it is totally safe, just do it when running Purify or
483 // Valgrind.
thestig@chromium.orgddb849c2010-10-28 05:03:42 +0900484#if defined(PURIFY) || defined(USE_HEAPCHECKER)
jar@chromium.org63772352009-03-12 05:06:02 +0900485 delete pending_task.task;
akalin@chromium.org839060b2010-08-03 12:06:21 +0900486#elif defined(OS_POSIX)
487 if (RUNNING_ON_VALGRIND)
488 delete pending_task.task;
489#endif // defined(OS_POSIX)
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900490 }
initial.commit3f4a7322008-07-27 06:49:38 +0900491 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900492 did_work |= !deferred_non_nestable_work_queue_.empty();
493 while (!deferred_non_nestable_work_queue_.empty()) {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900494 // TODO(darin): Delete all tasks once it is safe to do so.
495 // Until it is totaly safe, only delete them under Purify and Valgrind.
496 Task* task = NULL;
thestig@chromium.orgddb849c2010-10-28 05:03:42 +0900497#if defined(PURIFY) || defined(USE_HEAPCHECKER)
akalin@chromium.org839060b2010-08-03 12:06:21 +0900498 task = deferred_non_nestable_work_queue_.front().task;
499#elif defined(OS_POSIX)
500 if (RUNNING_ON_VALGRIND)
501 task = deferred_non_nestable_work_queue_.front().task;
502#endif
jar@chromium.org2fa6b4b2009-03-12 04:53:50 +0900503 deferred_non_nestable_work_queue_.pop();
akalin@chromium.org839060b2010-08-03 12:06:21 +0900504 if (task)
505 delete task;
initial.commit3f4a7322008-07-27 06:49:38 +0900506 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900507 did_work |= !delayed_work_queue_.empty();
508 while (!delayed_work_queue_.empty()) {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900509 Task* task = delayed_work_queue_.top().task;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900510 delayed_work_queue_.pop();
akalin@chromium.org839060b2010-08-03 12:06:21 +0900511 delete task;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900512 }
513 return did_work;
initial.commit3f4a7322008-07-27 06:49:38 +0900514}
515
darin@google.com981f3552008-08-16 12:09:05 +0900516bool MessageLoop::DoWork() {
darin@google.combe165ae2008-09-07 17:08:29 +0900517 if (!nestable_tasks_allowed_) {
518 // Task can't be executed right now.
519 return false;
520 }
521
522 for (;;) {
523 ReloadWorkQueue();
524 if (work_queue_.empty())
525 break;
526
527 // Execute oldest task.
528 do {
529 PendingTask pending_task = work_queue_.front();
530 work_queue_.pop();
531 if (!pending_task.delayed_run_time.is_null()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900532 AddToDelayedWorkQueue(pending_task);
darin@chromium.orgb2d33452008-09-24 04:19:20 +0900533 // If we changed the topmost task, then it is time to re-schedule.
jar@chromium.org40355072010-10-21 15:32:33 +0900534 if (delayed_work_queue_.top().task == pending_task.task)
darin@google.combe165ae2008-09-07 17:08:29 +0900535 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
536 } else {
537 if (DeferOrRunPendingTask(pending_task))
538 return true;
539 }
540 } while (!work_queue_.empty());
541 }
542
543 // Nothing happened.
544 return false;
darin@google.com981f3552008-08-16 12:09:05 +0900545}
546
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900547bool MessageLoop::DoDelayedWork(base::TimeTicks* next_delayed_work_time) {
jar@chromium.org40355072010-10-21 15:32:33 +0900548 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900549 recent_time_ = *next_delayed_work_time = TimeTicks();
darin@google.combe165ae2008-09-07 17:08:29 +0900550 return false;
551 }
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900552
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900553 // When we "fall behind," there will be a lot of tasks in the delayed work
jar@chromium.org94f73832010-11-05 08:23:42 +0900554 // queue that are ready to run. To increase efficiency when we fall behind,
555 // we will only call Time::Now() intermittently, and then process all tasks
556 // that are ready to run before calling it again. As a result, the more we
557 // fall behind (and have a lot of ready-to-run delayed tasks), the more
558 // efficient we'll be at handling the tasks.
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900559
560 TimeTicks next_run_time = delayed_work_queue_.top().delayed_run_time;
jar@chromium.org94f73832010-11-05 08:23:42 +0900561 if (next_run_time > recent_time_) {
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900562 recent_time_ = TimeTicks::Now(); // Get a better view of Now();
jar@chromium.org94f73832010-11-05 08:23:42 +0900563 if (next_run_time > recent_time_) {
564 *next_delayed_work_time = next_run_time;
565 return false;
566 }
darin@google.combe165ae2008-09-07 17:08:29 +0900567 }
darin@google.com981f3552008-08-16 12:09:05 +0900568
jar@chromium.org40355072010-10-21 15:32:33 +0900569 PendingTask pending_task = delayed_work_queue_.top();
570 delayed_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900571
jar@chromium.org40355072010-10-21 15:32:33 +0900572 if (!delayed_work_queue_.empty())
darin@google.combe165ae2008-09-07 17:08:29 +0900573 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
darin@google.com981f3552008-08-16 12:09:05 +0900574
darin@google.combe165ae2008-09-07 17:08:29 +0900575 return DeferOrRunPendingTask(pending_task);
darin@google.com981f3552008-08-16 12:09:05 +0900576}
577
578bool MessageLoop::DoIdleWork() {
579 if (ProcessNextDelayedNonNestableTask())
580 return true;
581
582 if (state_->quit_received)
583 pump_->Quit();
584
585 return false;
586}
587
588//------------------------------------------------------------------------------
589// MessageLoop::AutoRunState
590
591MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
592 // Make the loop reference us.
593 previous_state_ = loop_->state_;
594 if (previous_state_) {
595 run_depth = previous_state_->run_depth + 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900596 } else {
darin@google.com981f3552008-08-16 12:09:05 +0900597 run_depth = 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900598 }
darin@google.com981f3552008-08-16 12:09:05 +0900599 loop_->state_ = this;
600
601 // Initialize the other fields:
602 quit_received = false;
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900603#if !defined(OS_MACOSX)
darin@google.com981f3552008-08-16 12:09:05 +0900604 dispatcher = NULL;
605#endif
606}
607
608MessageLoop::AutoRunState::~AutoRunState() {
609 loop_->state_ = previous_state_;
darin@google.comee6fa722008-08-13 08:25:43 +0900610}
611
initial.commit3f4a7322008-07-27 06:49:38 +0900612//------------------------------------------------------------------------------
darin@google.combe165ae2008-09-07 17:08:29 +0900613// MessageLoop::PendingTask
initial.commit3f4a7322008-07-27 06:49:38 +0900614
darin@google.combe165ae2008-09-07 17:08:29 +0900615bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
616 // Since the top of a priority queue is defined as the "greatest" element, we
617 // need to invert the comparison here. We want the smaller time to be at the
618 // top of the heap.
initial.commit3f4a7322008-07-27 06:49:38 +0900619
darin@google.combe165ae2008-09-07 17:08:29 +0900620 if (delayed_run_time < other.delayed_run_time)
621 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900622
darin@google.combe165ae2008-09-07 17:08:29 +0900623 if (delayed_run_time > other.delayed_run_time)
624 return true;
initial.commit3f4a7322008-07-27 06:49:38 +0900625
darin@google.combe165ae2008-09-07 17:08:29 +0900626 // If the times happen to match, then we use the sequence number to decide.
627 // Compare the difference to support integer roll-over.
628 return (sequence_num - other.sequence_num) > 0;
initial.commit3f4a7322008-07-27 06:49:38 +0900629}
630
631//------------------------------------------------------------------------------
632// Method and data for histogramming events and actions taken by each instance
633// on each thread.
634
635// static
initial.commit3f4a7322008-07-27 06:49:38 +0900636void MessageLoop::EnableHistogrammer(bool enable) {
637 enable_histogrammer_ = enable;
638}
639
640void MessageLoop::StartHistogrammer() {
641 if (enable_histogrammer_ && !message_histogram_.get()
mad@chromium.org42f95b52010-12-23 23:40:10 +0900642 && base::StatisticsRecorder::IsActive()) {
darin@google.com981f3552008-08-16 12:09:05 +0900643 DCHECK(!thread_name_.empty());
brettw@chromium.org275c2ec2010-10-14 13:38:38 +0900644 message_histogram_ = base::LinearHistogram::FactoryGet(
645 "MsgLoop:" + thread_name_,
jar@chromium.orged5238a2009-12-28 15:59:52 +0900646 kLeastNonZeroMessageId, kMaxMessageId,
647 kNumberOfDistinctMessagesDisplayed,
648 message_histogram_->kHexRangePrintingFlag);
initial.commit3f4a7322008-07-27 06:49:38 +0900649 message_histogram_->SetRangeDescriptions(event_descriptions_);
650 }
651}
652
653void MessageLoop::HistogramEvent(int event) {
654 if (message_histogram_.get())
655 message_histogram_->Add(event);
656}
657
darin@google.comd936b5b2008-08-26 14:53:57 +0900658//------------------------------------------------------------------------------
659// MessageLoopForUI
660
661#if defined(OS_WIN)
darin@google.comd936b5b2008-08-26 14:53:57 +0900662void MessageLoopForUI::DidProcessMessage(const MSG& message) {
663 pump_win()->DidProcessMessage(message);
664}
darin@google.comd936b5b2008-08-26 14:53:57 +0900665#endif // defined(OS_WIN)
666
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900667#if !defined(OS_MACOSX) && !defined(OS_NACL)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900668void MessageLoopForUI::AddObserver(Observer* observer) {
669 pump_ui()->AddObserver(observer);
670}
671
672void MessageLoopForUI::RemoveObserver(Observer* observer) {
673 pump_ui()->RemoveObserver(observer);
674}
675
676void MessageLoopForUI::Run(Dispatcher* dispatcher) {
677 AutoRunState save_state(this);
678 state_->dispatcher = dispatcher;
679 RunHandler();
680}
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900681#endif // !defined(OS_MACOSX) && !defined(OS_NACL)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900682
darin@google.comd936b5b2008-08-26 14:53:57 +0900683//------------------------------------------------------------------------------
684// MessageLoopForIO
685
686#if defined(OS_WIN)
687
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900688void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
689 pump_io()->RegisterIOHandler(file, handler);
690}
691
rvargas@google.com73887542008-11-08 06:52:15 +0900692bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
693 return pump_io()->WaitForIOCompletion(timeout, filter);
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900694}
695
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900696#elif defined(OS_POSIX) && !defined(OS_NACL)
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900697
jeremy@chromium.orgefc0db02008-12-16 07:02:17 +0900698bool MessageLoopForIO::WatchFileDescriptor(int fd,
699 bool persistent,
700 Mode mode,
701 FileDescriptorWatcher *controller,
702 Watcher *delegate) {
703 return pump_libevent()->WatchFileDescriptor(
704 fd,
705 persistent,
706 static_cast<base::MessagePumpLibevent::Mode>(mode),
707 controller,
708 delegate);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900709}
710
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900711#endif