blob: eec8a2429b2bd0c4662ec65a9c8c27e3572ff717 [file] [log] [blame]
[email protected]e6e55fb2010-04-15 01:04:291// Copyright (c) 2010 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commitd7cae122008-07-26 21:49:384
[email protected]ea15e982008-08-15 07:31:205#include "base/message_loop.h"
6
[email protected]fc7fb6e2008-08-16 03:09:057#include <algorithm>
8
[email protected]f1ea2fa2008-08-21 22:26:069#include "base/compiler_specific.h"
[email protected]f886b7bf2008-09-10 10:54:0610#include "base/lazy_instance.h"
initial.commitd7cae122008-07-26 21:49:3811#include "base/logging.h"
[email protected]b16ef312008-08-19 18:36:2312#include "base/message_pump_default.h"
[email protected]835d7c82010-10-14 04:38:3813#include "base/metrics/histogram.h"
[email protected]d8858e372011-01-04 19:06:5114#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
[email protected]1357c322010-12-30 22:18:5615#include "base/threading/thread_local.h"
initial.commitd7cae122008-07-26 21:49:3816
[email protected]96c9ea12008-09-23 21:08:2817#if defined(OS_MACOSX)
18#include "base/message_pump_mac.h"
19#endif
[email protected]36987e92008-09-18 18:46:2620#if defined(OS_POSIX)
21#include "base/message_pump_libevent.h"
[email protected]36987e92008-09-18 18:46:2622#endif
[email protected]e43eddf12009-12-29 00:32:5223#if defined(OS_POSIX) && !defined(OS_MACOSX)
[email protected]8fc3a482008-10-03 16:52:5924#include "base/message_pump_glib.h"
25#endif
[email protected]71ad9c6f2010-10-22 16:17:4726#if defined(TOUCH_UI)
27#include "base/message_pump_glib_x.h"
28#endif
[email protected]36987e92008-09-18 18:46:2629
[email protected]e1acf6f2008-10-27 20:43:3330using base::TimeDelta;
[email protected]7e7fab42010-11-06 22:23:2931using base::TimeTicks;
[email protected]e1acf6f2008-10-27 20:43:3332
[email protected]5097dc82010-07-15 17:23:2333namespace {
34
[email protected]f886b7bf2008-09-10 10:54:0635// A lazily created thread local storage for quick access to a thread's message
36// loop, if one exists. This should be safe and free of static constructors.
[email protected]5097dc82010-07-15 17:23:2337base::LazyInstance<base::ThreadLocalPointer<MessageLoop> > lazy_tls_ptr(
[email protected]f886b7bf2008-09-10 10:54:0638 base::LINKER_INITIALIZED);
initial.commitd7cae122008-07-26 21:49:3839
initial.commitd7cae122008-07-26 21:49:3840// Logical events for Histogram profiling. Run with -message-loop-histogrammer
41// to get an accounting of messages and actions taken on each thread.
[email protected]5097dc82010-07-15 17:23:2342const int kTaskRunEvent = 0x1;
43const int kTimerEvent = 0x2;
initial.commitd7cae122008-07-26 21:49:3844
45// Provide range of message IDs for use in histogramming and debug display.
[email protected]5097dc82010-07-15 17:23:2346const int kLeastNonZeroMessageId = 1;
47const int kMaxMessageId = 1099;
48const int kNumberOfDistinctMessagesDisplayed = 1100;
49
50// Provide a macro that takes an expression (such as a constant, or macro
51// constant) and creates a pair to initalize an array of pairs. In this case,
52// our pair consists of the expressions value, and the "stringized" version
53// of the expression (i.e., the exrpression put in quotes). For example, if
54// we have:
55// #define FOO 2
56// #define BAR 5
57// then the following:
58// VALUE_TO_NUMBER_AND_NAME(FOO + BAR)
59// will expand to:
60// {7, "FOO + BAR"}
61// We use the resulting array as an argument to our histogram, which reads the
62// number as a bucket identifier, and proceeds to use the corresponding name
63// in the pair (i.e., the quoted string) when printing out a histogram.
64#define VALUE_TO_NUMBER_AND_NAME(name) {name, #name},
65
[email protected]835d7c82010-10-14 04:38:3866const base::LinearHistogram::DescriptionPair event_descriptions_[] = {
[email protected]5097dc82010-07-15 17:23:2367 // Provide some pretty print capability in our histogram for our internal
68 // messages.
69
70 // A few events we handle (kindred to messages), and used to profile actions.
71 VALUE_TO_NUMBER_AND_NAME(kTaskRunEvent)
72 VALUE_TO_NUMBER_AND_NAME(kTimerEvent)
73
74 {-1, NULL} // The list must be null terminated, per API to histogram.
75};
76
77bool enable_histogrammer_ = false;
78
79} // namespace
initial.commitd7cae122008-07-26 21:49:3880
81//------------------------------------------------------------------------------
82
[email protected]fc7fb6e2008-08-16 03:09:0583#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:3884
initial.commitd7cae122008-07-26 21:49:3885// Upon a SEH exception in this thread, it restores the original unhandled
86// exception filter.
87static int SEHFilter(LPTOP_LEVEL_EXCEPTION_FILTER old_filter) {
88 ::SetUnhandledExceptionFilter(old_filter);
89 return EXCEPTION_CONTINUE_SEARCH;
90}
91
92// Retrieves a pointer to the current unhandled exception filter. There
93// is no standalone getter method.
94static LPTOP_LEVEL_EXCEPTION_FILTER GetTopSEHFilter() {
95 LPTOP_LEVEL_EXCEPTION_FILTER top_filter = NULL;
96 top_filter = ::SetUnhandledExceptionFilter(0);
97 ::SetUnhandledExceptionFilter(top_filter);
98 return top_filter;
99}
100
[email protected]fc7fb6e2008-08-16 03:09:05101#endif // defined(OS_WIN)
102
initial.commitd7cae122008-07-26 21:49:38103//------------------------------------------------------------------------------
104
[email protected]3a3d47472010-07-15 21:03:54105MessageLoop::TaskObserver::TaskObserver() {
106}
107
108MessageLoop::TaskObserver::~TaskObserver() {
109}
110
111MessageLoop::DestructionObserver::~DestructionObserver() {
112}
113
114//------------------------------------------------------------------------------
115
[email protected]f886b7bf2008-09-10 10:54:06116// static
117MessageLoop* MessageLoop::current() {
118 // TODO(darin): sadly, we cannot enable this yet since people call us even
119 // when they have no intention of using us.
[email protected]2fdc86a2010-01-26 23:08:02120 // DCHECK(loop) << "Ouch, did you forget to initialize me?";
[email protected]f886b7bf2008-09-10 10:54:06121 return lazy_tls_ptr.Pointer()->Get();
122}
123
[email protected]4d9bdfaf2008-08-26 05:53:57124MessageLoop::MessageLoop(Type type)
125 : type_(type),
[email protected]a5b94a92008-08-12 23:25:43126 nestable_tasks_allowed_(true),
[email protected]b16ef312008-08-19 18:36:23127 exception_restoration_(false),
[email protected]752578562008-09-07 08:08:29128 state_(NULL),
129 next_sequence_num_(0) {
[email protected]f886b7bf2008-09-10 10:54:06130 DCHECK(!current()) << "should only have one message loop per thread";
131 lazy_tls_ptr.Pointer()->Set(this);
[email protected]4d9bdfaf2008-08-26 05:53:57132
[email protected]e6e55fb2010-04-15 01:04:29133// TODO(rvargas): Get rid of the OS guards.
[email protected]fc7fb6e2008-08-16 03:09:05134#if defined(OS_WIN)
[email protected]e6e55fb2010-04-15 01:04:29135#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
136#define MESSAGE_PUMP_IO new base::MessagePumpForIO()
137#elif defined(OS_MACOSX)
138#define MESSAGE_PUMP_UI base::MessagePumpMac::Create()
139#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
[email protected]71ad9c6f2010-10-22 16:17:47140#elif defined(TOUCH_UI)
[email protected]8e6e26f2010-12-16 19:43:30141#define MESSAGE_PUMP_UI new base::MessagePumpGlibX()
[email protected]71ad9c6f2010-10-22 16:17:47142#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
[email protected]5cffdfd2010-12-01 08:45:51143#elif defined(OS_NACL)
144// Currently NaCl doesn't have a UI or an IO MessageLoop.
145// TODO(abarth): Figure out if we need these.
146#define MESSAGE_PUMP_UI NULL
147#define MESSAGE_PUMP_IO NULL
[email protected]e6e55fb2010-04-15 01:04:29148#elif defined(OS_POSIX) // POSIX but not MACOSX.
149#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
150#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
[email protected]e43eddf12009-12-29 00:32:52151#else
[email protected]e6e55fb2010-04-15 01:04:29152#error Not implemented
[email protected]e43eddf12009-12-29 00:32:52153#endif
[email protected]e6e55fb2010-04-15 01:04:29154
155 if (type_ == TYPE_UI) {
156 pump_ = MESSAGE_PUMP_UI;
[email protected]8fc3a482008-10-03 16:52:59157 } else if (type_ == TYPE_IO) {
[email protected]e6e55fb2010-04-15 01:04:29158 pump_ = MESSAGE_PUMP_IO;
[email protected]36987e92008-09-18 18:46:26159 } else {
[email protected]e6e55fb2010-04-15 01:04:29160 DCHECK_EQ(TYPE_DEFAULT, type_);
[email protected]36987e92008-09-18 18:46:26161 pump_ = new base::MessagePumpDefault();
162 }
initial.commitd7cae122008-07-26 21:49:38163}
164
165MessageLoop::~MessageLoop() {
[email protected]c3bf6982010-11-10 20:28:06166 DCHECK_EQ(this, current());
[email protected]2a127252008-08-05 23:16:41167
[email protected]08de3cde2008-09-09 05:55:35168 DCHECK(!state_);
169
[email protected]001747c2008-09-10 00:37:07170 // Clean up any unprocessed tasks, but take care: deleting a task could
171 // result in the addition of more tasks (e.g., via DeleteSoon). We set a
172 // limit on the number of times we will allow a deleted task to generate more
173 // tasks. Normally, we should only pass through this loop once or twice. If
174 // we end up hitting the loop limit, then it is probably due to one task that
175 // is being stubborn. Inspect the queues to see who is left.
176 bool did_work;
177 for (int i = 0; i < 100; ++i) {
178 DeletePendingTasks();
179 ReloadWorkQueue();
180 // If we end up with empty queues, then break out of the loop.
181 did_work = DeletePendingTasks();
182 if (!did_work)
183 break;
[email protected]08de3cde2008-09-09 05:55:35184 }
[email protected]001747c2008-09-10 00:37:07185 DCHECK(!did_work);
186
[email protected]582384772010-11-30 00:25:29187 // Let interested parties have one last shot at accessing this.
188 FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
189 WillDestroyCurrentMessageLoop());
190
[email protected]001747c2008-09-10 00:37:07191 // OK, now make it so that no one can find us.
[email protected]2b89d22b22008-09-10 11:14:56192 lazy_tls_ptr.Pointer()->Set(NULL);
initial.commitd7cae122008-07-26 21:49:38193}
194
[email protected]23c386b2010-09-15 22:14:36195void MessageLoop::AddDestructionObserver(
196 DestructionObserver* destruction_observer) {
[email protected]c3bf6982010-11-10 20:28:06197 DCHECK_EQ(this, current());
[email protected]23c386b2010-09-15 22:14:36198 destruction_observers_.AddObserver(destruction_observer);
[email protected]2a127252008-08-05 23:16:41199}
200
[email protected]23c386b2010-09-15 22:14:36201void MessageLoop::RemoveDestructionObserver(
202 DestructionObserver* destruction_observer) {
[email protected]c3bf6982010-11-10 20:28:06203 DCHECK_EQ(this, current());
[email protected]23c386b2010-09-15 22:14:36204 destruction_observers_.RemoveObserver(destruction_observer);
[email protected]2a127252008-08-05 23:16:41205}
206
[email protected]23c386b2010-09-15 22:14:36207void MessageLoop::AddTaskObserver(TaskObserver* task_observer) {
[email protected]9cfb89a2010-06-09 21:20:41208 DCHECK_EQ(this, current());
[email protected]23c386b2010-09-15 22:14:36209 task_observers_.AddObserver(task_observer);
[email protected]9cfb89a2010-06-09 21:20:41210}
211
[email protected]23c386b2010-09-15 22:14:36212void MessageLoop::RemoveTaskObserver(TaskObserver* task_observer) {
[email protected]9cfb89a2010-06-09 21:20:41213 DCHECK_EQ(this, current());
[email protected]23c386b2010-09-15 22:14:36214 task_observers_.RemoveObserver(task_observer);
[email protected]9cfb89a2010-06-09 21:20:41215}
216
[email protected]ea15e982008-08-15 07:31:20217void MessageLoop::Run() {
[email protected]fc7fb6e2008-08-16 03:09:05218 AutoRunState save_state(this);
219 RunHandler();
[email protected]ea15e982008-08-15 07:31:20220}
221
[email protected]7e0e8762008-07-31 13:10:20222void MessageLoop::RunAllPending() {
[email protected]fc7fb6e2008-08-16 03:09:05223 AutoRunState save_state(this);
224 state_->quit_received = true; // Means run until we would otherwise block.
225 RunHandler();
initial.commitd7cae122008-07-26 21:49:38226}
227
228// Runs the loop in two different SEH modes:
229// enable_SEH_restoration_ = false : any unhandled exception goes to the last
230// one that calls SetUnhandledExceptionFilter().
231// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
232// that was existed before the loop was run.
[email protected]fc7fb6e2008-08-16 03:09:05233void MessageLoop::RunHandler() {
234#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38235 if (exception_restoration_) {
[email protected]aff8a132009-10-26 18:15:59236 RunInternalInSEHFrame();
[email protected]fc7fb6e2008-08-16 03:09:05237 return;
initial.commitd7cae122008-07-26 21:49:38238 }
[email protected]fc7fb6e2008-08-16 03:09:05239#endif
240
241 RunInternal();
initial.commitd7cae122008-07-26 21:49:38242}
[email protected]aff8a132009-10-26 18:15:59243//------------------------------------------------------------------------------
244#if defined(OS_WIN)
245__declspec(noinline) void MessageLoop::RunInternalInSEHFrame() {
246 LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
247 __try {
248 RunInternal();
249 } __except(SEHFilter(current_filter)) {
250 }
251 return;
252}
253#endif
initial.commitd7cae122008-07-26 21:49:38254//------------------------------------------------------------------------------
initial.commitd7cae122008-07-26 21:49:38255
[email protected]fc7fb6e2008-08-16 03:09:05256void MessageLoop::RunInternal() {
[email protected]c3bf6982010-11-10 20:28:06257 DCHECK_EQ(this, current());
[email protected]fc7fb6e2008-08-16 03:09:05258
initial.commitd7cae122008-07-26 21:49:38259 StartHistogrammer();
260
[email protected]e43eddf12009-12-29 00:32:52261#if !defined(OS_MACOSX)
[email protected]148d1052009-07-31 22:53:37262 if (state_->dispatcher && type() == TYPE_UI) {
263 static_cast<base::MessagePumpForUI*>(pump_.get())->
264 RunWithDispatcher(this, state_->dispatcher);
[email protected]fc7fb6e2008-08-16 03:09:05265 return;
[email protected]7e0e8762008-07-31 13:10:20266 }
[email protected]fc7fb6e2008-08-16 03:09:05267#endif
[email protected]1d2eb132008-12-08 17:36:06268
[email protected]fc7fb6e2008-08-16 03:09:05269 pump_->Run(this);
[email protected]b8f2fe5d2008-07-30 07:50:53270}
[email protected]7622bd02008-07-30 06:58:56271
[email protected]3882c4332008-07-30 19:03:59272//------------------------------------------------------------------------------
273// Wrapper functions for use in above message loop framework.
274
initial.commitd7cae122008-07-26 21:49:38275bool MessageLoop::ProcessNextDelayedNonNestableTask() {
[email protected]fc7fb6e2008-08-16 03:09:05276 if (state_->run_depth != 1)
initial.commitd7cae122008-07-26 21:49:38277 return false;
278
[email protected]752578562008-09-07 08:08:29279 if (deferred_non_nestable_work_queue_.empty())
initial.commitd7cae122008-07-26 21:49:38280 return false;
[email protected]1d2eb132008-12-08 17:36:06281
[email protected]752578562008-09-07 08:08:29282 Task* task = deferred_non_nestable_work_queue_.front().task;
283 deferred_non_nestable_work_queue_.pop();
[email protected]1d2eb132008-12-08 17:36:06284
[email protected]752578562008-09-07 08:08:29285 RunTask(task);
initial.commitd7cae122008-07-26 21:49:38286 return true;
287}
288
initial.commitd7cae122008-07-26 21:49:38289//------------------------------------------------------------------------------
290
291void MessageLoop::Quit() {
[email protected]c3bf6982010-11-10 20:28:06292 DCHECK_EQ(this, current());
[email protected]fc7fb6e2008-08-16 03:09:05293 if (state_) {
294 state_->quit_received = true;
295 } else {
296 NOTREACHED() << "Must be inside Run to call Quit";
initial.commitd7cae122008-07-26 21:49:38297 }
initial.commitd7cae122008-07-26 21:49:38298}
299
[email protected]781a7ed2010-02-23 07:12:22300void MessageLoop::QuitNow() {
[email protected]c3bf6982010-11-10 20:28:06301 DCHECK_EQ(this, current());
[email protected]781a7ed2010-02-23 07:12:22302 if (state_) {
303 pump_->Quit();
304 } else {
305 NOTREACHED() << "Must be inside Run to call Quit";
306 }
307}
308
[email protected]752578562008-09-07 08:08:29309void MessageLoop::PostTask(
310 const tracked_objects::Location& from_here, Task* task) {
311 PostTask_Helper(from_here, task, 0, true);
312}
313
314void MessageLoop::PostDelayedTask(
[email protected]743ace42009-06-17 17:23:51315 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
[email protected]752578562008-09-07 08:08:29316 PostTask_Helper(from_here, task, delay_ms, true);
317}
318
319void MessageLoop::PostNonNestableTask(
320 const tracked_objects::Location& from_here, Task* task) {
321 PostTask_Helper(from_here, task, 0, false);
322}
323
324void MessageLoop::PostNonNestableDelayedTask(
[email protected]743ace42009-06-17 17:23:51325 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
[email protected]752578562008-09-07 08:08:29326 PostTask_Helper(from_here, task, delay_ms, false);
327}
328
initial.commitd7cae122008-07-26 21:49:38329// Possibly called on a background thread!
[email protected]752578562008-09-07 08:08:29330void MessageLoop::PostTask_Helper(
[email protected]743ace42009-06-17 17:23:51331 const tracked_objects::Location& from_here, Task* task, int64 delay_ms,
[email protected]752578562008-09-07 08:08:29332 bool nestable) {
initial.commitd7cae122008-07-26 21:49:38333 task->SetBirthPlace(from_here);
[email protected]9bcbf472008-08-30 00:22:48334
[email protected]752578562008-09-07 08:08:29335 PendingTask pending_task(task, nestable);
[email protected]9bcbf472008-08-30 00:22:48336
337 if (delay_ms > 0) {
[email protected]752578562008-09-07 08:08:29338 pending_task.delayed_run_time =
[email protected]7e7fab42010-11-06 22:23:29339 TimeTicks::Now() + TimeDelta::FromMilliseconds(delay_ms);
[email protected]57f030a2010-06-29 04:58:15340
341#if defined(OS_WIN)
342 if (high_resolution_timer_expiration_.is_null()) {
343 // Windows timers are granular to 15.6ms. If we only set high-res
344 // timers for those under 15.6ms, then a 18ms timer ticks at ~32ms,
345 // which as a percentage is pretty inaccurate. So enable high
346 // res timers for any timer which is within 2x of the granularity.
347 // This is a tradeoff between accuracy and power management.
348 bool needs_high_res_timers =
[email protected]31a897acd2010-12-20 22:00:02349 delay_ms < (2 * base::Time::kMinLowResolutionThresholdMs);
[email protected]57f030a2010-06-29 04:58:15350 if (needs_high_res_timers) {
[email protected]31a897acd2010-12-20 22:00:02351 base::Time::ActivateHighResolutionTimer(true);
[email protected]7e7fab42010-11-06 22:23:29352 high_resolution_timer_expiration_ = TimeTicks::Now() +
[email protected]21766d752010-10-20 10:50:38353 TimeDelta::FromMilliseconds(kHighResolutionTimerModeLeaseTimeMs);
[email protected]57f030a2010-06-29 04:58:15354 }
355 }
356#endif
[email protected]9bcbf472008-08-30 00:22:48357 } else {
[email protected]2753b392009-12-28 06:59:52358 DCHECK_EQ(delay_ms, 0) << "delay should not be negative";
[email protected]9bcbf472008-08-30 00:22:48359 }
360
[email protected]57f030a2010-06-29 04:58:15361#if defined(OS_WIN)
362 if (!high_resolution_timer_expiration_.is_null()) {
[email protected]7e7fab42010-11-06 22:23:29363 if (TimeTicks::Now() > high_resolution_timer_expiration_) {
[email protected]31a897acd2010-12-20 22:00:02364 base::Time::ActivateHighResolutionTimer(false);
[email protected]7e7fab42010-11-06 22:23:29365 high_resolution_timer_expiration_ = TimeTicks();
[email protected]57f030a2010-06-29 04:58:15366 }
367 }
368#endif
369
initial.commitd7cae122008-07-26 21:49:38370 // Warning: Don't try to short-circuit, and handle this thread's tasks more
371 // directly, as it could starve handling of foreign threads. Put every task
372 // into this queue.
373
[email protected]fc7fb6e2008-08-16 03:09:05374 scoped_refptr<base::MessagePump> pump;
initial.commitd7cae122008-07-26 21:49:38375 {
[email protected]fc7fb6e2008-08-16 03:09:05376 AutoLock locked(incoming_queue_lock_);
377
[email protected]752578562008-09-07 08:08:29378 bool was_empty = incoming_queue_.empty();
379 incoming_queue_.push(pending_task);
initial.commitd7cae122008-07-26 21:49:38380 if (!was_empty)
381 return; // Someone else should have started the sub-pump.
382
[email protected]fc7fb6e2008-08-16 03:09:05383 pump = pump_;
[email protected]ea15e982008-08-15 07:31:20384 }
[email protected]fc7fb6e2008-08-16 03:09:05385 // Since the incoming_queue_ may contain a task that destroys this message
386 // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
387 // We use a stack-based reference to the message pump so that we can call
388 // ScheduleWork outside of incoming_queue_lock_.
[email protected]ea15e982008-08-15 07:31:20389
[email protected]fc7fb6e2008-08-16 03:09:05390 pump->ScheduleWork();
initial.commitd7cae122008-07-26 21:49:38391}
392
393void MessageLoop::SetNestableTasksAllowed(bool allowed) {
[email protected]124a2bdf2008-08-09 00:14:09394 if (nestable_tasks_allowed_ != allowed) {
395 nestable_tasks_allowed_ = allowed;
396 if (!nestable_tasks_allowed_)
397 return;
398 // Start the native pump if we are not already pumping.
[email protected]fc7fb6e2008-08-16 03:09:05399 pump_->ScheduleWork();
[email protected]124a2bdf2008-08-09 00:14:09400 }
initial.commitd7cae122008-07-26 21:49:38401}
402
403bool MessageLoop::NestableTasksAllowed() const {
404 return nestable_tasks_allowed_;
405}
406
[email protected]b5f95102009-07-01 19:53:59407bool MessageLoop::IsNested() {
408 return state_->run_depth > 1;
409}
410
initial.commitd7cae122008-07-26 21:49:38411//------------------------------------------------------------------------------
initial.commitd7cae122008-07-26 21:49:38412
initial.commitd7cae122008-07-26 21:49:38413void MessageLoop::RunTask(Task* task) {
initial.commitd7cae122008-07-26 21:49:38414 DCHECK(nestable_tasks_allowed_);
415 // Execute the task and assume the worst: It is probably not reentrant.
416 nestable_tasks_allowed_ = false;
[email protected]752578562008-09-07 08:08:29417
418 HistogramEvent(kTaskRunEvent);
[email protected]9cfb89a2010-06-09 21:20:41419 FOR_EACH_OBSERVER(TaskObserver, task_observers_,
[email protected]024686682010-10-26 23:40:48420 WillProcessTask(task));
[email protected]752578562008-09-07 08:08:29421 task->Run();
[email protected]024686682010-10-26 23:40:48422 FOR_EACH_OBSERVER(TaskObserver, task_observers_, DidProcessTask(task));
[email protected]752578562008-09-07 08:08:29423 delete task;
424
425 nestable_tasks_allowed_ = true;
initial.commitd7cae122008-07-26 21:49:38426}
427
[email protected]752578562008-09-07 08:08:29428bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) {
429 if (pending_task.nestable || state_->run_depth == 1) {
430 RunTask(pending_task.task);
431 // Show that we ran a task (Note: a new one might arrive as a
432 // consequence!).
433 return true;
434 }
435
436 // We couldn't run the task now because we're in a nested message loop
437 // and the task isn't nestable.
438 deferred_non_nestable_work_queue_.push(pending_task);
439 return false;
initial.commitd7cae122008-07-26 21:49:38440}
441
[email protected]001747c2008-09-10 00:37:07442void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
443 // Move to the delayed work queue. Initialize the sequence number
444 // before inserting into the delayed_work_queue_. The sequence number
445 // is used to faciliate FIFO sorting when two tasks have the same
446 // delayed_run_time value.
447 PendingTask new_pending_task(pending_task);
448 new_pending_task.sequence_num = next_sequence_num_++;
449 delayed_work_queue_.push(new_pending_task);
450}
451
initial.commitd7cae122008-07-26 21:49:38452void MessageLoop::ReloadWorkQueue() {
453 // We can improve performance of our loading tasks from incoming_queue_ to
[email protected]fc7fb6e2008-08-16 03:09:05454 // work_queue_ by waiting until the last minute (work_queue_ is empty) to
455 // load. That reduces the number of locks-per-task significantly when our
[email protected]752578562008-09-07 08:08:29456 // queues get large.
457 if (!work_queue_.empty())
initial.commitd7cae122008-07-26 21:49:38458 return; // Wait till we *really* need to lock and load.
459
460 // Acquire all we can from the inter-thread queue with one lock acquisition.
initial.commitd7cae122008-07-26 21:49:38461 {
462 AutoLock lock(incoming_queue_lock_);
[email protected]752578562008-09-07 08:08:29463 if (incoming_queue_.empty())
initial.commitd7cae122008-07-26 21:49:38464 return;
[email protected]b2f0ea12009-09-02 20:05:21465 incoming_queue_.Swap(&work_queue_); // Constant time
[email protected]752578562008-09-07 08:08:29466 DCHECK(incoming_queue_.empty());
initial.commitd7cae122008-07-26 21:49:38467 }
468}
469
[email protected]001747c2008-09-10 00:37:07470bool MessageLoop::DeletePendingTasks() {
471 bool did_work = !work_queue_.empty();
472 while (!work_queue_.empty()) {
473 PendingTask pending_task = work_queue_.front();
474 work_queue_.pop();
475 if (!pending_task.delayed_run_time.is_null()) {
476 // We want to delete delayed tasks in the same order in which they would
477 // normally be deleted in case of any funny dependencies between delayed
478 // tasks.
479 AddToDelayedWorkQueue(pending_task);
480 } else {
[email protected]24db0262010-08-03 03:06:21481 // TODO(darin): Delete all tasks once it is safe to do so.
482 // Until it is totally safe, just do it when running Purify or
483 // Valgrind.
[email protected]f4681a92010-10-27 20:03:42484#if defined(PURIFY) || defined(USE_HEAPCHECKER)
[email protected]404ec5e2009-03-11 20:06:02485 delete pending_task.task;
[email protected]d8858e372011-01-04 19:06:51486#else
487 if (RunningOnValgrind())
[email protected]24db0262010-08-03 03:06:21488 delete pending_task.task;
489#endif // defined(OS_POSIX)
[email protected]001747c2008-09-10 00:37:07490 }
initial.commitd7cae122008-07-26 21:49:38491 }
[email protected]001747c2008-09-10 00:37:07492 did_work |= !deferred_non_nestable_work_queue_.empty();
493 while (!deferred_non_nestable_work_queue_.empty()) {
[email protected]24db0262010-08-03 03:06:21494 // TODO(darin): Delete all tasks once it is safe to do so.
495 // Until it is totaly safe, only delete them under Purify and Valgrind.
496 Task* task = NULL;
[email protected]f4681a92010-10-27 20:03:42497#if defined(PURIFY) || defined(USE_HEAPCHECKER)
[email protected]24db0262010-08-03 03:06:21498 task = deferred_non_nestable_work_queue_.front().task;
[email protected]d8858e372011-01-04 19:06:51499#else
500 if (RunningOnValgrind())
[email protected]24db0262010-08-03 03:06:21501 task = deferred_non_nestable_work_queue_.front().task;
502#endif
[email protected]8df21d32009-03-11 19:53:50503 deferred_non_nestable_work_queue_.pop();
[email protected]24db0262010-08-03 03:06:21504 if (task)
505 delete task;
initial.commitd7cae122008-07-26 21:49:38506 }
[email protected]001747c2008-09-10 00:37:07507 did_work |= !delayed_work_queue_.empty();
508 while (!delayed_work_queue_.empty()) {
[email protected]24db0262010-08-03 03:06:21509 Task* task = delayed_work_queue_.top().task;
[email protected]001747c2008-09-10 00:37:07510 delayed_work_queue_.pop();
[email protected]24db0262010-08-03 03:06:21511 delete task;
[email protected]001747c2008-09-10 00:37:07512 }
513 return did_work;
initial.commitd7cae122008-07-26 21:49:38514}
515
[email protected]fc7fb6e2008-08-16 03:09:05516bool MessageLoop::DoWork() {
[email protected]752578562008-09-07 08:08:29517 if (!nestable_tasks_allowed_) {
518 // Task can't be executed right now.
519 return false;
520 }
521
522 for (;;) {
523 ReloadWorkQueue();
524 if (work_queue_.empty())
525 break;
526
527 // Execute oldest task.
528 do {
529 PendingTask pending_task = work_queue_.front();
530 work_queue_.pop();
531 if (!pending_task.delayed_run_time.is_null()) {
[email protected]001747c2008-09-10 00:37:07532 AddToDelayedWorkQueue(pending_task);
[email protected]72deacd2008-09-23 19:19:20533 // If we changed the topmost task, then it is time to re-schedule.
[email protected]11f76c72010-10-21 06:32:33534 if (delayed_work_queue_.top().task == pending_task.task)
[email protected]752578562008-09-07 08:08:29535 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
536 } else {
537 if (DeferOrRunPendingTask(pending_task))
538 return true;
539 }
540 } while (!work_queue_.empty());
541 }
542
543 // Nothing happened.
544 return false;
[email protected]fc7fb6e2008-08-16 03:09:05545}
546
[email protected]7e7fab42010-11-06 22:23:29547bool MessageLoop::DoDelayedWork(base::TimeTicks* next_delayed_work_time) {
[email protected]11f76c72010-10-21 06:32:33548 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
[email protected]7e7fab42010-11-06 22:23:29549 recent_time_ = *next_delayed_work_time = TimeTicks();
[email protected]752578562008-09-07 08:08:29550 return false;
551 }
[email protected]1d2eb132008-12-08 17:36:06552
[email protected]7e7fab42010-11-06 22:23:29553 // When we "fall behind," there will be a lot of tasks in the delayed work
[email protected]a8f7d3d2010-11-04 23:23:42554 // queue that are ready to run. To increase efficiency when we fall behind,
555 // we will only call Time::Now() intermittently, and then process all tasks
556 // that are ready to run before calling it again. As a result, the more we
557 // fall behind (and have a lot of ready-to-run delayed tasks), the more
558 // efficient we'll be at handling the tasks.
[email protected]7e7fab42010-11-06 22:23:29559
560 TimeTicks next_run_time = delayed_work_queue_.top().delayed_run_time;
[email protected]a8f7d3d2010-11-04 23:23:42561 if (next_run_time > recent_time_) {
[email protected]7e7fab42010-11-06 22:23:29562 recent_time_ = TimeTicks::Now(); // Get a better view of Now();
[email protected]a8f7d3d2010-11-04 23:23:42563 if (next_run_time > recent_time_) {
564 *next_delayed_work_time = next_run_time;
565 return false;
566 }
[email protected]752578562008-09-07 08:08:29567 }
[email protected]fc7fb6e2008-08-16 03:09:05568
[email protected]11f76c72010-10-21 06:32:33569 PendingTask pending_task = delayed_work_queue_.top();
570 delayed_work_queue_.pop();
[email protected]1d2eb132008-12-08 17:36:06571
[email protected]11f76c72010-10-21 06:32:33572 if (!delayed_work_queue_.empty())
[email protected]752578562008-09-07 08:08:29573 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
[email protected]fc7fb6e2008-08-16 03:09:05574
[email protected]752578562008-09-07 08:08:29575 return DeferOrRunPendingTask(pending_task);
[email protected]fc7fb6e2008-08-16 03:09:05576}
577
578bool MessageLoop::DoIdleWork() {
579 if (ProcessNextDelayedNonNestableTask())
580 return true;
581
582 if (state_->quit_received)
583 pump_->Quit();
584
585 return false;
586}
587
588//------------------------------------------------------------------------------
589// MessageLoop::AutoRunState
590
591MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
592 // Make the loop reference us.
593 previous_state_ = loop_->state_;
594 if (previous_state_) {
595 run_depth = previous_state_->run_depth + 1;
[email protected]ea15e982008-08-15 07:31:20596 } else {
[email protected]fc7fb6e2008-08-16 03:09:05597 run_depth = 1;
[email protected]ea15e982008-08-15 07:31:20598 }
[email protected]fc7fb6e2008-08-16 03:09:05599 loop_->state_ = this;
600
601 // Initialize the other fields:
602 quit_received = false;
[email protected]e43eddf12009-12-29 00:32:52603#if !defined(OS_MACOSX)
[email protected]fc7fb6e2008-08-16 03:09:05604 dispatcher = NULL;
605#endif
606}
607
608MessageLoop::AutoRunState::~AutoRunState() {
609 loop_->state_ = previous_state_;
[email protected]a5b94a92008-08-12 23:25:43610}
611
initial.commitd7cae122008-07-26 21:49:38612//------------------------------------------------------------------------------
[email protected]752578562008-09-07 08:08:29613// MessageLoop::PendingTask
initial.commitd7cae122008-07-26 21:49:38614
[email protected]752578562008-09-07 08:08:29615bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
616 // Since the top of a priority queue is defined as the "greatest" element, we
617 // need to invert the comparison here. We want the smaller time to be at the
618 // top of the heap.
initial.commitd7cae122008-07-26 21:49:38619
[email protected]752578562008-09-07 08:08:29620 if (delayed_run_time < other.delayed_run_time)
621 return false;
initial.commitd7cae122008-07-26 21:49:38622
[email protected]752578562008-09-07 08:08:29623 if (delayed_run_time > other.delayed_run_time)
624 return true;
initial.commitd7cae122008-07-26 21:49:38625
[email protected]752578562008-09-07 08:08:29626 // If the times happen to match, then we use the sequence number to decide.
627 // Compare the difference to support integer roll-over.
628 return (sequence_num - other.sequence_num) > 0;
initial.commitd7cae122008-07-26 21:49:38629}
630
631//------------------------------------------------------------------------------
632// Method and data for histogramming events and actions taken by each instance
633// on each thread.
634
635// static
initial.commitd7cae122008-07-26 21:49:38636void MessageLoop::EnableHistogrammer(bool enable) {
637 enable_histogrammer_ = enable;
638}
639
640void MessageLoop::StartHistogrammer() {
641 if (enable_histogrammer_ && !message_histogram_.get()
[email protected]d14425542010-12-23 14:40:10642 && base::StatisticsRecorder::IsActive()) {
[email protected]fc7fb6e2008-08-16 03:09:05643 DCHECK(!thread_name_.empty());
[email protected]835d7c82010-10-14 04:38:38644 message_histogram_ = base::LinearHistogram::FactoryGet(
645 "MsgLoop:" + thread_name_,
[email protected]2753b392009-12-28 06:59:52646 kLeastNonZeroMessageId, kMaxMessageId,
647 kNumberOfDistinctMessagesDisplayed,
648 message_histogram_->kHexRangePrintingFlag);
initial.commitd7cae122008-07-26 21:49:38649 message_histogram_->SetRangeDescriptions(event_descriptions_);
650 }
651}
652
653void MessageLoop::HistogramEvent(int event) {
654 if (message_histogram_.get())
655 message_histogram_->Add(event);
656}
657
[email protected]4d9bdfaf2008-08-26 05:53:57658//------------------------------------------------------------------------------
659// MessageLoopForUI
660
661#if defined(OS_WIN)
[email protected]4d9bdfaf2008-08-26 05:53:57662void MessageLoopForUI::DidProcessMessage(const MSG& message) {
663 pump_win()->DidProcessMessage(message);
664}
[email protected]4d9bdfaf2008-08-26 05:53:57665#endif // defined(OS_WIN)
666
[email protected]5cffdfd2010-12-01 08:45:51667#if !defined(OS_MACOSX) && !defined(OS_NACL)
[email protected]148d1052009-07-31 22:53:37668void MessageLoopForUI::AddObserver(Observer* observer) {
669 pump_ui()->AddObserver(observer);
670}
671
672void MessageLoopForUI::RemoveObserver(Observer* observer) {
673 pump_ui()->RemoveObserver(observer);
674}
675
676void MessageLoopForUI::Run(Dispatcher* dispatcher) {
677 AutoRunState save_state(this);
678 state_->dispatcher = dispatcher;
679 RunHandler();
680}
[email protected]5cffdfd2010-12-01 08:45:51681#endif // !defined(OS_MACOSX) && !defined(OS_NACL)
[email protected]148d1052009-07-31 22:53:37682
[email protected]4d9bdfaf2008-08-26 05:53:57683//------------------------------------------------------------------------------
684// MessageLoopForIO
685
686#if defined(OS_WIN)
687
[email protected]32cda29d2008-10-09 23:58:43688void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
689 pump_io()->RegisterIOHandler(file, handler);
690}
691
[email protected]17b89142008-11-07 21:52:15692bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
693 return pump_io()->WaitForIOCompletion(timeout, filter);
[email protected]32cda29d2008-10-09 23:58:43694}
695
[email protected]5cffdfd2010-12-01 08:45:51696#elif defined(OS_POSIX) && !defined(OS_NACL)
[email protected]36987e92008-09-18 18:46:26697
[email protected]e45e6c02008-12-15 22:02:17698bool MessageLoopForIO::WatchFileDescriptor(int fd,
699 bool persistent,
700 Mode mode,
701 FileDescriptorWatcher *controller,
702 Watcher *delegate) {
703 return pump_libevent()->WatchFileDescriptor(
704 fd,
705 persistent,
706 static_cast<base::MessagePumpLibevent::Mode>(mode),
707 controller,
708 delegate);
[email protected]36987e92008-09-18 18:46:26709}
710
[email protected]36987e92008-09-18 18:46:26711#endif