blob: 58aaa01c0b5ef1a0930c8cb2cab3998158d1f084 [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()
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900145#elif defined(OS_NACL)
146// Currently NaCl doesn't have a UI or an IO MessageLoop.
147// TODO(abarth): Figure out if we need these.
148#define MESSAGE_PUMP_UI NULL
149#define MESSAGE_PUMP_IO NULL
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900150#elif defined(OS_POSIX) // POSIX but not MACOSX.
151#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
152#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900153#else
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900154#error Not implemented
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900155#endif
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900156
157 if (type_ == TYPE_UI) {
158 pump_ = MESSAGE_PUMP_UI;
dsh@google.com119a2522008-10-04 01:52:59 +0900159 } else if (type_ == TYPE_IO) {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900160 pump_ = MESSAGE_PUMP_IO;
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900161 } else {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900162 DCHECK_EQ(TYPE_DEFAULT, type_);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900163 pump_ = new base::MessagePumpDefault();
164 }
initial.commit3f4a7322008-07-27 06:49:38 +0900165}
166
167MessageLoop::~MessageLoop() {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900168 DCHECK_EQ(this, current());
darin@google.com965e5342008-08-06 08:16:41 +0900169
darin@google.com0e500502008-09-09 14:55:35 +0900170 DCHECK(!state_);
171
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900172 // Clean up any unprocessed tasks, but take care: deleting a task could
173 // result in the addition of more tasks (e.g., via DeleteSoon). We set a
174 // limit on the number of times we will allow a deleted task to generate more
175 // tasks. Normally, we should only pass through this loop once or twice. If
176 // we end up hitting the loop limit, then it is probably due to one task that
177 // is being stubborn. Inspect the queues to see who is left.
178 bool did_work;
179 for (int i = 0; i < 100; ++i) {
180 DeletePendingTasks();
181 ReloadWorkQueue();
182 // If we end up with empty queues, then break out of the loop.
183 did_work = DeletePendingTasks();
184 if (!did_work)
185 break;
darin@google.com0e500502008-09-09 14:55:35 +0900186 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900187 DCHECK(!did_work);
188
sanjeevr@chromium.org03b44d52010-11-30 09:25:29 +0900189 // Let interested parties have one last shot at accessing this.
190 FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
191 WillDestroyCurrentMessageLoop());
192
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900193 // OK, now make it so that no one can find us.
deanm@chromium.orge4cc5922008-09-10 20:14:56 +0900194 lazy_tls_ptr.Pointer()->Set(NULL);
initial.commit3f4a7322008-07-27 06:49:38 +0900195}
196
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900197void MessageLoop::AddDestructionObserver(
198 DestructionObserver* destruction_observer) {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900199 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900200 destruction_observers_.AddObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900201}
202
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900203void MessageLoop::RemoveDestructionObserver(
204 DestructionObserver* destruction_observer) {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900205 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900206 destruction_observers_.RemoveObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900207}
208
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900209void MessageLoop::AddTaskObserver(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_.AddObserver(task_observer);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900212}
213
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900214void MessageLoop::RemoveTaskObserver(TaskObserver* task_observer) {
willchan@chromium.orga9047632010-06-10 06:20:41 +0900215 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900216 task_observers_.RemoveObserver(task_observer);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900217}
218
darin@google.com6ddeb842008-08-15 16:31:20 +0900219void MessageLoop::Run() {
darin@google.com981f3552008-08-16 12:09:05 +0900220 AutoRunState save_state(this);
221 RunHandler();
darin@google.com6ddeb842008-08-15 16:31:20 +0900222}
223
jar@google.com9239e022008-07-31 22:10:20 +0900224void MessageLoop::RunAllPending() {
darin@google.com981f3552008-08-16 12:09:05 +0900225 AutoRunState save_state(this);
226 state_->quit_received = true; // Means run until we would otherwise block.
227 RunHandler();
initial.commit3f4a7322008-07-27 06:49:38 +0900228}
229
230// Runs the loop in two different SEH modes:
231// enable_SEH_restoration_ = false : any unhandled exception goes to the last
232// one that calls SetUnhandledExceptionFilter().
233// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
234// that was existed before the loop was run.
darin@google.com981f3552008-08-16 12:09:05 +0900235void MessageLoop::RunHandler() {
236#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +0900237 if (exception_restoration_) {
stoyan@google.com283facb2009-10-27 03:15:59 +0900238 RunInternalInSEHFrame();
darin@google.com981f3552008-08-16 12:09:05 +0900239 return;
initial.commit3f4a7322008-07-27 06:49:38 +0900240 }
darin@google.com981f3552008-08-16 12:09:05 +0900241#endif
242
243 RunInternal();
initial.commit3f4a7322008-07-27 06:49:38 +0900244}
stoyan@google.com283facb2009-10-27 03:15:59 +0900245//------------------------------------------------------------------------------
246#if defined(OS_WIN)
247__declspec(noinline) void MessageLoop::RunInternalInSEHFrame() {
248 LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
249 __try {
250 RunInternal();
251 } __except(SEHFilter(current_filter)) {
252 }
253 return;
254}
255#endif
initial.commit3f4a7322008-07-27 06:49:38 +0900256//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900257
darin@google.com981f3552008-08-16 12:09:05 +0900258void MessageLoop::RunInternal() {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900259 DCHECK_EQ(this, current());
darin@google.com981f3552008-08-16 12:09:05 +0900260
initial.commit3f4a7322008-07-27 06:49:38 +0900261 StartHistogrammer();
262
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900263#if !defined(OS_MACOSX)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900264 if (state_->dispatcher && type() == TYPE_UI) {
265 static_cast<base::MessagePumpForUI*>(pump_.get())->
266 RunWithDispatcher(this, state_->dispatcher);
darin@google.com981f3552008-08-16 12:09:05 +0900267 return;
jar@google.com9239e022008-07-31 22:10:20 +0900268 }
darin@google.com981f3552008-08-16 12:09:05 +0900269#endif
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900270
darin@google.com981f3552008-08-16 12:09:05 +0900271 pump_->Run(this);
jar@google.comfbaaf692008-07-30 16:50:53 +0900272}
jar@google.com7ff36e62008-07-30 15:58:56 +0900273
jar@google.comb4d1bff2008-07-31 04:03:59 +0900274//------------------------------------------------------------------------------
275// Wrapper functions for use in above message loop framework.
276
initial.commit3f4a7322008-07-27 06:49:38 +0900277bool MessageLoop::ProcessNextDelayedNonNestableTask() {
darin@google.com981f3552008-08-16 12:09:05 +0900278 if (state_->run_depth != 1)
initial.commit3f4a7322008-07-27 06:49:38 +0900279 return false;
280
darin@google.combe165ae2008-09-07 17:08:29 +0900281 if (deferred_non_nestable_work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900282 return false;
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900283
darin@google.combe165ae2008-09-07 17:08:29 +0900284 Task* task = deferred_non_nestable_work_queue_.front().task;
285 deferred_non_nestable_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900286
darin@google.combe165ae2008-09-07 17:08:29 +0900287 RunTask(task);
initial.commit3f4a7322008-07-27 06:49:38 +0900288 return true;
289}
290
initial.commit3f4a7322008-07-27 06:49:38 +0900291//------------------------------------------------------------------------------
292
293void MessageLoop::Quit() {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900294 DCHECK_EQ(this, current());
darin@google.com981f3552008-08-16 12:09:05 +0900295 if (state_) {
296 state_->quit_received = true;
297 } else {
298 NOTREACHED() << "Must be inside Run to call Quit";
initial.commit3f4a7322008-07-27 06:49:38 +0900299 }
initial.commit3f4a7322008-07-27 06:49:38 +0900300}
301
darin@chromium.orgd70a12c2010-02-23 16:12:22 +0900302void MessageLoop::QuitNow() {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900303 DCHECK_EQ(this, current());
darin@chromium.orgd70a12c2010-02-23 16:12:22 +0900304 if (state_) {
305 pump_->Quit();
306 } else {
307 NOTREACHED() << "Must be inside Run to call Quit";
308 }
309}
310
darin@google.combe165ae2008-09-07 17:08:29 +0900311void MessageLoop::PostTask(
312 const tracked_objects::Location& from_here, Task* task) {
313 PostTask_Helper(from_here, task, 0, true);
314}
315
316void MessageLoop::PostDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900317 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
darin@google.combe165ae2008-09-07 17:08:29 +0900318 PostTask_Helper(from_here, task, delay_ms, true);
319}
320
321void MessageLoop::PostNonNestableTask(
322 const tracked_objects::Location& from_here, Task* task) {
323 PostTask_Helper(from_here, task, 0, false);
324}
325
326void MessageLoop::PostNonNestableDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900327 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
darin@google.combe165ae2008-09-07 17:08:29 +0900328 PostTask_Helper(from_here, task, delay_ms, false);
329}
330
initial.commit3f4a7322008-07-27 06:49:38 +0900331// Possibly called on a background thread!
darin@google.combe165ae2008-09-07 17:08:29 +0900332void MessageLoop::PostTask_Helper(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900333 const tracked_objects::Location& from_here, Task* task, int64 delay_ms,
darin@google.combe165ae2008-09-07 17:08:29 +0900334 bool nestable) {
initial.commit3f4a7322008-07-27 06:49:38 +0900335 task->SetBirthPlace(from_here);
darin@google.com0795f572008-08-30 09:22:48 +0900336
darin@google.combe165ae2008-09-07 17:08:29 +0900337 PendingTask pending_task(task, nestable);
darin@google.com0795f572008-08-30 09:22:48 +0900338
339 if (delay_ms > 0) {
darin@google.combe165ae2008-09-07 17:08:29 +0900340 pending_task.delayed_run_time =
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900341 TimeTicks::Now() + TimeDelta::FromMilliseconds(delay_ms);
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900342
343#if defined(OS_WIN)
344 if (high_resolution_timer_expiration_.is_null()) {
345 // Windows timers are granular to 15.6ms. If we only set high-res
346 // timers for those under 15.6ms, then a 18ms timer ticks at ~32ms,
347 // which as a percentage is pretty inaccurate. So enable high
348 // res timers for any timer which is within 2x of the granularity.
349 // This is a tradeoff between accuracy and power management.
350 bool needs_high_res_timers =
351 delay_ms < (2 * Time::kMinLowResolutionThresholdMs);
352 if (needs_high_res_timers) {
phajdan.jr@chromium.org3337f3d2010-10-20 19:50:38 +0900353 Time::ActivateHighResolutionTimer(true);
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900354 high_resolution_timer_expiration_ = TimeTicks::Now() +
phajdan.jr@chromium.org3337f3d2010-10-20 19:50:38 +0900355 TimeDelta::FromMilliseconds(kHighResolutionTimerModeLeaseTimeMs);
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900356 }
357 }
358#endif
darin@google.com0795f572008-08-30 09:22:48 +0900359 } else {
jar@chromium.orged5238a2009-12-28 15:59:52 +0900360 DCHECK_EQ(delay_ms, 0) << "delay should not be negative";
darin@google.com0795f572008-08-30 09:22:48 +0900361 }
362
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900363#if defined(OS_WIN)
364 if (!high_resolution_timer_expiration_.is_null()) {
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900365 if (TimeTicks::Now() > high_resolution_timer_expiration_) {
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900366 Time::ActivateHighResolutionTimer(false);
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900367 high_resolution_timer_expiration_ = TimeTicks();
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900368 }
369 }
370#endif
371
initial.commit3f4a7322008-07-27 06:49:38 +0900372 // Warning: Don't try to short-circuit, and handle this thread's tasks more
373 // directly, as it could starve handling of foreign threads. Put every task
374 // into this queue.
375
darin@google.com981f3552008-08-16 12:09:05 +0900376 scoped_refptr<base::MessagePump> pump;
initial.commit3f4a7322008-07-27 06:49:38 +0900377 {
darin@google.com981f3552008-08-16 12:09:05 +0900378 AutoLock locked(incoming_queue_lock_);
379
darin@google.combe165ae2008-09-07 17:08:29 +0900380 bool was_empty = incoming_queue_.empty();
381 incoming_queue_.push(pending_task);
initial.commit3f4a7322008-07-27 06:49:38 +0900382 if (!was_empty)
383 return; // Someone else should have started the sub-pump.
384
darin@google.com981f3552008-08-16 12:09:05 +0900385 pump = pump_;
darin@google.com6ddeb842008-08-15 16:31:20 +0900386 }
darin@google.com981f3552008-08-16 12:09:05 +0900387 // Since the incoming_queue_ may contain a task that destroys this message
388 // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
389 // We use a stack-based reference to the message pump so that we can call
390 // ScheduleWork outside of incoming_queue_lock_.
darin@google.com6ddeb842008-08-15 16:31:20 +0900391
darin@google.com981f3552008-08-16 12:09:05 +0900392 pump->ScheduleWork();
initial.commit3f4a7322008-07-27 06:49:38 +0900393}
394
395void MessageLoop::SetNestableTasksAllowed(bool allowed) {
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900396 if (nestable_tasks_allowed_ != allowed) {
397 nestable_tasks_allowed_ = allowed;
398 if (!nestable_tasks_allowed_)
399 return;
400 // Start the native pump if we are not already pumping.
darin@google.com981f3552008-08-16 12:09:05 +0900401 pump_->ScheduleWork();
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900402 }
initial.commit3f4a7322008-07-27 06:49:38 +0900403}
404
405bool MessageLoop::NestableTasksAllowed() const {
406 return nestable_tasks_allowed_;
407}
408
jcampan@chromium.orgeac57172009-07-02 04:53:59 +0900409bool MessageLoop::IsNested() {
410 return state_->run_depth > 1;
411}
412
initial.commit3f4a7322008-07-27 06:49:38 +0900413//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900414
initial.commit3f4a7322008-07-27 06:49:38 +0900415void MessageLoop::RunTask(Task* task) {
initial.commit3f4a7322008-07-27 06:49:38 +0900416 DCHECK(nestable_tasks_allowed_);
417 // Execute the task and assume the worst: It is probably not reentrant.
418 nestable_tasks_allowed_ = false;
darin@google.combe165ae2008-09-07 17:08:29 +0900419
420 HistogramEvent(kTaskRunEvent);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900421 FOR_EACH_OBSERVER(TaskObserver, task_observers_,
davemoore@chromium.orgeb5f68f2010-10-27 08:40:48 +0900422 WillProcessTask(task));
darin@google.combe165ae2008-09-07 17:08:29 +0900423 task->Run();
davemoore@chromium.orgeb5f68f2010-10-27 08:40:48 +0900424 FOR_EACH_OBSERVER(TaskObserver, task_observers_, DidProcessTask(task));
darin@google.combe165ae2008-09-07 17:08:29 +0900425 delete task;
426
427 nestable_tasks_allowed_ = true;
initial.commit3f4a7322008-07-27 06:49:38 +0900428}
429
darin@google.combe165ae2008-09-07 17:08:29 +0900430bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) {
431 if (pending_task.nestable || state_->run_depth == 1) {
432 RunTask(pending_task.task);
433 // Show that we ran a task (Note: a new one might arrive as a
434 // consequence!).
435 return true;
436 }
437
438 // We couldn't run the task now because we're in a nested message loop
439 // and the task isn't nestable.
440 deferred_non_nestable_work_queue_.push(pending_task);
441 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900442}
443
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900444void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
445 // Move to the delayed work queue. Initialize the sequence number
446 // before inserting into the delayed_work_queue_. The sequence number
447 // is used to faciliate FIFO sorting when two tasks have the same
448 // delayed_run_time value.
449 PendingTask new_pending_task(pending_task);
450 new_pending_task.sequence_num = next_sequence_num_++;
451 delayed_work_queue_.push(new_pending_task);
452}
453
initial.commit3f4a7322008-07-27 06:49:38 +0900454void MessageLoop::ReloadWorkQueue() {
455 // We can improve performance of our loading tasks from incoming_queue_ to
darin@google.com981f3552008-08-16 12:09:05 +0900456 // work_queue_ by waiting until the last minute (work_queue_ is empty) to
457 // load. That reduces the number of locks-per-task significantly when our
darin@google.combe165ae2008-09-07 17:08:29 +0900458 // queues get large.
459 if (!work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900460 return; // Wait till we *really* need to lock and load.
461
462 // Acquire all we can from the inter-thread queue with one lock acquisition.
initial.commit3f4a7322008-07-27 06:49:38 +0900463 {
464 AutoLock lock(incoming_queue_lock_);
darin@google.combe165ae2008-09-07 17:08:29 +0900465 if (incoming_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900466 return;
darin@chromium.orgb80ef1a2009-09-03 05:05:21 +0900467 incoming_queue_.Swap(&work_queue_); // Constant time
darin@google.combe165ae2008-09-07 17:08:29 +0900468 DCHECK(incoming_queue_.empty());
initial.commit3f4a7322008-07-27 06:49:38 +0900469 }
470}
471
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900472bool MessageLoop::DeletePendingTasks() {
473 bool did_work = !work_queue_.empty();
474 while (!work_queue_.empty()) {
475 PendingTask pending_task = work_queue_.front();
476 work_queue_.pop();
477 if (!pending_task.delayed_run_time.is_null()) {
478 // We want to delete delayed tasks in the same order in which they would
479 // normally be deleted in case of any funny dependencies between delayed
480 // tasks.
481 AddToDelayedWorkQueue(pending_task);
482 } else {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900483 // TODO(darin): Delete all tasks once it is safe to do so.
484 // Until it is totally safe, just do it when running Purify or
485 // Valgrind.
thestig@chromium.orgddb849c2010-10-28 05:03:42 +0900486#if defined(PURIFY) || defined(USE_HEAPCHECKER)
jar@chromium.org63772352009-03-12 05:06:02 +0900487 delete pending_task.task;
akalin@chromium.org839060b2010-08-03 12:06:21 +0900488#elif defined(OS_POSIX)
489 if (RUNNING_ON_VALGRIND)
490 delete pending_task.task;
491#endif // defined(OS_POSIX)
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900492 }
initial.commit3f4a7322008-07-27 06:49:38 +0900493 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900494 did_work |= !deferred_non_nestable_work_queue_.empty();
495 while (!deferred_non_nestable_work_queue_.empty()) {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900496 // TODO(darin): Delete all tasks once it is safe to do so.
497 // Until it is totaly safe, only delete them under Purify and Valgrind.
498 Task* task = NULL;
thestig@chromium.orgddb849c2010-10-28 05:03:42 +0900499#if defined(PURIFY) || defined(USE_HEAPCHECKER)
akalin@chromium.org839060b2010-08-03 12:06:21 +0900500 task = deferred_non_nestable_work_queue_.front().task;
501#elif defined(OS_POSIX)
502 if (RUNNING_ON_VALGRIND)
503 task = deferred_non_nestable_work_queue_.front().task;
504#endif
jar@chromium.org2fa6b4b2009-03-12 04:53:50 +0900505 deferred_non_nestable_work_queue_.pop();
akalin@chromium.org839060b2010-08-03 12:06:21 +0900506 if (task)
507 delete task;
initial.commit3f4a7322008-07-27 06:49:38 +0900508 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900509 did_work |= !delayed_work_queue_.empty();
510 while (!delayed_work_queue_.empty()) {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900511 Task* task = delayed_work_queue_.top().task;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900512 delayed_work_queue_.pop();
akalin@chromium.org839060b2010-08-03 12:06:21 +0900513 delete task;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900514 }
515 return did_work;
initial.commit3f4a7322008-07-27 06:49:38 +0900516}
517
darin@google.com981f3552008-08-16 12:09:05 +0900518bool MessageLoop::DoWork() {
darin@google.combe165ae2008-09-07 17:08:29 +0900519 if (!nestable_tasks_allowed_) {
520 // Task can't be executed right now.
521 return false;
522 }
523
524 for (;;) {
525 ReloadWorkQueue();
526 if (work_queue_.empty())
527 break;
528
529 // Execute oldest task.
530 do {
531 PendingTask pending_task = work_queue_.front();
532 work_queue_.pop();
533 if (!pending_task.delayed_run_time.is_null()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900534 AddToDelayedWorkQueue(pending_task);
darin@chromium.orgb2d33452008-09-24 04:19:20 +0900535 // If we changed the topmost task, then it is time to re-schedule.
jar@chromium.org40355072010-10-21 15:32:33 +0900536 if (delayed_work_queue_.top().task == pending_task.task)
darin@google.combe165ae2008-09-07 17:08:29 +0900537 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
538 } else {
539 if (DeferOrRunPendingTask(pending_task))
540 return true;
541 }
542 } while (!work_queue_.empty());
543 }
544
545 // Nothing happened.
546 return false;
darin@google.com981f3552008-08-16 12:09:05 +0900547}
548
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900549bool MessageLoop::DoDelayedWork(base::TimeTicks* next_delayed_work_time) {
jar@chromium.org40355072010-10-21 15:32:33 +0900550 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900551 recent_time_ = *next_delayed_work_time = TimeTicks();
darin@google.combe165ae2008-09-07 17:08:29 +0900552 return false;
553 }
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900554
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900555 // When we "fall behind," there will be a lot of tasks in the delayed work
jar@chromium.org94f73832010-11-05 08:23:42 +0900556 // queue that are ready to run. To increase efficiency when we fall behind,
557 // we will only call Time::Now() intermittently, and then process all tasks
558 // that are ready to run before calling it again. As a result, the more we
559 // fall behind (and have a lot of ready-to-run delayed tasks), the more
560 // efficient we'll be at handling the tasks.
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900561
562 TimeTicks next_run_time = delayed_work_queue_.top().delayed_run_time;
jar@chromium.org94f73832010-11-05 08:23:42 +0900563 if (next_run_time > recent_time_) {
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900564 recent_time_ = TimeTicks::Now(); // Get a better view of Now();
jar@chromium.org94f73832010-11-05 08:23:42 +0900565 if (next_run_time > recent_time_) {
566 *next_delayed_work_time = next_run_time;
567 return false;
568 }
darin@google.combe165ae2008-09-07 17:08:29 +0900569 }
darin@google.com981f3552008-08-16 12:09:05 +0900570
jar@chromium.org40355072010-10-21 15:32:33 +0900571 PendingTask pending_task = delayed_work_queue_.top();
572 delayed_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900573
jar@chromium.org40355072010-10-21 15:32:33 +0900574 if (!delayed_work_queue_.empty())
darin@google.combe165ae2008-09-07 17:08:29 +0900575 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
darin@google.com981f3552008-08-16 12:09:05 +0900576
darin@google.combe165ae2008-09-07 17:08:29 +0900577 return DeferOrRunPendingTask(pending_task);
darin@google.com981f3552008-08-16 12:09:05 +0900578}
579
580bool MessageLoop::DoIdleWork() {
581 if (ProcessNextDelayedNonNestableTask())
582 return true;
583
584 if (state_->quit_received)
585 pump_->Quit();
586
587 return false;
588}
589
590//------------------------------------------------------------------------------
591// MessageLoop::AutoRunState
592
593MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
594 // Make the loop reference us.
595 previous_state_ = loop_->state_;
596 if (previous_state_) {
597 run_depth = previous_state_->run_depth + 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900598 } else {
darin@google.com981f3552008-08-16 12:09:05 +0900599 run_depth = 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900600 }
darin@google.com981f3552008-08-16 12:09:05 +0900601 loop_->state_ = this;
602
603 // Initialize the other fields:
604 quit_received = false;
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900605#if !defined(OS_MACOSX)
darin@google.com981f3552008-08-16 12:09:05 +0900606 dispatcher = NULL;
607#endif
608}
609
610MessageLoop::AutoRunState::~AutoRunState() {
611 loop_->state_ = previous_state_;
darin@google.comee6fa722008-08-13 08:25:43 +0900612}
613
initial.commit3f4a7322008-07-27 06:49:38 +0900614//------------------------------------------------------------------------------
darin@google.combe165ae2008-09-07 17:08:29 +0900615// MessageLoop::PendingTask
initial.commit3f4a7322008-07-27 06:49:38 +0900616
darin@google.combe165ae2008-09-07 17:08:29 +0900617bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
618 // Since the top of a priority queue is defined as the "greatest" element, we
619 // need to invert the comparison here. We want the smaller time to be at the
620 // top of the heap.
initial.commit3f4a7322008-07-27 06:49:38 +0900621
darin@google.combe165ae2008-09-07 17:08:29 +0900622 if (delayed_run_time < other.delayed_run_time)
623 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900624
darin@google.combe165ae2008-09-07 17:08:29 +0900625 if (delayed_run_time > other.delayed_run_time)
626 return true;
initial.commit3f4a7322008-07-27 06:49:38 +0900627
darin@google.combe165ae2008-09-07 17:08:29 +0900628 // If the times happen to match, then we use the sequence number to decide.
629 // Compare the difference to support integer roll-over.
630 return (sequence_num - other.sequence_num) > 0;
initial.commit3f4a7322008-07-27 06:49:38 +0900631}
632
633//------------------------------------------------------------------------------
634// Method and data for histogramming events and actions taken by each instance
635// on each thread.
636
637// static
initial.commit3f4a7322008-07-27 06:49:38 +0900638void MessageLoop::EnableHistogrammer(bool enable) {
639 enable_histogrammer_ = enable;
640}
641
642void MessageLoop::StartHistogrammer() {
643 if (enable_histogrammer_ && !message_histogram_.get()
brettw@chromium.org275c2ec2010-10-14 13:38:38 +0900644 && base::StatisticsRecorder::WasStarted()) {
darin@google.com981f3552008-08-16 12:09:05 +0900645 DCHECK(!thread_name_.empty());
brettw@chromium.org275c2ec2010-10-14 13:38:38 +0900646 message_histogram_ = base::LinearHistogram::FactoryGet(
647 "MsgLoop:" + thread_name_,
jar@chromium.orged5238a2009-12-28 15:59:52 +0900648 kLeastNonZeroMessageId, kMaxMessageId,
649 kNumberOfDistinctMessagesDisplayed,
650 message_histogram_->kHexRangePrintingFlag);
initial.commit3f4a7322008-07-27 06:49:38 +0900651 message_histogram_->SetRangeDescriptions(event_descriptions_);
652 }
653}
654
655void MessageLoop::HistogramEvent(int event) {
656 if (message_histogram_.get())
657 message_histogram_->Add(event);
658}
659
darin@google.comd936b5b2008-08-26 14:53:57 +0900660//------------------------------------------------------------------------------
661// MessageLoopForUI
662
663#if defined(OS_WIN)
darin@google.comd936b5b2008-08-26 14:53:57 +0900664void MessageLoopForUI::DidProcessMessage(const MSG& message) {
665 pump_win()->DidProcessMessage(message);
666}
darin@google.comd936b5b2008-08-26 14:53:57 +0900667#endif // defined(OS_WIN)
668
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900669#if !defined(OS_MACOSX) && !defined(OS_NACL)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900670void MessageLoopForUI::AddObserver(Observer* observer) {
671 pump_ui()->AddObserver(observer);
672}
673
674void MessageLoopForUI::RemoveObserver(Observer* observer) {
675 pump_ui()->RemoveObserver(observer);
676}
677
678void MessageLoopForUI::Run(Dispatcher* dispatcher) {
679 AutoRunState save_state(this);
680 state_->dispatcher = dispatcher;
681 RunHandler();
682}
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900683#endif // !defined(OS_MACOSX) && !defined(OS_NACL)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900684
darin@google.comd936b5b2008-08-26 14:53:57 +0900685//------------------------------------------------------------------------------
686// MessageLoopForIO
687
688#if defined(OS_WIN)
689
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900690void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
691 pump_io()->RegisterIOHandler(file, handler);
692}
693
rvargas@google.com73887542008-11-08 06:52:15 +0900694bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
695 return pump_io()->WaitForIOCompletion(timeout, filter);
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900696}
697
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900698#elif defined(OS_POSIX) && !defined(OS_NACL)
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900699
jeremy@chromium.orgefc0db02008-12-16 07:02:17 +0900700bool MessageLoopForIO::WatchFileDescriptor(int fd,
701 bool persistent,
702 Mode mode,
703 FileDescriptorWatcher *controller,
704 Watcher *delegate) {
705 return pump_libevent()->WatchFileDescriptor(
706 fd,
707 persistent,
708 static_cast<base::MessagePumpLibevent::Mode>(mode),
709 controller,
710 delegate);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900711}
712
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900713#endif