blob: b926c79515d411f0a424f8a6ed53b5ed2203782e [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]f886b7bf2008-09-10 10:54:0614#include "base/thread_local.h"
initial.commitd7cae122008-07-26 21:49:3815
[email protected]96c9ea12008-09-23 21:08:2816#if defined(OS_MACOSX)
17#include "base/message_pump_mac.h"
18#endif
[email protected]36987e92008-09-18 18:46:2619#if defined(OS_POSIX)
20#include "base/message_pump_libevent.h"
[email protected]d680c5c2009-05-14 16:44:2621#include "base/third_party/valgrind/valgrind.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::Time;
31using base::TimeDelta;
32
[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)
141#define MESSAGE_PUMP_UI new base::MessagePumpGlibX()
142#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
[email protected]e6e55fb2010-04-15 01:04:29143#elif defined(OS_POSIX) // POSIX but not MACOSX.
144#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
145#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
[email protected]e43eddf12009-12-29 00:32:52146#else
[email protected]e6e55fb2010-04-15 01:04:29147#error Not implemented
[email protected]e43eddf12009-12-29 00:32:52148#endif
[email protected]e6e55fb2010-04-15 01:04:29149
150 if (type_ == TYPE_UI) {
151 pump_ = MESSAGE_PUMP_UI;
[email protected]8fc3a482008-10-03 16:52:59152 } else if (type_ == TYPE_IO) {
[email protected]e6e55fb2010-04-15 01:04:29153 pump_ = MESSAGE_PUMP_IO;
[email protected]36987e92008-09-18 18:46:26154 } else {
[email protected]e6e55fb2010-04-15 01:04:29155 DCHECK_EQ(TYPE_DEFAULT, type_);
[email protected]36987e92008-09-18 18:46:26156 pump_ = new base::MessagePumpDefault();
157 }
initial.commitd7cae122008-07-26 21:49:38158}
159
160MessageLoop::~MessageLoop() {
161 DCHECK(this == current());
[email protected]2a127252008-08-05 23:16:41162
163 // Let interested parties have one last shot at accessing this.
164 FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
165 WillDestroyCurrentMessageLoop());
166
[email protected]08de3cde2008-09-09 05:55:35167 DCHECK(!state_);
168
[email protected]001747c2008-09-10 00:37:07169 // Clean up any unprocessed tasks, but take care: deleting a task could
170 // result in the addition of more tasks (e.g., via DeleteSoon). We set a
171 // limit on the number of times we will allow a deleted task to generate more
172 // tasks. Normally, we should only pass through this loop once or twice. If
173 // we end up hitting the loop limit, then it is probably due to one task that
174 // is being stubborn. Inspect the queues to see who is left.
175 bool did_work;
176 for (int i = 0; i < 100; ++i) {
177 DeletePendingTasks();
178 ReloadWorkQueue();
179 // If we end up with empty queues, then break out of the loop.
180 did_work = DeletePendingTasks();
181 if (!did_work)
182 break;
[email protected]08de3cde2008-09-09 05:55:35183 }
[email protected]001747c2008-09-10 00:37:07184 DCHECK(!did_work);
185
186 // OK, now make it so that no one can find us.
[email protected]2b89d22b22008-09-10 11:14:56187 lazy_tls_ptr.Pointer()->Set(NULL);
initial.commitd7cae122008-07-26 21:49:38188}
189
[email protected]23c386b2010-09-15 22:14:36190void MessageLoop::AddDestructionObserver(
191 DestructionObserver* destruction_observer) {
[email protected]2a127252008-08-05 23:16:41192 DCHECK(this == current());
[email protected]23c386b2010-09-15 22:14:36193 destruction_observers_.AddObserver(destruction_observer);
[email protected]2a127252008-08-05 23:16:41194}
195
[email protected]23c386b2010-09-15 22:14:36196void MessageLoop::RemoveDestructionObserver(
197 DestructionObserver* destruction_observer) {
[email protected]2a127252008-08-05 23:16:41198 DCHECK(this == current());
[email protected]23c386b2010-09-15 22:14:36199 destruction_observers_.RemoveObserver(destruction_observer);
[email protected]2a127252008-08-05 23:16:41200}
201
[email protected]23c386b2010-09-15 22:14:36202void MessageLoop::AddTaskObserver(TaskObserver* task_observer) {
[email protected]9cfb89a2010-06-09 21:20:41203 DCHECK_EQ(this, current());
[email protected]23c386b2010-09-15 22:14:36204 task_observers_.AddObserver(task_observer);
[email protected]9cfb89a2010-06-09 21:20:41205}
206
[email protected]23c386b2010-09-15 22:14:36207void MessageLoop::RemoveTaskObserver(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_.RemoveObserver(task_observer);
[email protected]9cfb89a2010-06-09 21:20:41210}
211
[email protected]ea15e982008-08-15 07:31:20212void MessageLoop::Run() {
[email protected]fc7fb6e2008-08-16 03:09:05213 AutoRunState save_state(this);
214 RunHandler();
[email protected]ea15e982008-08-15 07:31:20215}
216
[email protected]7e0e8762008-07-31 13:10:20217void MessageLoop::RunAllPending() {
[email protected]fc7fb6e2008-08-16 03:09:05218 AutoRunState save_state(this);
219 state_->quit_received = true; // Means run until we would otherwise block.
220 RunHandler();
initial.commitd7cae122008-07-26 21:49:38221}
222
223// Runs the loop in two different SEH modes:
224// enable_SEH_restoration_ = false : any unhandled exception goes to the last
225// one that calls SetUnhandledExceptionFilter().
226// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
227// that was existed before the loop was run.
[email protected]fc7fb6e2008-08-16 03:09:05228void MessageLoop::RunHandler() {
229#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38230 if (exception_restoration_) {
[email protected]aff8a132009-10-26 18:15:59231 RunInternalInSEHFrame();
[email protected]fc7fb6e2008-08-16 03:09:05232 return;
initial.commitd7cae122008-07-26 21:49:38233 }
[email protected]fc7fb6e2008-08-16 03:09:05234#endif
235
236 RunInternal();
initial.commitd7cae122008-07-26 21:49:38237}
[email protected]aff8a132009-10-26 18:15:59238//------------------------------------------------------------------------------
239#if defined(OS_WIN)
240__declspec(noinline) void MessageLoop::RunInternalInSEHFrame() {
241 LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
242 __try {
243 RunInternal();
244 } __except(SEHFilter(current_filter)) {
245 }
246 return;
247}
248#endif
initial.commitd7cae122008-07-26 21:49:38249//------------------------------------------------------------------------------
initial.commitd7cae122008-07-26 21:49:38250
[email protected]fc7fb6e2008-08-16 03:09:05251void MessageLoop::RunInternal() {
252 DCHECK(this == current());
253
initial.commitd7cae122008-07-26 21:49:38254 StartHistogrammer();
255
[email protected]e43eddf12009-12-29 00:32:52256#if !defined(OS_MACOSX)
[email protected]148d1052009-07-31 22:53:37257 if (state_->dispatcher && type() == TYPE_UI) {
258 static_cast<base::MessagePumpForUI*>(pump_.get())->
259 RunWithDispatcher(this, state_->dispatcher);
[email protected]fc7fb6e2008-08-16 03:09:05260 return;
[email protected]7e0e8762008-07-31 13:10:20261 }
[email protected]fc7fb6e2008-08-16 03:09:05262#endif
[email protected]1d2eb132008-12-08 17:36:06263
[email protected]fc7fb6e2008-08-16 03:09:05264 pump_->Run(this);
[email protected]b8f2fe5d2008-07-30 07:50:53265}
[email protected]7622bd02008-07-30 06:58:56266
[email protected]3882c4332008-07-30 19:03:59267//------------------------------------------------------------------------------
268// Wrapper functions for use in above message loop framework.
269
initial.commitd7cae122008-07-26 21:49:38270bool MessageLoop::ProcessNextDelayedNonNestableTask() {
[email protected]fc7fb6e2008-08-16 03:09:05271 if (state_->run_depth != 1)
initial.commitd7cae122008-07-26 21:49:38272 return false;
273
[email protected]752578562008-09-07 08:08:29274 if (deferred_non_nestable_work_queue_.empty())
initial.commitd7cae122008-07-26 21:49:38275 return false;
[email protected]1d2eb132008-12-08 17:36:06276
[email protected]752578562008-09-07 08:08:29277 Task* task = deferred_non_nestable_work_queue_.front().task;
278 deferred_non_nestable_work_queue_.pop();
[email protected]1d2eb132008-12-08 17:36:06279
[email protected]752578562008-09-07 08:08:29280 RunTask(task);
initial.commitd7cae122008-07-26 21:49:38281 return true;
282}
283
initial.commitd7cae122008-07-26 21:49:38284//------------------------------------------------------------------------------
285
286void MessageLoop::Quit() {
[email protected]fc7fb6e2008-08-16 03:09:05287 DCHECK(current() == this);
288 if (state_) {
289 state_->quit_received = true;
290 } else {
291 NOTREACHED() << "Must be inside Run to call Quit";
initial.commitd7cae122008-07-26 21:49:38292 }
initial.commitd7cae122008-07-26 21:49:38293}
294
[email protected]781a7ed2010-02-23 07:12:22295void MessageLoop::QuitNow() {
296 DCHECK(current() == this);
297 if (state_) {
298 pump_->Quit();
299 } else {
300 NOTREACHED() << "Must be inside Run to call Quit";
301 }
302}
303
[email protected]752578562008-09-07 08:08:29304void MessageLoop::PostTask(
305 const tracked_objects::Location& from_here, Task* task) {
306 PostTask_Helper(from_here, task, 0, true);
307}
308
309void MessageLoop::PostDelayedTask(
[email protected]743ace42009-06-17 17:23:51310 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
[email protected]752578562008-09-07 08:08:29311 PostTask_Helper(from_here, task, delay_ms, true);
312}
313
314void MessageLoop::PostNonNestableTask(
315 const tracked_objects::Location& from_here, Task* task) {
316 PostTask_Helper(from_here, task, 0, false);
317}
318
319void MessageLoop::PostNonNestableDelayedTask(
[email protected]743ace42009-06-17 17:23:51320 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
[email protected]752578562008-09-07 08:08:29321 PostTask_Helper(from_here, task, delay_ms, false);
322}
323
initial.commitd7cae122008-07-26 21:49:38324// Possibly called on a background thread!
[email protected]752578562008-09-07 08:08:29325void MessageLoop::PostTask_Helper(
[email protected]743ace42009-06-17 17:23:51326 const tracked_objects::Location& from_here, Task* task, int64 delay_ms,
[email protected]752578562008-09-07 08:08:29327 bool nestable) {
initial.commitd7cae122008-07-26 21:49:38328 task->SetBirthPlace(from_here);
[email protected]9bcbf472008-08-30 00:22:48329
[email protected]752578562008-09-07 08:08:29330 PendingTask pending_task(task, nestable);
[email protected]9bcbf472008-08-30 00:22:48331
332 if (delay_ms > 0) {
[email protected]752578562008-09-07 08:08:29333 pending_task.delayed_run_time =
[email protected]9bcbf472008-08-30 00:22:48334 Time::Now() + TimeDelta::FromMilliseconds(delay_ms);
[email protected]57f030a2010-06-29 04:58:15335
336#if defined(OS_WIN)
337 if (high_resolution_timer_expiration_.is_null()) {
338 // Windows timers are granular to 15.6ms. If we only set high-res
339 // timers for those under 15.6ms, then a 18ms timer ticks at ~32ms,
340 // which as a percentage is pretty inaccurate. So enable high
341 // res timers for any timer which is within 2x of the granularity.
342 // This is a tradeoff between accuracy and power management.
343 bool needs_high_res_timers =
344 delay_ms < (2 * Time::kMinLowResolutionThresholdMs);
345 if (needs_high_res_timers) {
[email protected]21766d752010-10-20 10:50:38346 Time::ActivateHighResolutionTimer(true);
347 high_resolution_timer_expiration_ = base::TimeTicks::Now() +
348 TimeDelta::FromMilliseconds(kHighResolutionTimerModeLeaseTimeMs);
[email protected]57f030a2010-06-29 04:58:15349 }
350 }
351#endif
[email protected]9bcbf472008-08-30 00:22:48352 } else {
[email protected]2753b392009-12-28 06:59:52353 DCHECK_EQ(delay_ms, 0) << "delay should not be negative";
[email protected]9bcbf472008-08-30 00:22:48354 }
355
[email protected]57f030a2010-06-29 04:58:15356#if defined(OS_WIN)
357 if (!high_resolution_timer_expiration_.is_null()) {
358 if (base::TimeTicks::Now() > high_resolution_timer_expiration_) {
359 Time::ActivateHighResolutionTimer(false);
360 high_resolution_timer_expiration_ = base::TimeTicks();
361 }
362 }
363#endif
364
initial.commitd7cae122008-07-26 21:49:38365 // Warning: Don't try to short-circuit, and handle this thread's tasks more
366 // directly, as it could starve handling of foreign threads. Put every task
367 // into this queue.
368
[email protected]fc7fb6e2008-08-16 03:09:05369 scoped_refptr<base::MessagePump> pump;
initial.commitd7cae122008-07-26 21:49:38370 {
[email protected]fc7fb6e2008-08-16 03:09:05371 AutoLock locked(incoming_queue_lock_);
372
[email protected]752578562008-09-07 08:08:29373 bool was_empty = incoming_queue_.empty();
374 incoming_queue_.push(pending_task);
initial.commitd7cae122008-07-26 21:49:38375 if (!was_empty)
376 return; // Someone else should have started the sub-pump.
377
[email protected]fc7fb6e2008-08-16 03:09:05378 pump = pump_;
[email protected]ea15e982008-08-15 07:31:20379 }
[email protected]fc7fb6e2008-08-16 03:09:05380 // Since the incoming_queue_ may contain a task that destroys this message
381 // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
382 // We use a stack-based reference to the message pump so that we can call
383 // ScheduleWork outside of incoming_queue_lock_.
[email protected]ea15e982008-08-15 07:31:20384
[email protected]fc7fb6e2008-08-16 03:09:05385 pump->ScheduleWork();
initial.commitd7cae122008-07-26 21:49:38386}
387
388void MessageLoop::SetNestableTasksAllowed(bool allowed) {
[email protected]124a2bdf2008-08-09 00:14:09389 if (nestable_tasks_allowed_ != allowed) {
390 nestable_tasks_allowed_ = allowed;
391 if (!nestable_tasks_allowed_)
392 return;
393 // Start the native pump if we are not already pumping.
[email protected]fc7fb6e2008-08-16 03:09:05394 pump_->ScheduleWork();
[email protected]124a2bdf2008-08-09 00:14:09395 }
initial.commitd7cae122008-07-26 21:49:38396}
397
398bool MessageLoop::NestableTasksAllowed() const {
399 return nestable_tasks_allowed_;
400}
401
[email protected]b5f95102009-07-01 19:53:59402bool MessageLoop::IsNested() {
403 return state_->run_depth > 1;
404}
405
initial.commitd7cae122008-07-26 21:49:38406//------------------------------------------------------------------------------
initial.commitd7cae122008-07-26 21:49:38407
initial.commitd7cae122008-07-26 21:49:38408void MessageLoop::RunTask(Task* task) {
initial.commitd7cae122008-07-26 21:49:38409 DCHECK(nestable_tasks_allowed_);
410 // Execute the task and assume the worst: It is probably not reentrant.
411 nestable_tasks_allowed_ = false;
[email protected]752578562008-09-07 08:08:29412
413 HistogramEvent(kTaskRunEvent);
[email protected]9cfb89a2010-06-09 21:20:41414 FOR_EACH_OBSERVER(TaskObserver, task_observers_,
[email protected]024686682010-10-26 23:40:48415 WillProcessTask(task));
[email protected]752578562008-09-07 08:08:29416 task->Run();
[email protected]024686682010-10-26 23:40:48417 FOR_EACH_OBSERVER(TaskObserver, task_observers_, DidProcessTask(task));
[email protected]752578562008-09-07 08:08:29418 delete task;
419
420 nestable_tasks_allowed_ = true;
initial.commitd7cae122008-07-26 21:49:38421}
422
[email protected]752578562008-09-07 08:08:29423bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) {
424 if (pending_task.nestable || state_->run_depth == 1) {
425 RunTask(pending_task.task);
426 // Show that we ran a task (Note: a new one might arrive as a
427 // consequence!).
428 return true;
429 }
430
431 // We couldn't run the task now because we're in a nested message loop
432 // and the task isn't nestable.
433 deferred_non_nestable_work_queue_.push(pending_task);
434 return false;
initial.commitd7cae122008-07-26 21:49:38435}
436
[email protected]001747c2008-09-10 00:37:07437void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
438 // Move to the delayed work queue. Initialize the sequence number
439 // before inserting into the delayed_work_queue_. The sequence number
440 // is used to faciliate FIFO sorting when two tasks have the same
441 // delayed_run_time value.
442 PendingTask new_pending_task(pending_task);
443 new_pending_task.sequence_num = next_sequence_num_++;
444 delayed_work_queue_.push(new_pending_task);
445}
446
initial.commitd7cae122008-07-26 21:49:38447void MessageLoop::ReloadWorkQueue() {
448 // We can improve performance of our loading tasks from incoming_queue_ to
[email protected]fc7fb6e2008-08-16 03:09:05449 // work_queue_ by waiting until the last minute (work_queue_ is empty) to
450 // load. That reduces the number of locks-per-task significantly when our
[email protected]752578562008-09-07 08:08:29451 // queues get large.
452 if (!work_queue_.empty())
initial.commitd7cae122008-07-26 21:49:38453 return; // Wait till we *really* need to lock and load.
454
455 // Acquire all we can from the inter-thread queue with one lock acquisition.
initial.commitd7cae122008-07-26 21:49:38456 {
457 AutoLock lock(incoming_queue_lock_);
[email protected]752578562008-09-07 08:08:29458 if (incoming_queue_.empty())
initial.commitd7cae122008-07-26 21:49:38459 return;
[email protected]b2f0ea12009-09-02 20:05:21460 incoming_queue_.Swap(&work_queue_); // Constant time
[email protected]752578562008-09-07 08:08:29461 DCHECK(incoming_queue_.empty());
initial.commitd7cae122008-07-26 21:49:38462 }
463}
464
[email protected]001747c2008-09-10 00:37:07465bool MessageLoop::DeletePendingTasks() {
466 bool did_work = !work_queue_.empty();
467 while (!work_queue_.empty()) {
468 PendingTask pending_task = work_queue_.front();
469 work_queue_.pop();
470 if (!pending_task.delayed_run_time.is_null()) {
471 // We want to delete delayed tasks in the same order in which they would
472 // normally be deleted in case of any funny dependencies between delayed
473 // tasks.
474 AddToDelayedWorkQueue(pending_task);
475 } else {
[email protected]24db0262010-08-03 03:06:21476 // TODO(darin): Delete all tasks once it is safe to do so.
477 // Until it is totally safe, just do it when running Purify or
478 // Valgrind.
[email protected]bc097702010-10-15 02:38:43479#if defined(PURIFY)
[email protected]404ec5e2009-03-11 20:06:02480 delete pending_task.task;
[email protected]24db0262010-08-03 03:06:21481#elif defined(OS_POSIX)
482 if (RUNNING_ON_VALGRIND)
483 delete pending_task.task;
484#endif // defined(OS_POSIX)
[email protected]001747c2008-09-10 00:37:07485 }
initial.commitd7cae122008-07-26 21:49:38486 }
[email protected]001747c2008-09-10 00:37:07487 did_work |= !deferred_non_nestable_work_queue_.empty();
488 while (!deferred_non_nestable_work_queue_.empty()) {
[email protected]24db0262010-08-03 03:06:21489 // TODO(darin): Delete all tasks once it is safe to do so.
490 // Until it is totaly safe, only delete them under Purify and Valgrind.
491 Task* task = NULL;
[email protected]bc097702010-10-15 02:38:43492#if defined(PURIFY)
[email protected]24db0262010-08-03 03:06:21493 task = deferred_non_nestable_work_queue_.front().task;
494#elif defined(OS_POSIX)
495 if (RUNNING_ON_VALGRIND)
496 task = deferred_non_nestable_work_queue_.front().task;
497#endif
[email protected]8df21d32009-03-11 19:53:50498 deferred_non_nestable_work_queue_.pop();
[email protected]24db0262010-08-03 03:06:21499 if (task)
500 delete task;
initial.commitd7cae122008-07-26 21:49:38501 }
[email protected]001747c2008-09-10 00:37:07502 did_work |= !delayed_work_queue_.empty();
503 while (!delayed_work_queue_.empty()) {
[email protected]24db0262010-08-03 03:06:21504 Task* task = delayed_work_queue_.top().task;
[email protected]001747c2008-09-10 00:37:07505 delayed_work_queue_.pop();
[email protected]24db0262010-08-03 03:06:21506 delete task;
[email protected]001747c2008-09-10 00:37:07507 }
508 return did_work;
initial.commitd7cae122008-07-26 21:49:38509}
510
[email protected]fc7fb6e2008-08-16 03:09:05511bool MessageLoop::DoWork() {
[email protected]752578562008-09-07 08:08:29512 if (!nestable_tasks_allowed_) {
513 // Task can't be executed right now.
514 return false;
515 }
516
517 for (;;) {
518 ReloadWorkQueue();
519 if (work_queue_.empty())
520 break;
521
522 // Execute oldest task.
523 do {
524 PendingTask pending_task = work_queue_.front();
525 work_queue_.pop();
526 if (!pending_task.delayed_run_time.is_null()) {
[email protected]001747c2008-09-10 00:37:07527 AddToDelayedWorkQueue(pending_task);
[email protected]72deacd2008-09-23 19:19:20528 // If we changed the topmost task, then it is time to re-schedule.
[email protected]11f76c72010-10-21 06:32:33529 if (delayed_work_queue_.top().task == pending_task.task)
[email protected]752578562008-09-07 08:08:29530 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
531 } else {
532 if (DeferOrRunPendingTask(pending_task))
533 return true;
534 }
535 } while (!work_queue_.empty());
536 }
537
538 // Nothing happened.
539 return false;
[email protected]fc7fb6e2008-08-16 03:09:05540}
541
[email protected]71ad9c6f2010-10-22 16:17:47542bool MessageLoop::DoDelayedWork(base::Time* next_delayed_work_time) {
[email protected]11f76c72010-10-21 06:32:33543 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
[email protected]71ad9c6f2010-10-22 16:17:47544 *next_delayed_work_time = base::Time();
[email protected]752578562008-09-07 08:08:29545 return false;
546 }
[email protected]1d2eb132008-12-08 17:36:06547
[email protected]11f76c72010-10-21 06:32:33548 if (delayed_work_queue_.top().delayed_run_time > Time::Now()) {
549 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
550 return false;
[email protected]752578562008-09-07 08:08:29551 }
[email protected]fc7fb6e2008-08-16 03:09:05552
[email protected]11f76c72010-10-21 06:32:33553 PendingTask pending_task = delayed_work_queue_.top();
554 delayed_work_queue_.pop();
[email protected]1d2eb132008-12-08 17:36:06555
[email protected]11f76c72010-10-21 06:32:33556 if (!delayed_work_queue_.empty())
[email protected]752578562008-09-07 08:08:29557 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
[email protected]fc7fb6e2008-08-16 03:09:05558
[email protected]752578562008-09-07 08:08:29559 return DeferOrRunPendingTask(pending_task);
[email protected]fc7fb6e2008-08-16 03:09:05560}
561
562bool MessageLoop::DoIdleWork() {
563 if (ProcessNextDelayedNonNestableTask())
564 return true;
565
566 if (state_->quit_received)
567 pump_->Quit();
568
569 return false;
570}
571
572//------------------------------------------------------------------------------
573// MessageLoop::AutoRunState
574
575MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
576 // Make the loop reference us.
577 previous_state_ = loop_->state_;
578 if (previous_state_) {
579 run_depth = previous_state_->run_depth + 1;
[email protected]ea15e982008-08-15 07:31:20580 } else {
[email protected]fc7fb6e2008-08-16 03:09:05581 run_depth = 1;
[email protected]ea15e982008-08-15 07:31:20582 }
[email protected]fc7fb6e2008-08-16 03:09:05583 loop_->state_ = this;
584
585 // Initialize the other fields:
586 quit_received = false;
[email protected]e43eddf12009-12-29 00:32:52587#if !defined(OS_MACOSX)
[email protected]fc7fb6e2008-08-16 03:09:05588 dispatcher = NULL;
589#endif
590}
591
592MessageLoop::AutoRunState::~AutoRunState() {
593 loop_->state_ = previous_state_;
[email protected]a5b94a92008-08-12 23:25:43594}
595
initial.commitd7cae122008-07-26 21:49:38596//------------------------------------------------------------------------------
[email protected]752578562008-09-07 08:08:29597// MessageLoop::PendingTask
initial.commitd7cae122008-07-26 21:49:38598
[email protected]752578562008-09-07 08:08:29599bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
600 // Since the top of a priority queue is defined as the "greatest" element, we
601 // need to invert the comparison here. We want the smaller time to be at the
602 // top of the heap.
initial.commitd7cae122008-07-26 21:49:38603
[email protected]752578562008-09-07 08:08:29604 if (delayed_run_time < other.delayed_run_time)
605 return false;
initial.commitd7cae122008-07-26 21:49:38606
[email protected]752578562008-09-07 08:08:29607 if (delayed_run_time > other.delayed_run_time)
608 return true;
initial.commitd7cae122008-07-26 21:49:38609
[email protected]752578562008-09-07 08:08:29610 // If the times happen to match, then we use the sequence number to decide.
611 // Compare the difference to support integer roll-over.
612 return (sequence_num - other.sequence_num) > 0;
initial.commitd7cae122008-07-26 21:49:38613}
614
615//------------------------------------------------------------------------------
616// Method and data for histogramming events and actions taken by each instance
617// on each thread.
618
619// static
initial.commitd7cae122008-07-26 21:49:38620void MessageLoop::EnableHistogrammer(bool enable) {
621 enable_histogrammer_ = enable;
622}
623
624void MessageLoop::StartHistogrammer() {
625 if (enable_histogrammer_ && !message_histogram_.get()
[email protected]835d7c82010-10-14 04:38:38626 && base::StatisticsRecorder::WasStarted()) {
[email protected]fc7fb6e2008-08-16 03:09:05627 DCHECK(!thread_name_.empty());
[email protected]835d7c82010-10-14 04:38:38628 message_histogram_ = base::LinearHistogram::FactoryGet(
629 "MsgLoop:" + thread_name_,
[email protected]2753b392009-12-28 06:59:52630 kLeastNonZeroMessageId, kMaxMessageId,
631 kNumberOfDistinctMessagesDisplayed,
632 message_histogram_->kHexRangePrintingFlag);
initial.commitd7cae122008-07-26 21:49:38633 message_histogram_->SetRangeDescriptions(event_descriptions_);
634 }
635}
636
637void MessageLoop::HistogramEvent(int event) {
638 if (message_histogram_.get())
639 message_histogram_->Add(event);
640}
641
[email protected]4d9bdfaf2008-08-26 05:53:57642//------------------------------------------------------------------------------
643// MessageLoopForUI
644
645#if defined(OS_WIN)
[email protected]4d9bdfaf2008-08-26 05:53:57646void MessageLoopForUI::DidProcessMessage(const MSG& message) {
647 pump_win()->DidProcessMessage(message);
648}
[email protected]4d9bdfaf2008-08-26 05:53:57649#endif // defined(OS_WIN)
650
[email protected]e43eddf12009-12-29 00:32:52651#if !defined(OS_MACOSX)
[email protected]148d1052009-07-31 22:53:37652void MessageLoopForUI::AddObserver(Observer* observer) {
653 pump_ui()->AddObserver(observer);
654}
655
656void MessageLoopForUI::RemoveObserver(Observer* observer) {
657 pump_ui()->RemoveObserver(observer);
658}
659
660void MessageLoopForUI::Run(Dispatcher* dispatcher) {
661 AutoRunState save_state(this);
662 state_->dispatcher = dispatcher;
663 RunHandler();
664}
[email protected]e43eddf12009-12-29 00:32:52665#endif // !defined(OS_MACOSX)
[email protected]148d1052009-07-31 22:53:37666
[email protected]4d9bdfaf2008-08-26 05:53:57667//------------------------------------------------------------------------------
668// MessageLoopForIO
669
670#if defined(OS_WIN)
671
[email protected]32cda29d2008-10-09 23:58:43672void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
673 pump_io()->RegisterIOHandler(file, handler);
674}
675
[email protected]17b89142008-11-07 21:52:15676bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
677 return pump_io()->WaitForIOCompletion(timeout, filter);
[email protected]32cda29d2008-10-09 23:58:43678}
679
[email protected]36987e92008-09-18 18:46:26680#elif defined(OS_POSIX)
681
[email protected]e45e6c02008-12-15 22:02:17682bool MessageLoopForIO::WatchFileDescriptor(int fd,
683 bool persistent,
684 Mode mode,
685 FileDescriptorWatcher *controller,
686 Watcher *delegate) {
687 return pump_libevent()->WatchFileDescriptor(
688 fd,
689 persistent,
690 static_cast<base::MessagePumpLibevent::Mode>(mode),
691 controller,
692 delegate);
[email protected]36987e92008-09-18 18:46:26693}
694
[email protected]36987e92008-09-18 18:46:26695#endif