blob: 4c818065fdbde74be10de55b2a8639ae365ed807 [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)
sadrul@chromium.orgcff2c642010-12-17 04:43:30 +0900142#define MESSAGE_PUMP_UI new base::MessagePumpGlibX()
rjkroege@google.com3080f442010-10-23 01:17:47 +0900143#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900144#elif defined(OS_NACL)
145// Currently NaCl doesn't have a UI or an IO MessageLoop.
146// TODO(abarth): Figure out if we need these.
147#define MESSAGE_PUMP_UI NULL
148#define MESSAGE_PUMP_IO NULL
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900149#elif defined(OS_POSIX) // POSIX but not MACOSX.
150#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
151#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900152#else
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900153#error Not implemented
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900154#endif
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900155
156 if (type_ == TYPE_UI) {
157 pump_ = MESSAGE_PUMP_UI;
dsh@google.com119a2522008-10-04 01:52:59 +0900158 } else if (type_ == TYPE_IO) {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900159 pump_ = MESSAGE_PUMP_IO;
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900160 } else {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900161 DCHECK_EQ(TYPE_DEFAULT, type_);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900162 pump_ = new base::MessagePumpDefault();
163 }
initial.commit3f4a7322008-07-27 06:49:38 +0900164}
165
166MessageLoop::~MessageLoop() {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900167 DCHECK_EQ(this, current());
darin@google.com965e5342008-08-06 08:16:41 +0900168
darin@google.com0e500502008-09-09 14:55:35 +0900169 DCHECK(!state_);
170
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900171 // Clean up any unprocessed tasks, but take care: deleting a task could
172 // result in the addition of more tasks (e.g., via DeleteSoon). We set a
173 // limit on the number of times we will allow a deleted task to generate more
174 // tasks. Normally, we should only pass through this loop once or twice. If
175 // we end up hitting the loop limit, then it is probably due to one task that
176 // is being stubborn. Inspect the queues to see who is left.
177 bool did_work;
178 for (int i = 0; i < 100; ++i) {
179 DeletePendingTasks();
180 ReloadWorkQueue();
181 // If we end up with empty queues, then break out of the loop.
182 did_work = DeletePendingTasks();
183 if (!did_work)
184 break;
darin@google.com0e500502008-09-09 14:55:35 +0900185 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900186 DCHECK(!did_work);
187
sanjeevr@chromium.org03b44d52010-11-30 09:25:29 +0900188 // Let interested parties have one last shot at accessing this.
189 FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
190 WillDestroyCurrentMessageLoop());
191
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900192 // OK, now make it so that no one can find us.
deanm@chromium.orge4cc5922008-09-10 20:14:56 +0900193 lazy_tls_ptr.Pointer()->Set(NULL);
initial.commit3f4a7322008-07-27 06:49:38 +0900194}
195
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900196void MessageLoop::AddDestructionObserver(
197 DestructionObserver* destruction_observer) {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900198 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900199 destruction_observers_.AddObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900200}
201
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900202void MessageLoop::RemoveDestructionObserver(
203 DestructionObserver* destruction_observer) {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900204 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900205 destruction_observers_.RemoveObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900206}
207
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900208void MessageLoop::AddTaskObserver(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_.AddObserver(task_observer);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900211}
212
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900213void MessageLoop::RemoveTaskObserver(TaskObserver* task_observer) {
willchan@chromium.orga9047632010-06-10 06:20:41 +0900214 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900215 task_observers_.RemoveObserver(task_observer);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900216}
217
darin@google.com6ddeb842008-08-15 16:31:20 +0900218void MessageLoop::Run() {
darin@google.com981f3552008-08-16 12:09:05 +0900219 AutoRunState save_state(this);
220 RunHandler();
darin@google.com6ddeb842008-08-15 16:31:20 +0900221}
222
jar@google.com9239e022008-07-31 22:10:20 +0900223void MessageLoop::RunAllPending() {
darin@google.com981f3552008-08-16 12:09:05 +0900224 AutoRunState save_state(this);
225 state_->quit_received = true; // Means run until we would otherwise block.
226 RunHandler();
initial.commit3f4a7322008-07-27 06:49:38 +0900227}
228
229// Runs the loop in two different SEH modes:
230// enable_SEH_restoration_ = false : any unhandled exception goes to the last
231// one that calls SetUnhandledExceptionFilter().
232// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
233// that was existed before the loop was run.
darin@google.com981f3552008-08-16 12:09:05 +0900234void MessageLoop::RunHandler() {
235#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +0900236 if (exception_restoration_) {
stoyan@google.com283facb2009-10-27 03:15:59 +0900237 RunInternalInSEHFrame();
darin@google.com981f3552008-08-16 12:09:05 +0900238 return;
initial.commit3f4a7322008-07-27 06:49:38 +0900239 }
darin@google.com981f3552008-08-16 12:09:05 +0900240#endif
241
242 RunInternal();
initial.commit3f4a7322008-07-27 06:49:38 +0900243}
stoyan@google.com283facb2009-10-27 03:15:59 +0900244//------------------------------------------------------------------------------
245#if defined(OS_WIN)
246__declspec(noinline) void MessageLoop::RunInternalInSEHFrame() {
247 LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
248 __try {
249 RunInternal();
250 } __except(SEHFilter(current_filter)) {
251 }
252 return;
253}
254#endif
initial.commit3f4a7322008-07-27 06:49:38 +0900255//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900256
darin@google.com981f3552008-08-16 12:09:05 +0900257void MessageLoop::RunInternal() {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900258 DCHECK_EQ(this, current());
darin@google.com981f3552008-08-16 12:09:05 +0900259
initial.commit3f4a7322008-07-27 06:49:38 +0900260 StartHistogrammer();
261
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900262#if !defined(OS_MACOSX)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900263 if (state_->dispatcher && type() == TYPE_UI) {
264 static_cast<base::MessagePumpForUI*>(pump_.get())->
265 RunWithDispatcher(this, state_->dispatcher);
darin@google.com981f3552008-08-16 12:09:05 +0900266 return;
jar@google.com9239e022008-07-31 22:10:20 +0900267 }
darin@google.com981f3552008-08-16 12:09:05 +0900268#endif
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900269
darin@google.com981f3552008-08-16 12:09:05 +0900270 pump_->Run(this);
jar@google.comfbaaf692008-07-30 16:50:53 +0900271}
jar@google.com7ff36e62008-07-30 15:58:56 +0900272
jar@google.comb4d1bff2008-07-31 04:03:59 +0900273//------------------------------------------------------------------------------
274// Wrapper functions for use in above message loop framework.
275
initial.commit3f4a7322008-07-27 06:49:38 +0900276bool MessageLoop::ProcessNextDelayedNonNestableTask() {
darin@google.com981f3552008-08-16 12:09:05 +0900277 if (state_->run_depth != 1)
initial.commit3f4a7322008-07-27 06:49:38 +0900278 return false;
279
darin@google.combe165ae2008-09-07 17:08:29 +0900280 if (deferred_non_nestable_work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900281 return false;
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900282
darin@google.combe165ae2008-09-07 17:08:29 +0900283 Task* task = deferred_non_nestable_work_queue_.front().task;
284 deferred_non_nestable_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900285
darin@google.combe165ae2008-09-07 17:08:29 +0900286 RunTask(task);
initial.commit3f4a7322008-07-27 06:49:38 +0900287 return true;
288}
289
initial.commit3f4a7322008-07-27 06:49:38 +0900290//------------------------------------------------------------------------------
291
292void MessageLoop::Quit() {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900293 DCHECK_EQ(this, current());
darin@google.com981f3552008-08-16 12:09:05 +0900294 if (state_) {
295 state_->quit_received = true;
296 } else {
297 NOTREACHED() << "Must be inside Run to call Quit";
initial.commit3f4a7322008-07-27 06:49:38 +0900298 }
initial.commit3f4a7322008-07-27 06:49:38 +0900299}
300
darin@chromium.orgd70a12c2010-02-23 16:12:22 +0900301void MessageLoop::QuitNow() {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900302 DCHECK_EQ(this, current());
darin@chromium.orgd70a12c2010-02-23 16:12:22 +0900303 if (state_) {
304 pump_->Quit();
305 } else {
306 NOTREACHED() << "Must be inside Run to call Quit";
307 }
308}
309
darin@google.combe165ae2008-09-07 17:08:29 +0900310void MessageLoop::PostTask(
311 const tracked_objects::Location& from_here, Task* task) {
312 PostTask_Helper(from_here, task, 0, true);
313}
314
315void MessageLoop::PostDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900316 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
darin@google.combe165ae2008-09-07 17:08:29 +0900317 PostTask_Helper(from_here, task, delay_ms, true);
318}
319
320void MessageLoop::PostNonNestableTask(
321 const tracked_objects::Location& from_here, Task* task) {
322 PostTask_Helper(from_here, task, 0, false);
323}
324
325void MessageLoop::PostNonNestableDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900326 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
darin@google.combe165ae2008-09-07 17:08:29 +0900327 PostTask_Helper(from_here, task, delay_ms, false);
328}
329
initial.commit3f4a7322008-07-27 06:49:38 +0900330// Possibly called on a background thread!
darin@google.combe165ae2008-09-07 17:08:29 +0900331void MessageLoop::PostTask_Helper(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900332 const tracked_objects::Location& from_here, Task* task, int64 delay_ms,
darin@google.combe165ae2008-09-07 17:08:29 +0900333 bool nestable) {
initial.commit3f4a7322008-07-27 06:49:38 +0900334 task->SetBirthPlace(from_here);
darin@google.com0795f572008-08-30 09:22:48 +0900335
darin@google.combe165ae2008-09-07 17:08:29 +0900336 PendingTask pending_task(task, nestable);
darin@google.com0795f572008-08-30 09:22:48 +0900337
338 if (delay_ms > 0) {
darin@google.combe165ae2008-09-07 17:08:29 +0900339 pending_task.delayed_run_time =
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900340 TimeTicks::Now() + TimeDelta::FromMilliseconds(delay_ms);
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900341
342#if defined(OS_WIN)
343 if (high_resolution_timer_expiration_.is_null()) {
344 // Windows timers are granular to 15.6ms. If we only set high-res
345 // timers for those under 15.6ms, then a 18ms timer ticks at ~32ms,
346 // which as a percentage is pretty inaccurate. So enable high
347 // res timers for any timer which is within 2x of the granularity.
348 // This is a tradeoff between accuracy and power management.
349 bool needs_high_res_timers =
350 delay_ms < (2 * Time::kMinLowResolutionThresholdMs);
351 if (needs_high_res_timers) {
phajdan.jr@chromium.org3337f3d2010-10-20 19:50:38 +0900352 Time::ActivateHighResolutionTimer(true);
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900353 high_resolution_timer_expiration_ = TimeTicks::Now() +
phajdan.jr@chromium.org3337f3d2010-10-20 19:50:38 +0900354 TimeDelta::FromMilliseconds(kHighResolutionTimerModeLeaseTimeMs);
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900355 }
356 }
357#endif
darin@google.com0795f572008-08-30 09:22:48 +0900358 } else {
jar@chromium.orged5238a2009-12-28 15:59:52 +0900359 DCHECK_EQ(delay_ms, 0) << "delay should not be negative";
darin@google.com0795f572008-08-30 09:22:48 +0900360 }
361
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900362#if defined(OS_WIN)
363 if (!high_resolution_timer_expiration_.is_null()) {
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900364 if (TimeTicks::Now() > high_resolution_timer_expiration_) {
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900365 Time::ActivateHighResolutionTimer(false);
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900366 high_resolution_timer_expiration_ = TimeTicks();
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900367 }
368 }
369#endif
370
initial.commit3f4a7322008-07-27 06:49:38 +0900371 // Warning: Don't try to short-circuit, and handle this thread's tasks more
372 // directly, as it could starve handling of foreign threads. Put every task
373 // into this queue.
374
darin@google.com981f3552008-08-16 12:09:05 +0900375 scoped_refptr<base::MessagePump> pump;
initial.commit3f4a7322008-07-27 06:49:38 +0900376 {
darin@google.com981f3552008-08-16 12:09:05 +0900377 AutoLock locked(incoming_queue_lock_);
378
darin@google.combe165ae2008-09-07 17:08:29 +0900379 bool was_empty = incoming_queue_.empty();
380 incoming_queue_.push(pending_task);
initial.commit3f4a7322008-07-27 06:49:38 +0900381 if (!was_empty)
382 return; // Someone else should have started the sub-pump.
383
darin@google.com981f3552008-08-16 12:09:05 +0900384 pump = pump_;
darin@google.com6ddeb842008-08-15 16:31:20 +0900385 }
darin@google.com981f3552008-08-16 12:09:05 +0900386 // Since the incoming_queue_ may contain a task that destroys this message
387 // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
388 // We use a stack-based reference to the message pump so that we can call
389 // ScheduleWork outside of incoming_queue_lock_.
darin@google.com6ddeb842008-08-15 16:31:20 +0900390
darin@google.com981f3552008-08-16 12:09:05 +0900391 pump->ScheduleWork();
initial.commit3f4a7322008-07-27 06:49:38 +0900392}
393
394void MessageLoop::SetNestableTasksAllowed(bool allowed) {
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900395 if (nestable_tasks_allowed_ != allowed) {
396 nestable_tasks_allowed_ = allowed;
397 if (!nestable_tasks_allowed_)
398 return;
399 // Start the native pump if we are not already pumping.
darin@google.com981f3552008-08-16 12:09:05 +0900400 pump_->ScheduleWork();
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900401 }
initial.commit3f4a7322008-07-27 06:49:38 +0900402}
403
404bool MessageLoop::NestableTasksAllowed() const {
405 return nestable_tasks_allowed_;
406}
407
jcampan@chromium.orgeac57172009-07-02 04:53:59 +0900408bool MessageLoop::IsNested() {
409 return state_->run_depth > 1;
410}
411
initial.commit3f4a7322008-07-27 06:49:38 +0900412//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900413
initial.commit3f4a7322008-07-27 06:49:38 +0900414void MessageLoop::RunTask(Task* task) {
initial.commit3f4a7322008-07-27 06:49:38 +0900415 DCHECK(nestable_tasks_allowed_);
416 // Execute the task and assume the worst: It is probably not reentrant.
417 nestable_tasks_allowed_ = false;
darin@google.combe165ae2008-09-07 17:08:29 +0900418
419 HistogramEvent(kTaskRunEvent);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900420 FOR_EACH_OBSERVER(TaskObserver, task_observers_,
davemoore@chromium.orgeb5f68f2010-10-27 08:40:48 +0900421 WillProcessTask(task));
darin@google.combe165ae2008-09-07 17:08:29 +0900422 task->Run();
davemoore@chromium.orgeb5f68f2010-10-27 08:40:48 +0900423 FOR_EACH_OBSERVER(TaskObserver, task_observers_, DidProcessTask(task));
darin@google.combe165ae2008-09-07 17:08:29 +0900424 delete task;
425
426 nestable_tasks_allowed_ = true;
initial.commit3f4a7322008-07-27 06:49:38 +0900427}
428
darin@google.combe165ae2008-09-07 17:08:29 +0900429bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) {
430 if (pending_task.nestable || state_->run_depth == 1) {
431 RunTask(pending_task.task);
432 // Show that we ran a task (Note: a new one might arrive as a
433 // consequence!).
434 return true;
435 }
436
437 // We couldn't run the task now because we're in a nested message loop
438 // and the task isn't nestable.
439 deferred_non_nestable_work_queue_.push(pending_task);
440 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900441}
442
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900443void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
444 // Move to the delayed work queue. Initialize the sequence number
445 // before inserting into the delayed_work_queue_. The sequence number
446 // is used to faciliate FIFO sorting when two tasks have the same
447 // delayed_run_time value.
448 PendingTask new_pending_task(pending_task);
449 new_pending_task.sequence_num = next_sequence_num_++;
450 delayed_work_queue_.push(new_pending_task);
451}
452
initial.commit3f4a7322008-07-27 06:49:38 +0900453void MessageLoop::ReloadWorkQueue() {
454 // We can improve performance of our loading tasks from incoming_queue_ to
darin@google.com981f3552008-08-16 12:09:05 +0900455 // work_queue_ by waiting until the last minute (work_queue_ is empty) to
456 // load. That reduces the number of locks-per-task significantly when our
darin@google.combe165ae2008-09-07 17:08:29 +0900457 // queues get large.
458 if (!work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900459 return; // Wait till we *really* need to lock and load.
460
461 // Acquire all we can from the inter-thread queue with one lock acquisition.
initial.commit3f4a7322008-07-27 06:49:38 +0900462 {
463 AutoLock lock(incoming_queue_lock_);
darin@google.combe165ae2008-09-07 17:08:29 +0900464 if (incoming_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900465 return;
darin@chromium.orgb80ef1a2009-09-03 05:05:21 +0900466 incoming_queue_.Swap(&work_queue_); // Constant time
darin@google.combe165ae2008-09-07 17:08:29 +0900467 DCHECK(incoming_queue_.empty());
initial.commit3f4a7322008-07-27 06:49:38 +0900468 }
469}
470
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900471bool MessageLoop::DeletePendingTasks() {
472 bool did_work = !work_queue_.empty();
473 while (!work_queue_.empty()) {
474 PendingTask pending_task = work_queue_.front();
475 work_queue_.pop();
476 if (!pending_task.delayed_run_time.is_null()) {
477 // We want to delete delayed tasks in the same order in which they would
478 // normally be deleted in case of any funny dependencies between delayed
479 // tasks.
480 AddToDelayedWorkQueue(pending_task);
481 } else {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900482 // TODO(darin): Delete all tasks once it is safe to do so.
483 // Until it is totally safe, just do it when running Purify or
484 // Valgrind.
thestig@chromium.orgddb849c2010-10-28 05:03:42 +0900485#if defined(PURIFY) || defined(USE_HEAPCHECKER)
jar@chromium.org63772352009-03-12 05:06:02 +0900486 delete pending_task.task;
akalin@chromium.org839060b2010-08-03 12:06:21 +0900487#elif defined(OS_POSIX)
488 if (RUNNING_ON_VALGRIND)
489 delete pending_task.task;
490#endif // defined(OS_POSIX)
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900491 }
initial.commit3f4a7322008-07-27 06:49:38 +0900492 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900493 did_work |= !deferred_non_nestable_work_queue_.empty();
494 while (!deferred_non_nestable_work_queue_.empty()) {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900495 // TODO(darin): Delete all tasks once it is safe to do so.
496 // Until it is totaly safe, only delete them under Purify and Valgrind.
497 Task* task = NULL;
thestig@chromium.orgddb849c2010-10-28 05:03:42 +0900498#if defined(PURIFY) || defined(USE_HEAPCHECKER)
akalin@chromium.org839060b2010-08-03 12:06:21 +0900499 task = deferred_non_nestable_work_queue_.front().task;
500#elif defined(OS_POSIX)
501 if (RUNNING_ON_VALGRIND)
502 task = deferred_non_nestable_work_queue_.front().task;
503#endif
jar@chromium.org2fa6b4b2009-03-12 04:53:50 +0900504 deferred_non_nestable_work_queue_.pop();
akalin@chromium.org839060b2010-08-03 12:06:21 +0900505 if (task)
506 delete task;
initial.commit3f4a7322008-07-27 06:49:38 +0900507 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900508 did_work |= !delayed_work_queue_.empty();
509 while (!delayed_work_queue_.empty()) {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900510 Task* task = delayed_work_queue_.top().task;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900511 delayed_work_queue_.pop();
akalin@chromium.org839060b2010-08-03 12:06:21 +0900512 delete task;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900513 }
514 return did_work;
initial.commit3f4a7322008-07-27 06:49:38 +0900515}
516
darin@google.com981f3552008-08-16 12:09:05 +0900517bool MessageLoop::DoWork() {
darin@google.combe165ae2008-09-07 17:08:29 +0900518 if (!nestable_tasks_allowed_) {
519 // Task can't be executed right now.
520 return false;
521 }
522
523 for (;;) {
524 ReloadWorkQueue();
525 if (work_queue_.empty())
526 break;
527
528 // Execute oldest task.
529 do {
530 PendingTask pending_task = work_queue_.front();
531 work_queue_.pop();
532 if (!pending_task.delayed_run_time.is_null()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900533 AddToDelayedWorkQueue(pending_task);
darin@chromium.orgb2d33452008-09-24 04:19:20 +0900534 // If we changed the topmost task, then it is time to re-schedule.
jar@chromium.org40355072010-10-21 15:32:33 +0900535 if (delayed_work_queue_.top().task == pending_task.task)
darin@google.combe165ae2008-09-07 17:08:29 +0900536 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
537 } else {
538 if (DeferOrRunPendingTask(pending_task))
539 return true;
540 }
541 } while (!work_queue_.empty());
542 }
543
544 // Nothing happened.
545 return false;
darin@google.com981f3552008-08-16 12:09:05 +0900546}
547
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900548bool MessageLoop::DoDelayedWork(base::TimeTicks* next_delayed_work_time) {
jar@chromium.org40355072010-10-21 15:32:33 +0900549 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900550 recent_time_ = *next_delayed_work_time = TimeTicks();
darin@google.combe165ae2008-09-07 17:08:29 +0900551 return false;
552 }
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900553
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900554 // When we "fall behind," there will be a lot of tasks in the delayed work
jar@chromium.org94f73832010-11-05 08:23:42 +0900555 // queue that are ready to run. To increase efficiency when we fall behind,
556 // we will only call Time::Now() intermittently, and then process all tasks
557 // that are ready to run before calling it again. As a result, the more we
558 // fall behind (and have a lot of ready-to-run delayed tasks), the more
559 // efficient we'll be at handling the tasks.
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900560
561 TimeTicks next_run_time = delayed_work_queue_.top().delayed_run_time;
jar@chromium.org94f73832010-11-05 08:23:42 +0900562 if (next_run_time > recent_time_) {
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900563 recent_time_ = TimeTicks::Now(); // Get a better view of Now();
jar@chromium.org94f73832010-11-05 08:23:42 +0900564 if (next_run_time > recent_time_) {
565 *next_delayed_work_time = next_run_time;
566 return false;
567 }
darin@google.combe165ae2008-09-07 17:08:29 +0900568 }
darin@google.com981f3552008-08-16 12:09:05 +0900569
jar@chromium.org40355072010-10-21 15:32:33 +0900570 PendingTask pending_task = delayed_work_queue_.top();
571 delayed_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900572
jar@chromium.org40355072010-10-21 15:32:33 +0900573 if (!delayed_work_queue_.empty())
darin@google.combe165ae2008-09-07 17:08:29 +0900574 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
darin@google.com981f3552008-08-16 12:09:05 +0900575
darin@google.combe165ae2008-09-07 17:08:29 +0900576 return DeferOrRunPendingTask(pending_task);
darin@google.com981f3552008-08-16 12:09:05 +0900577}
578
579bool MessageLoop::DoIdleWork() {
580 if (ProcessNextDelayedNonNestableTask())
581 return true;
582
583 if (state_->quit_received)
584 pump_->Quit();
585
586 return false;
587}
588
589//------------------------------------------------------------------------------
590// MessageLoop::AutoRunState
591
592MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
593 // Make the loop reference us.
594 previous_state_ = loop_->state_;
595 if (previous_state_) {
596 run_depth = previous_state_->run_depth + 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900597 } else {
darin@google.com981f3552008-08-16 12:09:05 +0900598 run_depth = 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900599 }
darin@google.com981f3552008-08-16 12:09:05 +0900600 loop_->state_ = this;
601
602 // Initialize the other fields:
603 quit_received = false;
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900604#if !defined(OS_MACOSX)
darin@google.com981f3552008-08-16 12:09:05 +0900605 dispatcher = NULL;
606#endif
607}
608
609MessageLoop::AutoRunState::~AutoRunState() {
610 loop_->state_ = previous_state_;
darin@google.comee6fa722008-08-13 08:25:43 +0900611}
612
initial.commit3f4a7322008-07-27 06:49:38 +0900613//------------------------------------------------------------------------------
darin@google.combe165ae2008-09-07 17:08:29 +0900614// MessageLoop::PendingTask
initial.commit3f4a7322008-07-27 06:49:38 +0900615
darin@google.combe165ae2008-09-07 17:08:29 +0900616bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
617 // Since the top of a priority queue is defined as the "greatest" element, we
618 // need to invert the comparison here. We want the smaller time to be at the
619 // top of the heap.
initial.commit3f4a7322008-07-27 06:49:38 +0900620
darin@google.combe165ae2008-09-07 17:08:29 +0900621 if (delayed_run_time < other.delayed_run_time)
622 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900623
darin@google.combe165ae2008-09-07 17:08:29 +0900624 if (delayed_run_time > other.delayed_run_time)
625 return true;
initial.commit3f4a7322008-07-27 06:49:38 +0900626
darin@google.combe165ae2008-09-07 17:08:29 +0900627 // If the times happen to match, then we use the sequence number to decide.
628 // Compare the difference to support integer roll-over.
629 return (sequence_num - other.sequence_num) > 0;
initial.commit3f4a7322008-07-27 06:49:38 +0900630}
631
632//------------------------------------------------------------------------------
633// Method and data for histogramming events and actions taken by each instance
634// on each thread.
635
636// static
initial.commit3f4a7322008-07-27 06:49:38 +0900637void MessageLoop::EnableHistogrammer(bool enable) {
638 enable_histogrammer_ = enable;
639}
640
641void MessageLoop::StartHistogrammer() {
642 if (enable_histogrammer_ && !message_histogram_.get()
brettw@chromium.org275c2ec2010-10-14 13:38:38 +0900643 && base::StatisticsRecorder::WasStarted()) {
darin@google.com981f3552008-08-16 12:09:05 +0900644 DCHECK(!thread_name_.empty());
brettw@chromium.org275c2ec2010-10-14 13:38:38 +0900645 message_histogram_ = base::LinearHistogram::FactoryGet(
646 "MsgLoop:" + thread_name_,
jar@chromium.orged5238a2009-12-28 15:59:52 +0900647 kLeastNonZeroMessageId, kMaxMessageId,
648 kNumberOfDistinctMessagesDisplayed,
649 message_histogram_->kHexRangePrintingFlag);
initial.commit3f4a7322008-07-27 06:49:38 +0900650 message_histogram_->SetRangeDescriptions(event_descriptions_);
651 }
652}
653
654void MessageLoop::HistogramEvent(int event) {
655 if (message_histogram_.get())
656 message_histogram_->Add(event);
657}
658
darin@google.comd936b5b2008-08-26 14:53:57 +0900659//------------------------------------------------------------------------------
660// MessageLoopForUI
661
662#if defined(OS_WIN)
darin@google.comd936b5b2008-08-26 14:53:57 +0900663void MessageLoopForUI::DidProcessMessage(const MSG& message) {
664 pump_win()->DidProcessMessage(message);
665}
darin@google.comd936b5b2008-08-26 14:53:57 +0900666#endif // defined(OS_WIN)
667
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900668#if !defined(OS_MACOSX) && !defined(OS_NACL)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900669void MessageLoopForUI::AddObserver(Observer* observer) {
670 pump_ui()->AddObserver(observer);
671}
672
673void MessageLoopForUI::RemoveObserver(Observer* observer) {
674 pump_ui()->RemoveObserver(observer);
675}
676
677void MessageLoopForUI::Run(Dispatcher* dispatcher) {
678 AutoRunState save_state(this);
679 state_->dispatcher = dispatcher;
680 RunHandler();
681}
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900682#endif // !defined(OS_MACOSX) && !defined(OS_NACL)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900683
darin@google.comd936b5b2008-08-26 14:53:57 +0900684//------------------------------------------------------------------------------
685// MessageLoopForIO
686
687#if defined(OS_WIN)
688
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900689void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
690 pump_io()->RegisterIOHandler(file, handler);
691}
692
rvargas@google.com73887542008-11-08 06:52:15 +0900693bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
694 return pump_io()->WaitForIOCompletion(timeout, filter);
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900695}
696
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900697#elif defined(OS_POSIX) && !defined(OS_NACL)
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900698
jeremy@chromium.orgefc0db02008-12-16 07:02:17 +0900699bool MessageLoopForIO::WatchFileDescriptor(int fd,
700 bool persistent,
701 Mode mode,
702 FileDescriptorWatcher *controller,
703 Watcher *delegate) {
704 return pump_libevent()->WatchFileDescriptor(
705 fd,
706 persistent,
707 static_cast<base::MessagePumpLibevent::Mode>(mode),
708 controller,
709 delegate);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900710}
711
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900712#endif