blob: 823670f2cdb27c69f2723c3c9684524f19660a8e [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;
jar@chromium.org9b0fb062010-11-07 07:23:29 +090032using base::TimeTicks;
dsh@google.com0f8dd262008-10-28 05:43:33 +090033
erg@chromium.orga7528522010-07-16 02:23:23 +090034namespace {
35
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090036// A lazily created thread local storage for quick access to a thread's message
37// loop, if one exists. This should be safe and free of static constructors.
erg@chromium.orga7528522010-07-16 02:23:23 +090038base::LazyInstance<base::ThreadLocalPointer<MessageLoop> > lazy_tls_ptr(
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090039 base::LINKER_INITIALIZED);
initial.commit3f4a7322008-07-27 06:49:38 +090040
initial.commit3f4a7322008-07-27 06:49:38 +090041// Logical events for Histogram profiling. Run with -message-loop-histogrammer
42// to get an accounting of messages and actions taken on each thread.
erg@chromium.orga7528522010-07-16 02:23:23 +090043const int kTaskRunEvent = 0x1;
44const int kTimerEvent = 0x2;
initial.commit3f4a7322008-07-27 06:49:38 +090045
46// Provide range of message IDs for use in histogramming and debug display.
erg@chromium.orga7528522010-07-16 02:23:23 +090047const int kLeastNonZeroMessageId = 1;
48const int kMaxMessageId = 1099;
49const int kNumberOfDistinctMessagesDisplayed = 1100;
50
51// Provide a macro that takes an expression (such as a constant, or macro
52// constant) and creates a pair to initalize an array of pairs. In this case,
53// our pair consists of the expressions value, and the "stringized" version
54// of the expression (i.e., the exrpression put in quotes). For example, if
55// we have:
56// #define FOO 2
57// #define BAR 5
58// then the following:
59// VALUE_TO_NUMBER_AND_NAME(FOO + BAR)
60// will expand to:
61// {7, "FOO + BAR"}
62// We use the resulting array as an argument to our histogram, which reads the
63// number as a bucket identifier, and proceeds to use the corresponding name
64// in the pair (i.e., the quoted string) when printing out a histogram.
65#define VALUE_TO_NUMBER_AND_NAME(name) {name, #name},
66
brettw@chromium.org275c2ec2010-10-14 13:38:38 +090067const base::LinearHistogram::DescriptionPair event_descriptions_[] = {
erg@chromium.orga7528522010-07-16 02:23:23 +090068 // Provide some pretty print capability in our histogram for our internal
69 // messages.
70
71 // A few events we handle (kindred to messages), and used to profile actions.
72 VALUE_TO_NUMBER_AND_NAME(kTaskRunEvent)
73 VALUE_TO_NUMBER_AND_NAME(kTimerEvent)
74
75 {-1, NULL} // The list must be null terminated, per API to histogram.
76};
77
78bool enable_histogrammer_ = false;
79
80} // namespace
initial.commit3f4a7322008-07-27 06:49:38 +090081
82//------------------------------------------------------------------------------
83
darin@google.com981f3552008-08-16 12:09:05 +090084#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +090085
initial.commit3f4a7322008-07-27 06:49:38 +090086// Upon a SEH exception in this thread, it restores the original unhandled
87// exception filter.
88static int SEHFilter(LPTOP_LEVEL_EXCEPTION_FILTER old_filter) {
89 ::SetUnhandledExceptionFilter(old_filter);
90 return EXCEPTION_CONTINUE_SEARCH;
91}
92
93// Retrieves a pointer to the current unhandled exception filter. There
94// is no standalone getter method.
95static LPTOP_LEVEL_EXCEPTION_FILTER GetTopSEHFilter() {
96 LPTOP_LEVEL_EXCEPTION_FILTER top_filter = NULL;
97 top_filter = ::SetUnhandledExceptionFilter(0);
98 ::SetUnhandledExceptionFilter(top_filter);
99 return top_filter;
100}
101
darin@google.com981f3552008-08-16 12:09:05 +0900102#endif // defined(OS_WIN)
103
initial.commit3f4a7322008-07-27 06:49:38 +0900104//------------------------------------------------------------------------------
105
erg@chromium.org493f5f62010-07-16 06:03:54 +0900106MessageLoop::TaskObserver::TaskObserver() {
107}
108
109MessageLoop::TaskObserver::~TaskObserver() {
110}
111
112MessageLoop::DestructionObserver::~DestructionObserver() {
113}
114
115//------------------------------------------------------------------------------
116
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +0900117// static
118MessageLoop* MessageLoop::current() {
119 // TODO(darin): sadly, we cannot enable this yet since people call us even
120 // when they have no intention of using us.
erg@google.combf6ce9f2010-01-27 08:08:02 +0900121 // DCHECK(loop) << "Ouch, did you forget to initialize me?";
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +0900122 return lazy_tls_ptr.Pointer()->Get();
123}
124
darin@google.comd936b5b2008-08-26 14:53:57 +0900125MessageLoop::MessageLoop(Type type)
126 : type_(type),
darin@google.comee6fa722008-08-13 08:25:43 +0900127 nestable_tasks_allowed_(true),
darin@google.com12d40bb2008-08-20 03:36:23 +0900128 exception_restoration_(false),
darin@google.combe165ae2008-09-07 17:08:29 +0900129 state_(NULL),
130 next_sequence_num_(0) {
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +0900131 DCHECK(!current()) << "should only have one message loop per thread";
132 lazy_tls_ptr.Pointer()->Set(this);
darin@google.comd936b5b2008-08-26 14:53:57 +0900133
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900134// TODO(rvargas): Get rid of the OS guards.
darin@google.com981f3552008-08-16 12:09:05 +0900135#if defined(OS_WIN)
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900136#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
137#define MESSAGE_PUMP_IO new base::MessagePumpForIO()
138#elif defined(OS_MACOSX)
139#define MESSAGE_PUMP_UI base::MessagePumpMac::Create()
140#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
rjkroege@google.com3080f442010-10-23 01:17:47 +0900141#elif defined(TOUCH_UI)
bryeung@google.come6bb34b2010-11-04 07:11:41 +0900142// TODO(sadrul): enable the new message pump when ready
143#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
rjkroege@google.com3080f442010-10-23 01:17:47 +0900144#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900145#elif defined(OS_POSIX) // POSIX but not MACOSX.
146#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
147#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900148#else
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900149#error Not implemented
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900150#endif
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900151
152 if (type_ == TYPE_UI) {
153 pump_ = MESSAGE_PUMP_UI;
dsh@google.com119a2522008-10-04 01:52:59 +0900154 } else if (type_ == TYPE_IO) {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900155 pump_ = MESSAGE_PUMP_IO;
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900156 } else {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900157 DCHECK_EQ(TYPE_DEFAULT, type_);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900158 pump_ = new base::MessagePumpDefault();
159 }
initial.commit3f4a7322008-07-27 06:49:38 +0900160}
161
162MessageLoop::~MessageLoop() {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900163 DCHECK_EQ(this, current());
darin@google.com965e5342008-08-06 08:16:41 +0900164
darin@google.com0e500502008-09-09 14:55:35 +0900165 DCHECK(!state_);
166
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900167 // Clean up any unprocessed tasks, but take care: deleting a task could
168 // result in the addition of more tasks (e.g., via DeleteSoon). We set a
169 // limit on the number of times we will allow a deleted task to generate more
170 // tasks. Normally, we should only pass through this loop once or twice. If
171 // we end up hitting the loop limit, then it is probably due to one task that
172 // is being stubborn. Inspect the queues to see who is left.
173 bool did_work;
174 for (int i = 0; i < 100; ++i) {
175 DeletePendingTasks();
176 ReloadWorkQueue();
177 // If we end up with empty queues, then break out of the loop.
178 did_work = DeletePendingTasks();
179 if (!did_work)
180 break;
darin@google.com0e500502008-09-09 14:55:35 +0900181 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900182 DCHECK(!did_work);
183
sanjeevr@chromium.org03b44d52010-11-30 09:25:29 +0900184 // Let interested parties have one last shot at accessing this.
185 FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
186 WillDestroyCurrentMessageLoop());
187
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900188 // OK, now make it so that no one can find us.
deanm@chromium.orge4cc5922008-09-10 20:14:56 +0900189 lazy_tls_ptr.Pointer()->Set(NULL);
initial.commit3f4a7322008-07-27 06:49:38 +0900190}
191
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900192void MessageLoop::AddDestructionObserver(
193 DestructionObserver* destruction_observer) {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900194 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900195 destruction_observers_.AddObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900196}
197
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900198void MessageLoop::RemoveDestructionObserver(
199 DestructionObserver* destruction_observer) {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900200 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900201 destruction_observers_.RemoveObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900202}
203
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900204void MessageLoop::AddTaskObserver(TaskObserver* task_observer) {
willchan@chromium.orga9047632010-06-10 06:20:41 +0900205 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900206 task_observers_.AddObserver(task_observer);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900207}
208
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900209void MessageLoop::RemoveTaskObserver(TaskObserver* task_observer) {
willchan@chromium.orga9047632010-06-10 06:20:41 +0900210 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900211 task_observers_.RemoveObserver(task_observer);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900212}
213
darin@google.com6ddeb842008-08-15 16:31:20 +0900214void MessageLoop::Run() {
darin@google.com981f3552008-08-16 12:09:05 +0900215 AutoRunState save_state(this);
216 RunHandler();
darin@google.com6ddeb842008-08-15 16:31:20 +0900217}
218
jar@google.com9239e022008-07-31 22:10:20 +0900219void MessageLoop::RunAllPending() {
darin@google.com981f3552008-08-16 12:09:05 +0900220 AutoRunState save_state(this);
221 state_->quit_received = true; // Means run until we would otherwise block.
222 RunHandler();
initial.commit3f4a7322008-07-27 06:49:38 +0900223}
224
225// Runs the loop in two different SEH modes:
226// enable_SEH_restoration_ = false : any unhandled exception goes to the last
227// one that calls SetUnhandledExceptionFilter().
228// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
229// that was existed before the loop was run.
darin@google.com981f3552008-08-16 12:09:05 +0900230void MessageLoop::RunHandler() {
231#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +0900232 if (exception_restoration_) {
stoyan@google.com283facb2009-10-27 03:15:59 +0900233 RunInternalInSEHFrame();
darin@google.com981f3552008-08-16 12:09:05 +0900234 return;
initial.commit3f4a7322008-07-27 06:49:38 +0900235 }
darin@google.com981f3552008-08-16 12:09:05 +0900236#endif
237
238 RunInternal();
initial.commit3f4a7322008-07-27 06:49:38 +0900239}
stoyan@google.com283facb2009-10-27 03:15:59 +0900240//------------------------------------------------------------------------------
241#if defined(OS_WIN)
242__declspec(noinline) void MessageLoop::RunInternalInSEHFrame() {
243 LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
244 __try {
245 RunInternal();
246 } __except(SEHFilter(current_filter)) {
247 }
248 return;
249}
250#endif
initial.commit3f4a7322008-07-27 06:49:38 +0900251//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900252
darin@google.com981f3552008-08-16 12:09:05 +0900253void MessageLoop::RunInternal() {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900254 DCHECK_EQ(this, current());
darin@google.com981f3552008-08-16 12:09:05 +0900255
initial.commit3f4a7322008-07-27 06:49:38 +0900256 StartHistogrammer();
257
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900258#if !defined(OS_MACOSX)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900259 if (state_->dispatcher && type() == TYPE_UI) {
260 static_cast<base::MessagePumpForUI*>(pump_.get())->
261 RunWithDispatcher(this, state_->dispatcher);
darin@google.com981f3552008-08-16 12:09:05 +0900262 return;
jar@google.com9239e022008-07-31 22:10:20 +0900263 }
darin@google.com981f3552008-08-16 12:09:05 +0900264#endif
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900265
darin@google.com981f3552008-08-16 12:09:05 +0900266 pump_->Run(this);
jar@google.comfbaaf692008-07-30 16:50:53 +0900267}
jar@google.com7ff36e62008-07-30 15:58:56 +0900268
jar@google.comb4d1bff2008-07-31 04:03:59 +0900269//------------------------------------------------------------------------------
270// Wrapper functions for use in above message loop framework.
271
initial.commit3f4a7322008-07-27 06:49:38 +0900272bool MessageLoop::ProcessNextDelayedNonNestableTask() {
darin@google.com981f3552008-08-16 12:09:05 +0900273 if (state_->run_depth != 1)
initial.commit3f4a7322008-07-27 06:49:38 +0900274 return false;
275
darin@google.combe165ae2008-09-07 17:08:29 +0900276 if (deferred_non_nestable_work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900277 return false;
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900278
darin@google.combe165ae2008-09-07 17:08:29 +0900279 Task* task = deferred_non_nestable_work_queue_.front().task;
280 deferred_non_nestable_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900281
darin@google.combe165ae2008-09-07 17:08:29 +0900282 RunTask(task);
initial.commit3f4a7322008-07-27 06:49:38 +0900283 return true;
284}
285
initial.commit3f4a7322008-07-27 06:49:38 +0900286//------------------------------------------------------------------------------
287
288void MessageLoop::Quit() {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900289 DCHECK_EQ(this, current());
darin@google.com981f3552008-08-16 12:09:05 +0900290 if (state_) {
291 state_->quit_received = true;
292 } else {
293 NOTREACHED() << "Must be inside Run to call Quit";
initial.commit3f4a7322008-07-27 06:49:38 +0900294 }
initial.commit3f4a7322008-07-27 06:49:38 +0900295}
296
darin@chromium.orgd70a12c2010-02-23 16:12:22 +0900297void MessageLoop::QuitNow() {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900298 DCHECK_EQ(this, current());
darin@chromium.orgd70a12c2010-02-23 16:12:22 +0900299 if (state_) {
300 pump_->Quit();
301 } else {
302 NOTREACHED() << "Must be inside Run to call Quit";
303 }
304}
305
darin@google.combe165ae2008-09-07 17:08:29 +0900306void MessageLoop::PostTask(
307 const tracked_objects::Location& from_here, Task* task) {
308 PostTask_Helper(from_here, task, 0, true);
309}
310
311void MessageLoop::PostDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900312 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
darin@google.combe165ae2008-09-07 17:08:29 +0900313 PostTask_Helper(from_here, task, delay_ms, true);
314}
315
316void MessageLoop::PostNonNestableTask(
317 const tracked_objects::Location& from_here, Task* task) {
318 PostTask_Helper(from_here, task, 0, false);
319}
320
321void MessageLoop::PostNonNestableDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900322 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
darin@google.combe165ae2008-09-07 17:08:29 +0900323 PostTask_Helper(from_here, task, delay_ms, false);
324}
325
initial.commit3f4a7322008-07-27 06:49:38 +0900326// Possibly called on a background thread!
darin@google.combe165ae2008-09-07 17:08:29 +0900327void MessageLoop::PostTask_Helper(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900328 const tracked_objects::Location& from_here, Task* task, int64 delay_ms,
darin@google.combe165ae2008-09-07 17:08:29 +0900329 bool nestable) {
initial.commit3f4a7322008-07-27 06:49:38 +0900330 task->SetBirthPlace(from_here);
darin@google.com0795f572008-08-30 09:22:48 +0900331
darin@google.combe165ae2008-09-07 17:08:29 +0900332 PendingTask pending_task(task, nestable);
darin@google.com0795f572008-08-30 09:22:48 +0900333
334 if (delay_ms > 0) {
darin@google.combe165ae2008-09-07 17:08:29 +0900335 pending_task.delayed_run_time =
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900336 TimeTicks::Now() + TimeDelta::FromMilliseconds(delay_ms);
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900337
338#if defined(OS_WIN)
339 if (high_resolution_timer_expiration_.is_null()) {
340 // Windows timers are granular to 15.6ms. If we only set high-res
341 // timers for those under 15.6ms, then a 18ms timer ticks at ~32ms,
342 // which as a percentage is pretty inaccurate. So enable high
343 // res timers for any timer which is within 2x of the granularity.
344 // This is a tradeoff between accuracy and power management.
345 bool needs_high_res_timers =
346 delay_ms < (2 * Time::kMinLowResolutionThresholdMs);
347 if (needs_high_res_timers) {
phajdan.jr@chromium.org3337f3d2010-10-20 19:50:38 +0900348 Time::ActivateHighResolutionTimer(true);
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900349 high_resolution_timer_expiration_ = TimeTicks::Now() +
phajdan.jr@chromium.org3337f3d2010-10-20 19:50:38 +0900350 TimeDelta::FromMilliseconds(kHighResolutionTimerModeLeaseTimeMs);
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900351 }
352 }
353#endif
darin@google.com0795f572008-08-30 09:22:48 +0900354 } else {
jar@chromium.orged5238a2009-12-28 15:59:52 +0900355 DCHECK_EQ(delay_ms, 0) << "delay should not be negative";
darin@google.com0795f572008-08-30 09:22:48 +0900356 }
357
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900358#if defined(OS_WIN)
359 if (!high_resolution_timer_expiration_.is_null()) {
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900360 if (TimeTicks::Now() > high_resolution_timer_expiration_) {
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900361 Time::ActivateHighResolutionTimer(false);
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900362 high_resolution_timer_expiration_ = TimeTicks();
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900363 }
364 }
365#endif
366
initial.commit3f4a7322008-07-27 06:49:38 +0900367 // Warning: Don't try to short-circuit, and handle this thread's tasks more
368 // directly, as it could starve handling of foreign threads. Put every task
369 // into this queue.
370
darin@google.com981f3552008-08-16 12:09:05 +0900371 scoped_refptr<base::MessagePump> pump;
initial.commit3f4a7322008-07-27 06:49:38 +0900372 {
darin@google.com981f3552008-08-16 12:09:05 +0900373 AutoLock locked(incoming_queue_lock_);
374
darin@google.combe165ae2008-09-07 17:08:29 +0900375 bool was_empty = incoming_queue_.empty();
376 incoming_queue_.push(pending_task);
initial.commit3f4a7322008-07-27 06:49:38 +0900377 if (!was_empty)
378 return; // Someone else should have started the sub-pump.
379
darin@google.com981f3552008-08-16 12:09:05 +0900380 pump = pump_;
darin@google.com6ddeb842008-08-15 16:31:20 +0900381 }
darin@google.com981f3552008-08-16 12:09:05 +0900382 // Since the incoming_queue_ may contain a task that destroys this message
383 // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
384 // We use a stack-based reference to the message pump so that we can call
385 // ScheduleWork outside of incoming_queue_lock_.
darin@google.com6ddeb842008-08-15 16:31:20 +0900386
darin@google.com981f3552008-08-16 12:09:05 +0900387 pump->ScheduleWork();
initial.commit3f4a7322008-07-27 06:49:38 +0900388}
389
390void MessageLoop::SetNestableTasksAllowed(bool allowed) {
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900391 if (nestable_tasks_allowed_ != allowed) {
392 nestable_tasks_allowed_ = allowed;
393 if (!nestable_tasks_allowed_)
394 return;
395 // Start the native pump if we are not already pumping.
darin@google.com981f3552008-08-16 12:09:05 +0900396 pump_->ScheduleWork();
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900397 }
initial.commit3f4a7322008-07-27 06:49:38 +0900398}
399
400bool MessageLoop::NestableTasksAllowed() const {
401 return nestable_tasks_allowed_;
402}
403
jcampan@chromium.orgeac57172009-07-02 04:53:59 +0900404bool MessageLoop::IsNested() {
405 return state_->run_depth > 1;
406}
407
initial.commit3f4a7322008-07-27 06:49:38 +0900408//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900409
initial.commit3f4a7322008-07-27 06:49:38 +0900410void MessageLoop::RunTask(Task* task) {
initial.commit3f4a7322008-07-27 06:49:38 +0900411 DCHECK(nestable_tasks_allowed_);
412 // Execute the task and assume the worst: It is probably not reentrant.
413 nestable_tasks_allowed_ = false;
darin@google.combe165ae2008-09-07 17:08:29 +0900414
415 HistogramEvent(kTaskRunEvent);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900416 FOR_EACH_OBSERVER(TaskObserver, task_observers_,
davemoore@chromium.orgeb5f68f2010-10-27 08:40:48 +0900417 WillProcessTask(task));
darin@google.combe165ae2008-09-07 17:08:29 +0900418 task->Run();
davemoore@chromium.orgeb5f68f2010-10-27 08:40:48 +0900419 FOR_EACH_OBSERVER(TaskObserver, task_observers_, DidProcessTask(task));
darin@google.combe165ae2008-09-07 17:08:29 +0900420 delete task;
421
422 nestable_tasks_allowed_ = true;
initial.commit3f4a7322008-07-27 06:49:38 +0900423}
424
darin@google.combe165ae2008-09-07 17:08:29 +0900425bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) {
426 if (pending_task.nestable || state_->run_depth == 1) {
427 RunTask(pending_task.task);
428 // Show that we ran a task (Note: a new one might arrive as a
429 // consequence!).
430 return true;
431 }
432
433 // We couldn't run the task now because we're in a nested message loop
434 // and the task isn't nestable.
435 deferred_non_nestable_work_queue_.push(pending_task);
436 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900437}
438
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900439void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
440 // Move to the delayed work queue. Initialize the sequence number
441 // before inserting into the delayed_work_queue_. The sequence number
442 // is used to faciliate FIFO sorting when two tasks have the same
443 // delayed_run_time value.
444 PendingTask new_pending_task(pending_task);
445 new_pending_task.sequence_num = next_sequence_num_++;
446 delayed_work_queue_.push(new_pending_task);
447}
448
initial.commit3f4a7322008-07-27 06:49:38 +0900449void MessageLoop::ReloadWorkQueue() {
450 // We can improve performance of our loading tasks from incoming_queue_ to
darin@google.com981f3552008-08-16 12:09:05 +0900451 // work_queue_ by waiting until the last minute (work_queue_ is empty) to
452 // load. That reduces the number of locks-per-task significantly when our
darin@google.combe165ae2008-09-07 17:08:29 +0900453 // queues get large.
454 if (!work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900455 return; // Wait till we *really* need to lock and load.
456
457 // Acquire all we can from the inter-thread queue with one lock acquisition.
initial.commit3f4a7322008-07-27 06:49:38 +0900458 {
459 AutoLock lock(incoming_queue_lock_);
darin@google.combe165ae2008-09-07 17:08:29 +0900460 if (incoming_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900461 return;
darin@chromium.orgb80ef1a2009-09-03 05:05:21 +0900462 incoming_queue_.Swap(&work_queue_); // Constant time
darin@google.combe165ae2008-09-07 17:08:29 +0900463 DCHECK(incoming_queue_.empty());
initial.commit3f4a7322008-07-27 06:49:38 +0900464 }
465}
466
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900467bool MessageLoop::DeletePendingTasks() {
468 bool did_work = !work_queue_.empty();
469 while (!work_queue_.empty()) {
470 PendingTask pending_task = work_queue_.front();
471 work_queue_.pop();
472 if (!pending_task.delayed_run_time.is_null()) {
473 // We want to delete delayed tasks in the same order in which they would
474 // normally be deleted in case of any funny dependencies between delayed
475 // tasks.
476 AddToDelayedWorkQueue(pending_task);
477 } else {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900478 // TODO(darin): Delete all tasks once it is safe to do so.
479 // Until it is totally safe, just do it when running Purify or
480 // Valgrind.
thestig@chromium.orgddb849c2010-10-28 05:03:42 +0900481#if defined(PURIFY) || defined(USE_HEAPCHECKER)
jar@chromium.org63772352009-03-12 05:06:02 +0900482 delete pending_task.task;
akalin@chromium.org839060b2010-08-03 12:06:21 +0900483#elif defined(OS_POSIX)
484 if (RUNNING_ON_VALGRIND)
485 delete pending_task.task;
486#endif // defined(OS_POSIX)
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900487 }
initial.commit3f4a7322008-07-27 06:49:38 +0900488 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900489 did_work |= !deferred_non_nestable_work_queue_.empty();
490 while (!deferred_non_nestable_work_queue_.empty()) {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900491 // TODO(darin): Delete all tasks once it is safe to do so.
492 // Until it is totaly safe, only delete them under Purify and Valgrind.
493 Task* task = NULL;
thestig@chromium.orgddb849c2010-10-28 05:03:42 +0900494#if defined(PURIFY) || defined(USE_HEAPCHECKER)
akalin@chromium.org839060b2010-08-03 12:06:21 +0900495 task = deferred_non_nestable_work_queue_.front().task;
496#elif defined(OS_POSIX)
497 if (RUNNING_ON_VALGRIND)
498 task = deferred_non_nestable_work_queue_.front().task;
499#endif
jar@chromium.org2fa6b4b2009-03-12 04:53:50 +0900500 deferred_non_nestable_work_queue_.pop();
akalin@chromium.org839060b2010-08-03 12:06:21 +0900501 if (task)
502 delete task;
initial.commit3f4a7322008-07-27 06:49:38 +0900503 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900504 did_work |= !delayed_work_queue_.empty();
505 while (!delayed_work_queue_.empty()) {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900506 Task* task = delayed_work_queue_.top().task;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900507 delayed_work_queue_.pop();
akalin@chromium.org839060b2010-08-03 12:06:21 +0900508 delete task;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900509 }
510 return did_work;
initial.commit3f4a7322008-07-27 06:49:38 +0900511}
512
darin@google.com981f3552008-08-16 12:09:05 +0900513bool MessageLoop::DoWork() {
darin@google.combe165ae2008-09-07 17:08:29 +0900514 if (!nestable_tasks_allowed_) {
515 // Task can't be executed right now.
516 return false;
517 }
518
519 for (;;) {
520 ReloadWorkQueue();
521 if (work_queue_.empty())
522 break;
523
524 // Execute oldest task.
525 do {
526 PendingTask pending_task = work_queue_.front();
527 work_queue_.pop();
528 if (!pending_task.delayed_run_time.is_null()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900529 AddToDelayedWorkQueue(pending_task);
darin@chromium.orgb2d33452008-09-24 04:19:20 +0900530 // If we changed the topmost task, then it is time to re-schedule.
jar@chromium.org40355072010-10-21 15:32:33 +0900531 if (delayed_work_queue_.top().task == pending_task.task)
darin@google.combe165ae2008-09-07 17:08:29 +0900532 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
533 } else {
534 if (DeferOrRunPendingTask(pending_task))
535 return true;
536 }
537 } while (!work_queue_.empty());
538 }
539
540 // Nothing happened.
541 return false;
darin@google.com981f3552008-08-16 12:09:05 +0900542}
543
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900544bool MessageLoop::DoDelayedWork(base::TimeTicks* next_delayed_work_time) {
jar@chromium.org40355072010-10-21 15:32:33 +0900545 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900546 recent_time_ = *next_delayed_work_time = TimeTicks();
darin@google.combe165ae2008-09-07 17:08:29 +0900547 return false;
548 }
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900549
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900550 // When we "fall behind," there will be a lot of tasks in the delayed work
jar@chromium.org94f73832010-11-05 08:23:42 +0900551 // queue that are ready to run. To increase efficiency when we fall behind,
552 // we will only call Time::Now() intermittently, and then process all tasks
553 // that are ready to run before calling it again. As a result, the more we
554 // fall behind (and have a lot of ready-to-run delayed tasks), the more
555 // efficient we'll be at handling the tasks.
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900556
557 TimeTicks next_run_time = delayed_work_queue_.top().delayed_run_time;
jar@chromium.org94f73832010-11-05 08:23:42 +0900558 if (next_run_time > recent_time_) {
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900559 recent_time_ = TimeTicks::Now(); // Get a better view of Now();
jar@chromium.org94f73832010-11-05 08:23:42 +0900560 if (next_run_time > recent_time_) {
561 *next_delayed_work_time = next_run_time;
562 return false;
563 }
darin@google.combe165ae2008-09-07 17:08:29 +0900564 }
darin@google.com981f3552008-08-16 12:09:05 +0900565
jar@chromium.org40355072010-10-21 15:32:33 +0900566 PendingTask pending_task = delayed_work_queue_.top();
567 delayed_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900568
jar@chromium.org40355072010-10-21 15:32:33 +0900569 if (!delayed_work_queue_.empty())
darin@google.combe165ae2008-09-07 17:08:29 +0900570 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
darin@google.com981f3552008-08-16 12:09:05 +0900571
darin@google.combe165ae2008-09-07 17:08:29 +0900572 return DeferOrRunPendingTask(pending_task);
darin@google.com981f3552008-08-16 12:09:05 +0900573}
574
575bool MessageLoop::DoIdleWork() {
576 if (ProcessNextDelayedNonNestableTask())
577 return true;
578
579 if (state_->quit_received)
580 pump_->Quit();
581
582 return false;
583}
584
585//------------------------------------------------------------------------------
586// MessageLoop::AutoRunState
587
588MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
589 // Make the loop reference us.
590 previous_state_ = loop_->state_;
591 if (previous_state_) {
592 run_depth = previous_state_->run_depth + 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900593 } else {
darin@google.com981f3552008-08-16 12:09:05 +0900594 run_depth = 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900595 }
darin@google.com981f3552008-08-16 12:09:05 +0900596 loop_->state_ = this;
597
598 // Initialize the other fields:
599 quit_received = false;
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900600#if !defined(OS_MACOSX)
darin@google.com981f3552008-08-16 12:09:05 +0900601 dispatcher = NULL;
602#endif
603}
604
605MessageLoop::AutoRunState::~AutoRunState() {
606 loop_->state_ = previous_state_;
darin@google.comee6fa722008-08-13 08:25:43 +0900607}
608
initial.commit3f4a7322008-07-27 06:49:38 +0900609//------------------------------------------------------------------------------
darin@google.combe165ae2008-09-07 17:08:29 +0900610// MessageLoop::PendingTask
initial.commit3f4a7322008-07-27 06:49:38 +0900611
darin@google.combe165ae2008-09-07 17:08:29 +0900612bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
613 // Since the top of a priority queue is defined as the "greatest" element, we
614 // need to invert the comparison here. We want the smaller time to be at the
615 // top of the heap.
initial.commit3f4a7322008-07-27 06:49:38 +0900616
darin@google.combe165ae2008-09-07 17:08:29 +0900617 if (delayed_run_time < other.delayed_run_time)
618 return false;
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 true;
initial.commit3f4a7322008-07-27 06:49:38 +0900622
darin@google.combe165ae2008-09-07 17:08:29 +0900623 // If the times happen to match, then we use the sequence number to decide.
624 // Compare the difference to support integer roll-over.
625 return (sequence_num - other.sequence_num) > 0;
initial.commit3f4a7322008-07-27 06:49:38 +0900626}
627
628//------------------------------------------------------------------------------
629// Method and data for histogramming events and actions taken by each instance
630// on each thread.
631
632// static
initial.commit3f4a7322008-07-27 06:49:38 +0900633void MessageLoop::EnableHistogrammer(bool enable) {
634 enable_histogrammer_ = enable;
635}
636
637void MessageLoop::StartHistogrammer() {
638 if (enable_histogrammer_ && !message_histogram_.get()
brettw@chromium.org275c2ec2010-10-14 13:38:38 +0900639 && base::StatisticsRecorder::WasStarted()) {
darin@google.com981f3552008-08-16 12:09:05 +0900640 DCHECK(!thread_name_.empty());
brettw@chromium.org275c2ec2010-10-14 13:38:38 +0900641 message_histogram_ = base::LinearHistogram::FactoryGet(
642 "MsgLoop:" + thread_name_,
jar@chromium.orged5238a2009-12-28 15:59:52 +0900643 kLeastNonZeroMessageId, kMaxMessageId,
644 kNumberOfDistinctMessagesDisplayed,
645 message_histogram_->kHexRangePrintingFlag);
initial.commit3f4a7322008-07-27 06:49:38 +0900646 message_histogram_->SetRangeDescriptions(event_descriptions_);
647 }
648}
649
650void MessageLoop::HistogramEvent(int event) {
651 if (message_histogram_.get())
652 message_histogram_->Add(event);
653}
654
darin@google.comd936b5b2008-08-26 14:53:57 +0900655//------------------------------------------------------------------------------
656// MessageLoopForUI
657
658#if defined(OS_WIN)
darin@google.comd936b5b2008-08-26 14:53:57 +0900659void MessageLoopForUI::DidProcessMessage(const MSG& message) {
660 pump_win()->DidProcessMessage(message);
661}
darin@google.comd936b5b2008-08-26 14:53:57 +0900662#endif // defined(OS_WIN)
663
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900664#if !defined(OS_MACOSX)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900665void MessageLoopForUI::AddObserver(Observer* observer) {
666 pump_ui()->AddObserver(observer);
667}
668
669void MessageLoopForUI::RemoveObserver(Observer* observer) {
670 pump_ui()->RemoveObserver(observer);
671}
672
673void MessageLoopForUI::Run(Dispatcher* dispatcher) {
674 AutoRunState save_state(this);
675 state_->dispatcher = dispatcher;
676 RunHandler();
677}
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900678#endif // !defined(OS_MACOSX)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900679
darin@google.comd936b5b2008-08-26 14:53:57 +0900680//------------------------------------------------------------------------------
681// MessageLoopForIO
682
683#if defined(OS_WIN)
684
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900685void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
686 pump_io()->RegisterIOHandler(file, handler);
687}
688
rvargas@google.com73887542008-11-08 06:52:15 +0900689bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
690 return pump_io()->WaitForIOCompletion(timeout, filter);
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900691}
692
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900693#elif defined(OS_POSIX)
694
jeremy@chromium.orgefc0db02008-12-16 07:02:17 +0900695bool MessageLoopForIO::WatchFileDescriptor(int fd,
696 bool persistent,
697 Mode mode,
698 FileDescriptorWatcher *controller,
699 Watcher *delegate) {
700 return pump_libevent()->WatchFileDescriptor(
701 fd,
702 persistent,
703 static_cast<base::MessagePumpLibevent::Mode>(mode),
704 controller,
705 delegate);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900706}
707
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900708#endif