blob: d83adccec08b56f8cdeb991c1b06af60d7a877e0 [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"
timurrrr@chromium.org490200b2011-01-05 04:06:51 +090014#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
brettw@chromium.org63965582010-12-31 07:18:56 +090015#include "base/threading/thread_local.h"
initial.commit3f4a7322008-07-27 06:49:38 +090016
mark@chromium.org059d0492008-09-24 06:08:28 +090017#if defined(OS_MACOSX)
18#include "base/message_pump_mac.h"
19#endif
dkegel@google.com9e044ae2008-09-19 03:46:26 +090020#if defined(OS_POSIX)
21#include "base/message_pump_libevent.h"
22#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::TimeDelta;
jar@chromium.org9b0fb062010-11-07 07:23:29 +090031using base::TimeTicks;
dsh@google.com0f8dd262008-10-28 05:43:33 +090032
erg@chromium.orga7528522010-07-16 02:23:23 +090033namespace {
34
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090035// 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.
erg@chromium.orga7528522010-07-16 02:23:23 +090037base::LazyInstance<base::ThreadLocalPointer<MessageLoop> > lazy_tls_ptr(
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090038 base::LINKER_INITIALIZED);
initial.commit3f4a7322008-07-27 06:49:38 +090039
initial.commit3f4a7322008-07-27 06:49:38 +090040// Logical events for Histogram profiling. Run with -message-loop-histogrammer
41// to get an accounting of messages and actions taken on each thread.
erg@chromium.orga7528522010-07-16 02:23:23 +090042const int kTaskRunEvent = 0x1;
43const int kTimerEvent = 0x2;
initial.commit3f4a7322008-07-27 06:49:38 +090044
45// Provide range of message IDs for use in histogramming and debug display.
erg@chromium.orga7528522010-07-16 02:23:23 +090046const 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
brettw@chromium.org275c2ec2010-10-14 13:38:38 +090066const base::LinearHistogram::DescriptionPair event_descriptions_[] = {
erg@chromium.orga7528522010-07-16 02:23:23 +090067 // 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.commit3f4a7322008-07-27 06:49:38 +090080
81//------------------------------------------------------------------------------
82
darin@google.com981f3552008-08-16 12:09:05 +090083#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +090084
initial.commit3f4a7322008-07-27 06:49:38 +090085// 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
darin@google.com981f3552008-08-16 12:09:05 +0900101#endif // defined(OS_WIN)
102
initial.commit3f4a7322008-07-27 06:49:38 +0900103//------------------------------------------------------------------------------
104
erg@chromium.org493f5f62010-07-16 06:03:54 +0900105MessageLoop::TaskObserver::TaskObserver() {
106}
107
108MessageLoop::TaskObserver::~TaskObserver() {
109}
110
111MessageLoop::DestructionObserver::~DestructionObserver() {
112}
113
114//------------------------------------------------------------------------------
115
darin@google.comd936b5b2008-08-26 14:53:57 +0900116MessageLoop::MessageLoop(Type type)
117 : type_(type),
darin@google.comee6fa722008-08-13 08:25:43 +0900118 nestable_tasks_allowed_(true),
darin@google.com12d40bb2008-08-20 03:36:23 +0900119 exception_restoration_(false),
darin@google.combe165ae2008-09-07 17:08:29 +0900120 state_(NULL),
121 next_sequence_num_(0) {
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +0900122 DCHECK(!current()) << "should only have one message loop per thread";
123 lazy_tls_ptr.Pointer()->Set(this);
darin@google.comd936b5b2008-08-26 14:53:57 +0900124
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900125// TODO(rvargas): Get rid of the OS guards.
darin@google.com981f3552008-08-16 12:09:05 +0900126#if defined(OS_WIN)
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900127#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
128#define MESSAGE_PUMP_IO new base::MessagePumpForIO()
129#elif defined(OS_MACOSX)
130#define MESSAGE_PUMP_UI base::MessagePumpMac::Create()
131#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
rjkroege@google.com3080f442010-10-23 01:17:47 +0900132#elif defined(TOUCH_UI)
sadrul@chromium.orgcff2c642010-12-17 04:43:30 +0900133#define MESSAGE_PUMP_UI new base::MessagePumpGlibX()
rjkroege@google.com3080f442010-10-23 01:17:47 +0900134#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900135#elif defined(OS_NACL)
136// Currently NaCl doesn't have a UI or an IO MessageLoop.
137// TODO(abarth): Figure out if we need these.
138#define MESSAGE_PUMP_UI NULL
139#define MESSAGE_PUMP_IO NULL
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900140#elif defined(OS_POSIX) // POSIX but not MACOSX.
141#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
142#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900143#else
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900144#error Not implemented
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900145#endif
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900146
147 if (type_ == TYPE_UI) {
148 pump_ = MESSAGE_PUMP_UI;
dsh@google.com119a2522008-10-04 01:52:59 +0900149 } else if (type_ == TYPE_IO) {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900150 pump_ = MESSAGE_PUMP_IO;
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900151 } else {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900152 DCHECK_EQ(TYPE_DEFAULT, type_);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900153 pump_ = new base::MessagePumpDefault();
154 }
initial.commit3f4a7322008-07-27 06:49:38 +0900155}
156
157MessageLoop::~MessageLoop() {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900158 DCHECK_EQ(this, current());
darin@google.com965e5342008-08-06 08:16:41 +0900159
darin@google.com0e500502008-09-09 14:55:35 +0900160 DCHECK(!state_);
161
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900162 // Clean up any unprocessed tasks, but take care: deleting a task could
163 // result in the addition of more tasks (e.g., via DeleteSoon). We set a
164 // limit on the number of times we will allow a deleted task to generate more
165 // tasks. Normally, we should only pass through this loop once or twice. If
166 // we end up hitting the loop limit, then it is probably due to one task that
167 // is being stubborn. Inspect the queues to see who is left.
168 bool did_work;
169 for (int i = 0; i < 100; ++i) {
170 DeletePendingTasks();
171 ReloadWorkQueue();
172 // If we end up with empty queues, then break out of the loop.
173 did_work = DeletePendingTasks();
174 if (!did_work)
175 break;
darin@google.com0e500502008-09-09 14:55:35 +0900176 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900177 DCHECK(!did_work);
178
sanjeevr@chromium.org03b44d52010-11-30 09:25:29 +0900179 // Let interested parties have one last shot at accessing this.
180 FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
181 WillDestroyCurrentMessageLoop());
182
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900183 // OK, now make it so that no one can find us.
deanm@chromium.orge4cc5922008-09-10 20:14:56 +0900184 lazy_tls_ptr.Pointer()->Set(NULL);
initial.commit3f4a7322008-07-27 06:49:38 +0900185}
186
erg@google.com67a25432011-01-08 05:23:43 +0900187// static
188MessageLoop* MessageLoop::current() {
189 // TODO(darin): sadly, we cannot enable this yet since people call us even
190 // when they have no intention of using us.
191 // DCHECK(loop) << "Ouch, did you forget to initialize me?";
192 return lazy_tls_ptr.Pointer()->Get();
193}
194
195// static
196void MessageLoop::EnableHistogrammer(bool enable) {
197 enable_histogrammer_ = enable;
198}
199
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900200void MessageLoop::AddDestructionObserver(
201 DestructionObserver* destruction_observer) {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900202 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900203 destruction_observers_.AddObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900204}
205
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900206void MessageLoop::RemoveDestructionObserver(
207 DestructionObserver* destruction_observer) {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900208 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900209 destruction_observers_.RemoveObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900210}
211
darin@google.combe165ae2008-09-07 17:08:29 +0900212void MessageLoop::PostTask(
213 const tracked_objects::Location& from_here, Task* task) {
214 PostTask_Helper(from_here, task, 0, true);
215}
216
217void MessageLoop::PostDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900218 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
darin@google.combe165ae2008-09-07 17:08:29 +0900219 PostTask_Helper(from_here, task, delay_ms, true);
220}
221
222void MessageLoop::PostNonNestableTask(
223 const tracked_objects::Location& from_here, Task* task) {
224 PostTask_Helper(from_here, task, 0, false);
225}
226
227void MessageLoop::PostNonNestableDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900228 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
darin@google.combe165ae2008-09-07 17:08:29 +0900229 PostTask_Helper(from_here, task, delay_ms, false);
230}
231
erg@google.com67a25432011-01-08 05:23:43 +0900232void MessageLoop::Run() {
233 AutoRunState save_state(this);
234 RunHandler();
235}
darin@google.com0795f572008-08-30 09:22:48 +0900236
erg@google.com67a25432011-01-08 05:23:43 +0900237void MessageLoop::RunAllPending() {
238 AutoRunState save_state(this);
239 state_->quit_received = true; // Means run until we would otherwise block.
240 RunHandler();
241}
darin@google.com0795f572008-08-30 09:22:48 +0900242
erg@google.com67a25432011-01-08 05:23:43 +0900243void MessageLoop::Quit() {
244 DCHECK_EQ(this, current());
245 if (state_) {
246 state_->quit_received = true;
darin@google.com0795f572008-08-30 09:22:48 +0900247 } else {
erg@google.com67a25432011-01-08 05:23:43 +0900248 NOTREACHED() << "Must be inside Run to call Quit";
darin@google.com0795f572008-08-30 09:22:48 +0900249 }
erg@google.com67a25432011-01-08 05:23:43 +0900250}
darin@google.com0795f572008-08-30 09:22:48 +0900251
erg@google.com67a25432011-01-08 05:23:43 +0900252void MessageLoop::QuitNow() {
253 DCHECK_EQ(this, current());
254 if (state_) {
255 pump_->Quit();
256 } else {
257 NOTREACHED() << "Must be inside Run to call Quit";
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900258 }
initial.commit3f4a7322008-07-27 06:49:38 +0900259}
260
261void MessageLoop::SetNestableTasksAllowed(bool allowed) {
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900262 if (nestable_tasks_allowed_ != allowed) {
263 nestable_tasks_allowed_ = allowed;
264 if (!nestable_tasks_allowed_)
265 return;
266 // Start the native pump if we are not already pumping.
darin@google.com981f3552008-08-16 12:09:05 +0900267 pump_->ScheduleWork();
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900268 }
initial.commit3f4a7322008-07-27 06:49:38 +0900269}
270
271bool MessageLoop::NestableTasksAllowed() const {
272 return nestable_tasks_allowed_;
273}
274
jcampan@chromium.orgeac57172009-07-02 04:53:59 +0900275bool MessageLoop::IsNested() {
276 return state_->run_depth > 1;
277}
278
erg@google.com67a25432011-01-08 05:23:43 +0900279void MessageLoop::AddTaskObserver(TaskObserver* task_observer) {
280 DCHECK_EQ(this, current());
281 task_observers_.AddObserver(task_observer);
282}
283
284void MessageLoop::RemoveTaskObserver(TaskObserver* task_observer) {
285 DCHECK_EQ(this, current());
286 task_observers_.RemoveObserver(task_observer);
287}
288
willchan@chromium.org3a397672011-01-26 09:53:48 +0900289void MessageLoop::AssertIdle() const {
290 // We only check |incoming_queue_|, since we don't want to lock |work_queue_|.
291 base::AutoLock lock(incoming_queue_lock_);
292 DCHECK(incoming_queue_.empty());
293}
294
initial.commit3f4a7322008-07-27 06:49:38 +0900295//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900296
erg@google.com67a25432011-01-08 05:23:43 +0900297// Runs the loop in two different SEH modes:
298// enable_SEH_restoration_ = false : any unhandled exception goes to the last
299// one that calls SetUnhandledExceptionFilter().
300// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
301// that was existed before the loop was run.
302void MessageLoop::RunHandler() {
303#if defined(OS_WIN)
304 if (exception_restoration_) {
305 RunInternalInSEHFrame();
306 return;
307 }
308#endif
309
310 RunInternal();
311}
312
313#if defined(OS_WIN)
314__declspec(noinline) void MessageLoop::RunInternalInSEHFrame() {
315 LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
316 __try {
317 RunInternal();
318 } __except(SEHFilter(current_filter)) {
319 }
320 return;
321}
322#endif
323
324void MessageLoop::RunInternal() {
325 DCHECK_EQ(this, current());
326
327 StartHistogrammer();
328
329#if !defined(OS_MACOSX)
330 if (state_->dispatcher && type() == TYPE_UI) {
331 static_cast<base::MessagePumpForUI*>(pump_.get())->
332 RunWithDispatcher(this, state_->dispatcher);
333 return;
334 }
335#endif
336
337 pump_->Run(this);
338}
339
340bool MessageLoop::ProcessNextDelayedNonNestableTask() {
341 if (state_->run_depth != 1)
342 return false;
343
344 if (deferred_non_nestable_work_queue_.empty())
345 return false;
346
347 Task* task = deferred_non_nestable_work_queue_.front().task;
348 deferred_non_nestable_work_queue_.pop();
349
350 RunTask(task);
351 return true;
352}
353
initial.commit3f4a7322008-07-27 06:49:38 +0900354void MessageLoop::RunTask(Task* task) {
initial.commit3f4a7322008-07-27 06:49:38 +0900355 DCHECK(nestable_tasks_allowed_);
356 // Execute the task and assume the worst: It is probably not reentrant.
357 nestable_tasks_allowed_ = false;
darin@google.combe165ae2008-09-07 17:08:29 +0900358
359 HistogramEvent(kTaskRunEvent);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900360 FOR_EACH_OBSERVER(TaskObserver, task_observers_,
davemoore@chromium.orgeb5f68f2010-10-27 08:40:48 +0900361 WillProcessTask(task));
darin@google.combe165ae2008-09-07 17:08:29 +0900362 task->Run();
davemoore@chromium.orgeb5f68f2010-10-27 08:40:48 +0900363 FOR_EACH_OBSERVER(TaskObserver, task_observers_, DidProcessTask(task));
darin@google.combe165ae2008-09-07 17:08:29 +0900364 delete task;
365
366 nestable_tasks_allowed_ = true;
initial.commit3f4a7322008-07-27 06:49:38 +0900367}
368
darin@google.combe165ae2008-09-07 17:08:29 +0900369bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) {
370 if (pending_task.nestable || state_->run_depth == 1) {
371 RunTask(pending_task.task);
372 // Show that we ran a task (Note: a new one might arrive as a
373 // consequence!).
374 return true;
375 }
376
377 // We couldn't run the task now because we're in a nested message loop
378 // and the task isn't nestable.
379 deferred_non_nestable_work_queue_.push(pending_task);
380 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900381}
382
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900383void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
384 // Move to the delayed work queue. Initialize the sequence number
385 // before inserting into the delayed_work_queue_. The sequence number
386 // is used to faciliate FIFO sorting when two tasks have the same
387 // delayed_run_time value.
388 PendingTask new_pending_task(pending_task);
389 new_pending_task.sequence_num = next_sequence_num_++;
390 delayed_work_queue_.push(new_pending_task);
391}
392
initial.commit3f4a7322008-07-27 06:49:38 +0900393void MessageLoop::ReloadWorkQueue() {
394 // We can improve performance of our loading tasks from incoming_queue_ to
darin@google.com981f3552008-08-16 12:09:05 +0900395 // work_queue_ by waiting until the last minute (work_queue_ is empty) to
396 // load. That reduces the number of locks-per-task significantly when our
darin@google.combe165ae2008-09-07 17:08:29 +0900397 // queues get large.
398 if (!work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900399 return; // Wait till we *really* need to lock and load.
400
401 // Acquire all we can from the inter-thread queue with one lock acquisition.
initial.commit3f4a7322008-07-27 06:49:38 +0900402 {
brettw@chromium.orgabe477a2011-01-21 13:55:52 +0900403 base::AutoLock lock(incoming_queue_lock_);
darin@google.combe165ae2008-09-07 17:08:29 +0900404 if (incoming_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900405 return;
darin@chromium.orgb80ef1a2009-09-03 05:05:21 +0900406 incoming_queue_.Swap(&work_queue_); // Constant time
darin@google.combe165ae2008-09-07 17:08:29 +0900407 DCHECK(incoming_queue_.empty());
initial.commit3f4a7322008-07-27 06:49:38 +0900408 }
409}
410
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900411bool MessageLoop::DeletePendingTasks() {
412 bool did_work = !work_queue_.empty();
413 while (!work_queue_.empty()) {
414 PendingTask pending_task = work_queue_.front();
415 work_queue_.pop();
416 if (!pending_task.delayed_run_time.is_null()) {
417 // We want to delete delayed tasks in the same order in which they would
418 // normally be deleted in case of any funny dependencies between delayed
419 // tasks.
420 AddToDelayedWorkQueue(pending_task);
421 } else {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900422 // TODO(darin): Delete all tasks once it is safe to do so.
423 // Until it is totally safe, just do it when running Purify or
424 // Valgrind.
thestig@chromium.orgddb849c2010-10-28 05:03:42 +0900425#if defined(PURIFY) || defined(USE_HEAPCHECKER)
jar@chromium.org63772352009-03-12 05:06:02 +0900426 delete pending_task.task;
timurrrr@chromium.org490200b2011-01-05 04:06:51 +0900427#else
428 if (RunningOnValgrind())
akalin@chromium.org839060b2010-08-03 12:06:21 +0900429 delete pending_task.task;
430#endif // defined(OS_POSIX)
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900431 }
initial.commit3f4a7322008-07-27 06:49:38 +0900432 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900433 did_work |= !deferred_non_nestable_work_queue_.empty();
434 while (!deferred_non_nestable_work_queue_.empty()) {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900435 // TODO(darin): Delete all tasks once it is safe to do so.
436 // Until it is totaly safe, only delete them under Purify and Valgrind.
437 Task* task = NULL;
thestig@chromium.orgddb849c2010-10-28 05:03:42 +0900438#if defined(PURIFY) || defined(USE_HEAPCHECKER)
akalin@chromium.org839060b2010-08-03 12:06:21 +0900439 task = deferred_non_nestable_work_queue_.front().task;
timurrrr@chromium.org490200b2011-01-05 04:06:51 +0900440#else
441 if (RunningOnValgrind())
akalin@chromium.org839060b2010-08-03 12:06:21 +0900442 task = deferred_non_nestable_work_queue_.front().task;
443#endif
jar@chromium.org2fa6b4b2009-03-12 04:53:50 +0900444 deferred_non_nestable_work_queue_.pop();
akalin@chromium.org839060b2010-08-03 12:06:21 +0900445 if (task)
446 delete task;
initial.commit3f4a7322008-07-27 06:49:38 +0900447 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900448 did_work |= !delayed_work_queue_.empty();
449 while (!delayed_work_queue_.empty()) {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900450 Task* task = delayed_work_queue_.top().task;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900451 delayed_work_queue_.pop();
akalin@chromium.org839060b2010-08-03 12:06:21 +0900452 delete task;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900453 }
454 return did_work;
initial.commit3f4a7322008-07-27 06:49:38 +0900455}
456
erg@google.com67a25432011-01-08 05:23:43 +0900457// Possibly called on a background thread!
458void MessageLoop::PostTask_Helper(
459 const tracked_objects::Location& from_here, Task* task, int64 delay_ms,
460 bool nestable) {
461 task->SetBirthPlace(from_here);
462
463 PendingTask pending_task(task, nestable);
464
465 if (delay_ms > 0) {
466 pending_task.delayed_run_time =
467 TimeTicks::Now() + TimeDelta::FromMilliseconds(delay_ms);
468
469#if defined(OS_WIN)
470 if (high_resolution_timer_expiration_.is_null()) {
471 // Windows timers are granular to 15.6ms. If we only set high-res
472 // timers for those under 15.6ms, then a 18ms timer ticks at ~32ms,
473 // which as a percentage is pretty inaccurate. So enable high
474 // res timers for any timer which is within 2x of the granularity.
475 // This is a tradeoff between accuracy and power management.
476 bool needs_high_res_timers =
477 delay_ms < (2 * base::Time::kMinLowResolutionThresholdMs);
478 if (needs_high_res_timers) {
479 base::Time::ActivateHighResolutionTimer(true);
480 high_resolution_timer_expiration_ = TimeTicks::Now() +
481 TimeDelta::FromMilliseconds(kHighResolutionTimerModeLeaseTimeMs);
482 }
483 }
484#endif
485 } else {
486 DCHECK_EQ(delay_ms, 0) << "delay should not be negative";
487 }
488
489#if defined(OS_WIN)
490 if (!high_resolution_timer_expiration_.is_null()) {
491 if (TimeTicks::Now() > high_resolution_timer_expiration_) {
492 base::Time::ActivateHighResolutionTimer(false);
493 high_resolution_timer_expiration_ = TimeTicks();
494 }
495 }
496#endif
497
498 // Warning: Don't try to short-circuit, and handle this thread's tasks more
499 // directly, as it could starve handling of foreign threads. Put every task
500 // into this queue.
501
502 scoped_refptr<base::MessagePump> pump;
503 {
brettw@chromium.orgabe477a2011-01-21 13:55:52 +0900504 base::AutoLock locked(incoming_queue_lock_);
erg@google.com67a25432011-01-08 05:23:43 +0900505
506 bool was_empty = incoming_queue_.empty();
507 incoming_queue_.push(pending_task);
508 if (!was_empty)
509 return; // Someone else should have started the sub-pump.
510
511 pump = pump_;
512 }
513 // Since the incoming_queue_ may contain a task that destroys this message
514 // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
515 // We use a stack-based reference to the message pump so that we can call
516 // ScheduleWork outside of incoming_queue_lock_.
517
518 pump->ScheduleWork();
519}
520
521//------------------------------------------------------------------------------
522// Method and data for histogramming events and actions taken by each instance
523// on each thread.
524
525void MessageLoop::StartHistogrammer() {
526 if (enable_histogrammer_ && !message_histogram_.get()
527 && base::StatisticsRecorder::IsActive()) {
528 DCHECK(!thread_name_.empty());
529 message_histogram_ = base::LinearHistogram::FactoryGet(
530 "MsgLoop:" + thread_name_,
531 kLeastNonZeroMessageId, kMaxMessageId,
532 kNumberOfDistinctMessagesDisplayed,
533 message_histogram_->kHexRangePrintingFlag);
534 message_histogram_->SetRangeDescriptions(event_descriptions_);
535 }
536}
537
538void MessageLoop::HistogramEvent(int event) {
539 if (message_histogram_.get())
540 message_histogram_->Add(event);
541}
542
darin@google.com981f3552008-08-16 12:09:05 +0900543bool MessageLoop::DoWork() {
darin@google.combe165ae2008-09-07 17:08:29 +0900544 if (!nestable_tasks_allowed_) {
545 // Task can't be executed right now.
546 return false;
547 }
548
549 for (;;) {
550 ReloadWorkQueue();
551 if (work_queue_.empty())
552 break;
553
554 // Execute oldest task.
555 do {
556 PendingTask pending_task = work_queue_.front();
557 work_queue_.pop();
558 if (!pending_task.delayed_run_time.is_null()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900559 AddToDelayedWorkQueue(pending_task);
darin@chromium.orgb2d33452008-09-24 04:19:20 +0900560 // If we changed the topmost task, then it is time to re-schedule.
jar@chromium.org40355072010-10-21 15:32:33 +0900561 if (delayed_work_queue_.top().task == pending_task.task)
darin@google.combe165ae2008-09-07 17:08:29 +0900562 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
563 } else {
564 if (DeferOrRunPendingTask(pending_task))
565 return true;
566 }
567 } while (!work_queue_.empty());
568 }
569
570 // Nothing happened.
571 return false;
darin@google.com981f3552008-08-16 12:09:05 +0900572}
573
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900574bool MessageLoop::DoDelayedWork(base::TimeTicks* next_delayed_work_time) {
jar@chromium.org40355072010-10-21 15:32:33 +0900575 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900576 recent_time_ = *next_delayed_work_time = TimeTicks();
darin@google.combe165ae2008-09-07 17:08:29 +0900577 return false;
578 }
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900579
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900580 // When we "fall behind," there will be a lot of tasks in the delayed work
jar@chromium.org94f73832010-11-05 08:23:42 +0900581 // queue that are ready to run. To increase efficiency when we fall behind,
582 // we will only call Time::Now() intermittently, and then process all tasks
583 // that are ready to run before calling it again. As a result, the more we
584 // fall behind (and have a lot of ready-to-run delayed tasks), the more
585 // efficient we'll be at handling the tasks.
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900586
587 TimeTicks next_run_time = delayed_work_queue_.top().delayed_run_time;
jar@chromium.org94f73832010-11-05 08:23:42 +0900588 if (next_run_time > recent_time_) {
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900589 recent_time_ = TimeTicks::Now(); // Get a better view of Now();
jar@chromium.org94f73832010-11-05 08:23:42 +0900590 if (next_run_time > recent_time_) {
591 *next_delayed_work_time = next_run_time;
592 return false;
593 }
darin@google.combe165ae2008-09-07 17:08:29 +0900594 }
darin@google.com981f3552008-08-16 12:09:05 +0900595
jar@chromium.org40355072010-10-21 15:32:33 +0900596 PendingTask pending_task = delayed_work_queue_.top();
597 delayed_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900598
jar@chromium.org40355072010-10-21 15:32:33 +0900599 if (!delayed_work_queue_.empty())
darin@google.combe165ae2008-09-07 17:08:29 +0900600 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
darin@google.com981f3552008-08-16 12:09:05 +0900601
darin@google.combe165ae2008-09-07 17:08:29 +0900602 return DeferOrRunPendingTask(pending_task);
darin@google.com981f3552008-08-16 12:09:05 +0900603}
604
605bool MessageLoop::DoIdleWork() {
606 if (ProcessNextDelayedNonNestableTask())
607 return true;
608
609 if (state_->quit_received)
610 pump_->Quit();
611
612 return false;
613}
614
615//------------------------------------------------------------------------------
616// MessageLoop::AutoRunState
617
618MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
619 // Make the loop reference us.
620 previous_state_ = loop_->state_;
621 if (previous_state_) {
622 run_depth = previous_state_->run_depth + 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900623 } else {
darin@google.com981f3552008-08-16 12:09:05 +0900624 run_depth = 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900625 }
darin@google.com981f3552008-08-16 12:09:05 +0900626 loop_->state_ = this;
627
628 // Initialize the other fields:
629 quit_received = false;
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900630#if !defined(OS_MACOSX)
darin@google.com981f3552008-08-16 12:09:05 +0900631 dispatcher = NULL;
632#endif
633}
634
635MessageLoop::AutoRunState::~AutoRunState() {
636 loop_->state_ = previous_state_;
darin@google.comee6fa722008-08-13 08:25:43 +0900637}
638
initial.commit3f4a7322008-07-27 06:49:38 +0900639//------------------------------------------------------------------------------
darin@google.combe165ae2008-09-07 17:08:29 +0900640// MessageLoop::PendingTask
initial.commit3f4a7322008-07-27 06:49:38 +0900641
darin@google.combe165ae2008-09-07 17:08:29 +0900642bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
643 // Since the top of a priority queue is defined as the "greatest" element, we
644 // need to invert the comparison here. We want the smaller time to be at the
645 // top of the heap.
initial.commit3f4a7322008-07-27 06:49:38 +0900646
darin@google.combe165ae2008-09-07 17:08:29 +0900647 if (delayed_run_time < other.delayed_run_time)
648 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900649
darin@google.combe165ae2008-09-07 17:08:29 +0900650 if (delayed_run_time > other.delayed_run_time)
651 return true;
initial.commit3f4a7322008-07-27 06:49:38 +0900652
darin@google.combe165ae2008-09-07 17:08:29 +0900653 // If the times happen to match, then we use the sequence number to decide.
654 // Compare the difference to support integer roll-over.
655 return (sequence_num - other.sequence_num) > 0;
initial.commit3f4a7322008-07-27 06:49:38 +0900656}
657
658//------------------------------------------------------------------------------
darin@google.comd936b5b2008-08-26 14:53:57 +0900659// MessageLoopForUI
660
661#if defined(OS_WIN)
darin@google.comd936b5b2008-08-26 14:53:57 +0900662void MessageLoopForUI::DidProcessMessage(const MSG& message) {
663 pump_win()->DidProcessMessage(message);
664}
darin@google.comd936b5b2008-08-26 14:53:57 +0900665#endif // defined(OS_WIN)
666
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900667#if !defined(OS_MACOSX) && !defined(OS_NACL)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900668void 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}
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900681#endif // !defined(OS_MACOSX) && !defined(OS_NACL)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900682
darin@google.comd936b5b2008-08-26 14:53:57 +0900683//------------------------------------------------------------------------------
684// MessageLoopForIO
685
686#if defined(OS_WIN)
687
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900688void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
689 pump_io()->RegisterIOHandler(file, handler);
690}
691
rvargas@google.com73887542008-11-08 06:52:15 +0900692bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
693 return pump_io()->WaitForIOCompletion(timeout, filter);
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900694}
695
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900696#elif defined(OS_POSIX) && !defined(OS_NACL)
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900697
jeremy@chromium.orgefc0db02008-12-16 07:02:17 +0900698bool 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);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900709}
710
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900711#endif