blob: 39881d172957b124b41d5566297f8afa46207c4a [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
ajwong@chromium.org440e0762011-02-19 09:32:44 +09007#if defined(OS_POSIX) && !defined(OS_MACOSX)
8#include <gdk/gdk.h>
9#include <gdk/gdkx.h>
10#endif
11
darin@google.com981f3552008-08-16 12:09:05 +090012#include <algorithm>
13
mmentovai@google.comfa5f9932008-08-22 07:26:06 +090014#include "base/compiler_specific.h"
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090015#include "base/lazy_instance.h"
initial.commit3f4a7322008-07-27 06:49:38 +090016#include "base/logging.h"
darin@google.com12d40bb2008-08-20 03:36:23 +090017#include "base/message_pump_default.h"
brettw@chromium.org275c2ec2010-10-14 13:38:38 +090018#include "base/metrics/histogram.h"
timurrrr@chromium.org490200b2011-01-05 04:06:51 +090019#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
brettw@chromium.org63965582010-12-31 07:18:56 +090020#include "base/threading/thread_local.h"
initial.commit3f4a7322008-07-27 06:49:38 +090021
mark@chromium.org059d0492008-09-24 06:08:28 +090022#if defined(OS_MACOSX)
23#include "base/message_pump_mac.h"
24#endif
dkegel@google.com9e044ae2008-09-19 03:46:26 +090025#if defined(OS_POSIX)
26#include "base/message_pump_libevent.h"
27#endif
evan@chromium.org875bb6e2009-12-29 09:32:52 +090028#if defined(OS_POSIX) && !defined(OS_MACOSX)
dsh@google.com119a2522008-10-04 01:52:59 +090029#include "base/message_pump_glib.h"
30#endif
rjkroege@google.com3080f442010-10-23 01:17:47 +090031#if defined(TOUCH_UI)
32#include "base/message_pump_glib_x.h"
33#endif
dkegel@google.com9e044ae2008-09-19 03:46:26 +090034
dsh@google.com0f8dd262008-10-28 05:43:33 +090035using base::TimeDelta;
jar@chromium.org9b0fb062010-11-07 07:23:29 +090036using base::TimeTicks;
dsh@google.com0f8dd262008-10-28 05:43:33 +090037
erg@chromium.orga7528522010-07-16 02:23:23 +090038namespace {
39
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090040// A lazily created thread local storage for quick access to a thread's message
41// loop, if one exists. This should be safe and free of static constructors.
erg@chromium.orga7528522010-07-16 02:23:23 +090042base::LazyInstance<base::ThreadLocalPointer<MessageLoop> > lazy_tls_ptr(
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090043 base::LINKER_INITIALIZED);
initial.commit3f4a7322008-07-27 06:49:38 +090044
initial.commit3f4a7322008-07-27 06:49:38 +090045// Logical events for Histogram profiling. Run with -message-loop-histogrammer
46// to get an accounting of messages and actions taken on each thread.
erg@chromium.orga7528522010-07-16 02:23:23 +090047const int kTaskRunEvent = 0x1;
48const int kTimerEvent = 0x2;
initial.commit3f4a7322008-07-27 06:49:38 +090049
50// Provide range of message IDs for use in histogramming and debug display.
erg@chromium.orga7528522010-07-16 02:23:23 +090051const int kLeastNonZeroMessageId = 1;
52const int kMaxMessageId = 1099;
53const int kNumberOfDistinctMessagesDisplayed = 1100;
54
55// Provide a macro that takes an expression (such as a constant, or macro
56// constant) and creates a pair to initalize an array of pairs. In this case,
57// our pair consists of the expressions value, and the "stringized" version
58// of the expression (i.e., the exrpression put in quotes). For example, if
59// we have:
60// #define FOO 2
61// #define BAR 5
62// then the following:
63// VALUE_TO_NUMBER_AND_NAME(FOO + BAR)
64// will expand to:
65// {7, "FOO + BAR"}
66// We use the resulting array as an argument to our histogram, which reads the
67// number as a bucket identifier, and proceeds to use the corresponding name
68// in the pair (i.e., the quoted string) when printing out a histogram.
69#define VALUE_TO_NUMBER_AND_NAME(name) {name, #name},
70
brettw@chromium.org275c2ec2010-10-14 13:38:38 +090071const base::LinearHistogram::DescriptionPair event_descriptions_[] = {
erg@chromium.orga7528522010-07-16 02:23:23 +090072 // Provide some pretty print capability in our histogram for our internal
73 // messages.
74
75 // A few events we handle (kindred to messages), and used to profile actions.
76 VALUE_TO_NUMBER_AND_NAME(kTaskRunEvent)
77 VALUE_TO_NUMBER_AND_NAME(kTimerEvent)
78
79 {-1, NULL} // The list must be null terminated, per API to histogram.
80};
81
82bool enable_histogrammer_ = false;
83
84} // namespace
initial.commit3f4a7322008-07-27 06:49:38 +090085
86//------------------------------------------------------------------------------
87
darin@google.com981f3552008-08-16 12:09:05 +090088#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +090089
initial.commit3f4a7322008-07-27 06:49:38 +090090// Upon a SEH exception in this thread, it restores the original unhandled
91// exception filter.
92static int SEHFilter(LPTOP_LEVEL_EXCEPTION_FILTER old_filter) {
93 ::SetUnhandledExceptionFilter(old_filter);
94 return EXCEPTION_CONTINUE_SEARCH;
95}
96
97// Retrieves a pointer to the current unhandled exception filter. There
98// is no standalone getter method.
99static LPTOP_LEVEL_EXCEPTION_FILTER GetTopSEHFilter() {
100 LPTOP_LEVEL_EXCEPTION_FILTER top_filter = NULL;
101 top_filter = ::SetUnhandledExceptionFilter(0);
102 ::SetUnhandledExceptionFilter(top_filter);
103 return top_filter;
104}
105
darin@google.com981f3552008-08-16 12:09:05 +0900106#endif // defined(OS_WIN)
107
initial.commit3f4a7322008-07-27 06:49:38 +0900108//------------------------------------------------------------------------------
109
erg@chromium.org493f5f62010-07-16 06:03:54 +0900110MessageLoop::TaskObserver::TaskObserver() {
111}
112
113MessageLoop::TaskObserver::~TaskObserver() {
114}
115
116MessageLoop::DestructionObserver::~DestructionObserver() {
117}
118
119//------------------------------------------------------------------------------
120
darin@google.comd936b5b2008-08-26 14:53:57 +0900121MessageLoop::MessageLoop(Type type)
122 : type_(type),
darin@google.comee6fa722008-08-13 08:25:43 +0900123 nestable_tasks_allowed_(true),
darin@google.com12d40bb2008-08-20 03:36:23 +0900124 exception_restoration_(false),
darin@google.combe165ae2008-09-07 17:08:29 +0900125 state_(NULL),
ananta@chromium.orgc542fec2011-03-24 12:40:28 +0900126#ifdef OS_WIN
127 os_modal_loop_(false),
128#endif // OS_WIN
darin@google.combe165ae2008-09-07 17:08:29 +0900129 next_sequence_num_(0) {
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +0900130 DCHECK(!current()) << "should only have one message loop per thread";
131 lazy_tls_ptr.Pointer()->Set(this);
darin@google.comd936b5b2008-08-26 14:53:57 +0900132
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900133// TODO(rvargas): Get rid of the OS guards.
darin@google.com981f3552008-08-16 12:09:05 +0900134#if defined(OS_WIN)
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900135#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()
rjkroege@google.com3080f442010-10-23 01:17:47 +0900140#elif defined(TOUCH_UI)
sadrul@chromium.orgcff2c642010-12-17 04:43:30 +0900141#define MESSAGE_PUMP_UI new base::MessagePumpGlibX()
rjkroege@google.com3080f442010-10-23 01:17:47 +0900142#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900143#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
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900148#elif defined(OS_POSIX) // POSIX but not MACOSX.
149#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
150#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900151#else
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900152#error Not implemented
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900153#endif
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900154
155 if (type_ == TYPE_UI) {
156 pump_ = MESSAGE_PUMP_UI;
dsh@google.com119a2522008-10-04 01:52:59 +0900157 } else if (type_ == TYPE_IO) {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900158 pump_ = MESSAGE_PUMP_IO;
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900159 } else {
thestig@chromium.org7016bac2010-04-15 10:04:29 +0900160 DCHECK_EQ(TYPE_DEFAULT, type_);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900161 pump_ = new base::MessagePumpDefault();
162 }
initial.commit3f4a7322008-07-27 06:49:38 +0900163}
164
165MessageLoop::~MessageLoop() {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900166 DCHECK_EQ(this, current());
darin@google.com965e5342008-08-06 08:16:41 +0900167
darin@google.com0e500502008-09-09 14:55:35 +0900168 DCHECK(!state_);
169
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900170 // 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;
darin@google.com0e500502008-09-09 14:55:35 +0900184 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900185 DCHECK(!did_work);
186
sanjeevr@chromium.org03b44d52010-11-30 09:25:29 +0900187 // Let interested parties have one last shot at accessing this.
188 FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
189 WillDestroyCurrentMessageLoop());
190
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900191 // OK, now make it so that no one can find us.
deanm@chromium.orge4cc5922008-09-10 20:14:56 +0900192 lazy_tls_ptr.Pointer()->Set(NULL);
initial.commit3f4a7322008-07-27 06:49:38 +0900193}
194
erg@google.com67a25432011-01-08 05:23:43 +0900195// static
196MessageLoop* MessageLoop::current() {
197 // TODO(darin): sadly, we cannot enable this yet since people call us even
198 // when they have no intention of using us.
199 // DCHECK(loop) << "Ouch, did you forget to initialize me?";
200 return lazy_tls_ptr.Pointer()->Get();
201}
202
203// static
204void MessageLoop::EnableHistogrammer(bool enable) {
205 enable_histogrammer_ = enable;
206}
207
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900208void MessageLoop::AddDestructionObserver(
209 DestructionObserver* destruction_observer) {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900210 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900211 destruction_observers_.AddObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900212}
213
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900214void MessageLoop::RemoveDestructionObserver(
215 DestructionObserver* destruction_observer) {
thestig@chromium.org226880a2010-11-11 05:28:06 +0900216 DCHECK_EQ(this, current());
sky@chromium.org18c66dc2010-09-16 07:14:36 +0900217 destruction_observers_.RemoveObserver(destruction_observer);
darin@google.com965e5342008-08-06 08:16:41 +0900218}
219
darin@google.combe165ae2008-09-07 17:08:29 +0900220void MessageLoop::PostTask(
221 const tracked_objects::Location& from_here, Task* task) {
222 PostTask_Helper(from_here, task, 0, true);
223}
224
225void MessageLoop::PostDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900226 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
darin@google.combe165ae2008-09-07 17:08:29 +0900227 PostTask_Helper(from_here, task, delay_ms, true);
228}
229
230void MessageLoop::PostNonNestableTask(
231 const tracked_objects::Location& from_here, Task* task) {
232 PostTask_Helper(from_here, task, 0, false);
233}
234
235void MessageLoop::PostNonNestableDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900236 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
darin@google.combe165ae2008-09-07 17:08:29 +0900237 PostTask_Helper(from_here, task, delay_ms, false);
238}
239
erg@google.com67a25432011-01-08 05:23:43 +0900240void MessageLoop::Run() {
241 AutoRunState save_state(this);
242 RunHandler();
243}
darin@google.com0795f572008-08-30 09:22:48 +0900244
erg@google.com67a25432011-01-08 05:23:43 +0900245void MessageLoop::RunAllPending() {
246 AutoRunState save_state(this);
247 state_->quit_received = true; // Means run until we would otherwise block.
248 RunHandler();
249}
darin@google.com0795f572008-08-30 09:22:48 +0900250
erg@google.com67a25432011-01-08 05:23:43 +0900251void MessageLoop::Quit() {
252 DCHECK_EQ(this, current());
253 if (state_) {
254 state_->quit_received = true;
darin@google.com0795f572008-08-30 09:22:48 +0900255 } else {
erg@google.com67a25432011-01-08 05:23:43 +0900256 NOTREACHED() << "Must be inside Run to call Quit";
darin@google.com0795f572008-08-30 09:22:48 +0900257 }
erg@google.com67a25432011-01-08 05:23:43 +0900258}
darin@google.com0795f572008-08-30 09:22:48 +0900259
erg@google.com67a25432011-01-08 05:23:43 +0900260void MessageLoop::QuitNow() {
261 DCHECK_EQ(this, current());
262 if (state_) {
263 pump_->Quit();
264 } else {
265 NOTREACHED() << "Must be inside Run to call Quit";
mbelshe@chromium.orgde50b7d2010-06-29 13:58:15 +0900266 }
initial.commit3f4a7322008-07-27 06:49:38 +0900267}
268
269void MessageLoop::SetNestableTasksAllowed(bool allowed) {
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900270 if (nestable_tasks_allowed_ != allowed) {
271 nestable_tasks_allowed_ = allowed;
272 if (!nestable_tasks_allowed_)
273 return;
274 // Start the native pump if we are not already pumping.
darin@google.com981f3552008-08-16 12:09:05 +0900275 pump_->ScheduleWork();
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900276 }
initial.commit3f4a7322008-07-27 06:49:38 +0900277}
278
279bool MessageLoop::NestableTasksAllowed() const {
280 return nestable_tasks_allowed_;
281}
282
jcampan@chromium.orgeac57172009-07-02 04:53:59 +0900283bool MessageLoop::IsNested() {
284 return state_->run_depth > 1;
285}
286
erg@google.com67a25432011-01-08 05:23:43 +0900287void MessageLoop::AddTaskObserver(TaskObserver* task_observer) {
288 DCHECK_EQ(this, current());
289 task_observers_.AddObserver(task_observer);
290}
291
292void MessageLoop::RemoveTaskObserver(TaskObserver* task_observer) {
293 DCHECK_EQ(this, current());
294 task_observers_.RemoveObserver(task_observer);
295}
296
willchan@chromium.org3a397672011-01-26 09:53:48 +0900297void MessageLoop::AssertIdle() const {
298 // We only check |incoming_queue_|, since we don't want to lock |work_queue_|.
299 base::AutoLock lock(incoming_queue_lock_);
300 DCHECK(incoming_queue_.empty());
301}
302
initial.commit3f4a7322008-07-27 06:49:38 +0900303//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900304
erg@google.com67a25432011-01-08 05:23:43 +0900305// Runs the loop in two different SEH modes:
306// enable_SEH_restoration_ = false : any unhandled exception goes to the last
307// one that calls SetUnhandledExceptionFilter().
308// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
309// that was existed before the loop was run.
310void MessageLoop::RunHandler() {
311#if defined(OS_WIN)
312 if (exception_restoration_) {
313 RunInternalInSEHFrame();
314 return;
315 }
316#endif
317
318 RunInternal();
319}
320
321#if defined(OS_WIN)
322__declspec(noinline) void MessageLoop::RunInternalInSEHFrame() {
323 LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
324 __try {
325 RunInternal();
326 } __except(SEHFilter(current_filter)) {
327 }
328 return;
329}
330#endif
331
332void MessageLoop::RunInternal() {
333 DCHECK_EQ(this, current());
334
335 StartHistogrammer();
336
337#if !defined(OS_MACOSX)
338 if (state_->dispatcher && type() == TYPE_UI) {
339 static_cast<base::MessagePumpForUI*>(pump_.get())->
340 RunWithDispatcher(this, state_->dispatcher);
341 return;
342 }
343#endif
344
345 pump_->Run(this);
346}
347
348bool MessageLoop::ProcessNextDelayedNonNestableTask() {
349 if (state_->run_depth != 1)
350 return false;
351
352 if (deferred_non_nestable_work_queue_.empty())
353 return false;
354
355 Task* task = deferred_non_nestable_work_queue_.front().task;
356 deferred_non_nestable_work_queue_.pop();
357
358 RunTask(task);
359 return true;
360}
361
initial.commit3f4a7322008-07-27 06:49:38 +0900362void MessageLoop::RunTask(Task* task) {
initial.commit3f4a7322008-07-27 06:49:38 +0900363 DCHECK(nestable_tasks_allowed_);
364 // Execute the task and assume the worst: It is probably not reentrant.
365 nestable_tasks_allowed_ = false;
darin@google.combe165ae2008-09-07 17:08:29 +0900366
367 HistogramEvent(kTaskRunEvent);
willchan@chromium.orga9047632010-06-10 06:20:41 +0900368 FOR_EACH_OBSERVER(TaskObserver, task_observers_,
davemoore@chromium.orgeb5f68f2010-10-27 08:40:48 +0900369 WillProcessTask(task));
darin@google.combe165ae2008-09-07 17:08:29 +0900370 task->Run();
davemoore@chromium.orgeb5f68f2010-10-27 08:40:48 +0900371 FOR_EACH_OBSERVER(TaskObserver, task_observers_, DidProcessTask(task));
darin@google.combe165ae2008-09-07 17:08:29 +0900372 delete task;
373
374 nestable_tasks_allowed_ = true;
initial.commit3f4a7322008-07-27 06:49:38 +0900375}
376
darin@google.combe165ae2008-09-07 17:08:29 +0900377bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) {
378 if (pending_task.nestable || state_->run_depth == 1) {
379 RunTask(pending_task.task);
380 // Show that we ran a task (Note: a new one might arrive as a
381 // consequence!).
382 return true;
383 }
384
385 // We couldn't run the task now because we're in a nested message loop
386 // and the task isn't nestable.
387 deferred_non_nestable_work_queue_.push(pending_task);
388 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900389}
390
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900391void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
392 // Move to the delayed work queue. Initialize the sequence number
393 // before inserting into the delayed_work_queue_. The sequence number
394 // is used to faciliate FIFO sorting when two tasks have the same
395 // delayed_run_time value.
396 PendingTask new_pending_task(pending_task);
397 new_pending_task.sequence_num = next_sequence_num_++;
398 delayed_work_queue_.push(new_pending_task);
399}
400
initial.commit3f4a7322008-07-27 06:49:38 +0900401void MessageLoop::ReloadWorkQueue() {
402 // We can improve performance of our loading tasks from incoming_queue_ to
darin@google.com981f3552008-08-16 12:09:05 +0900403 // work_queue_ by waiting until the last minute (work_queue_ is empty) to
404 // load. That reduces the number of locks-per-task significantly when our
darin@google.combe165ae2008-09-07 17:08:29 +0900405 // queues get large.
406 if (!work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900407 return; // Wait till we *really* need to lock and load.
408
409 // Acquire all we can from the inter-thread queue with one lock acquisition.
initial.commit3f4a7322008-07-27 06:49:38 +0900410 {
brettw@chromium.orgabe477a2011-01-21 13:55:52 +0900411 base::AutoLock lock(incoming_queue_lock_);
darin@google.combe165ae2008-09-07 17:08:29 +0900412 if (incoming_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900413 return;
darin@chromium.orgb80ef1a2009-09-03 05:05:21 +0900414 incoming_queue_.Swap(&work_queue_); // Constant time
darin@google.combe165ae2008-09-07 17:08:29 +0900415 DCHECK(incoming_queue_.empty());
initial.commit3f4a7322008-07-27 06:49:38 +0900416 }
417}
418
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900419bool MessageLoop::DeletePendingTasks() {
420 bool did_work = !work_queue_.empty();
421 while (!work_queue_.empty()) {
422 PendingTask pending_task = work_queue_.front();
423 work_queue_.pop();
424 if (!pending_task.delayed_run_time.is_null()) {
425 // We want to delete delayed tasks in the same order in which they would
426 // normally be deleted in case of any funny dependencies between delayed
427 // tasks.
428 AddToDelayedWorkQueue(pending_task);
429 } else {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900430 // TODO(darin): Delete all tasks once it is safe to do so.
431 // Until it is totally safe, just do it when running Purify or
432 // Valgrind.
thestig@chromium.orgddb849c2010-10-28 05:03:42 +0900433#if defined(PURIFY) || defined(USE_HEAPCHECKER)
jar@chromium.org63772352009-03-12 05:06:02 +0900434 delete pending_task.task;
timurrrr@chromium.org490200b2011-01-05 04:06:51 +0900435#else
436 if (RunningOnValgrind())
akalin@chromium.org839060b2010-08-03 12:06:21 +0900437 delete pending_task.task;
438#endif // defined(OS_POSIX)
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900439 }
initial.commit3f4a7322008-07-27 06:49:38 +0900440 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900441 did_work |= !deferred_non_nestable_work_queue_.empty();
442 while (!deferred_non_nestable_work_queue_.empty()) {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900443 // TODO(darin): Delete all tasks once it is safe to do so.
444 // Until it is totaly safe, only delete them under Purify and Valgrind.
445 Task* task = NULL;
thestig@chromium.orgddb849c2010-10-28 05:03:42 +0900446#if defined(PURIFY) || defined(USE_HEAPCHECKER)
akalin@chromium.org839060b2010-08-03 12:06:21 +0900447 task = deferred_non_nestable_work_queue_.front().task;
timurrrr@chromium.org490200b2011-01-05 04:06:51 +0900448#else
449 if (RunningOnValgrind())
akalin@chromium.org839060b2010-08-03 12:06:21 +0900450 task = deferred_non_nestable_work_queue_.front().task;
451#endif
jar@chromium.org2fa6b4b2009-03-12 04:53:50 +0900452 deferred_non_nestable_work_queue_.pop();
akalin@chromium.org839060b2010-08-03 12:06:21 +0900453 if (task)
454 delete task;
initial.commit3f4a7322008-07-27 06:49:38 +0900455 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900456 did_work |= !delayed_work_queue_.empty();
457 while (!delayed_work_queue_.empty()) {
akalin@chromium.org839060b2010-08-03 12:06:21 +0900458 Task* task = delayed_work_queue_.top().task;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900459 delayed_work_queue_.pop();
akalin@chromium.org839060b2010-08-03 12:06:21 +0900460 delete task;
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900461 }
462 return did_work;
initial.commit3f4a7322008-07-27 06:49:38 +0900463}
464
erg@google.com67a25432011-01-08 05:23:43 +0900465// Possibly called on a background thread!
466void MessageLoop::PostTask_Helper(
467 const tracked_objects::Location& from_here, Task* task, int64 delay_ms,
468 bool nestable) {
469 task->SetBirthPlace(from_here);
470
471 PendingTask pending_task(task, nestable);
472
473 if (delay_ms > 0) {
474 pending_task.delayed_run_time =
475 TimeTicks::Now() + TimeDelta::FromMilliseconds(delay_ms);
476
477#if defined(OS_WIN)
478 if (high_resolution_timer_expiration_.is_null()) {
479 // Windows timers are granular to 15.6ms. If we only set high-res
480 // timers for those under 15.6ms, then a 18ms timer ticks at ~32ms,
481 // which as a percentage is pretty inaccurate. So enable high
482 // res timers for any timer which is within 2x of the granularity.
483 // This is a tradeoff between accuracy and power management.
484 bool needs_high_res_timers =
485 delay_ms < (2 * base::Time::kMinLowResolutionThresholdMs);
486 if (needs_high_res_timers) {
487 base::Time::ActivateHighResolutionTimer(true);
488 high_resolution_timer_expiration_ = TimeTicks::Now() +
489 TimeDelta::FromMilliseconds(kHighResolutionTimerModeLeaseTimeMs);
490 }
491 }
492#endif
493 } else {
494 DCHECK_EQ(delay_ms, 0) << "delay should not be negative";
495 }
496
497#if defined(OS_WIN)
498 if (!high_resolution_timer_expiration_.is_null()) {
499 if (TimeTicks::Now() > high_resolution_timer_expiration_) {
500 base::Time::ActivateHighResolutionTimer(false);
501 high_resolution_timer_expiration_ = TimeTicks();
502 }
503 }
504#endif
505
506 // Warning: Don't try to short-circuit, and handle this thread's tasks more
507 // directly, as it could starve handling of foreign threads. Put every task
508 // into this queue.
509
510 scoped_refptr<base::MessagePump> pump;
511 {
brettw@chromium.orgabe477a2011-01-21 13:55:52 +0900512 base::AutoLock locked(incoming_queue_lock_);
erg@google.com67a25432011-01-08 05:23:43 +0900513
514 bool was_empty = incoming_queue_.empty();
515 incoming_queue_.push(pending_task);
516 if (!was_empty)
517 return; // Someone else should have started the sub-pump.
518
519 pump = pump_;
520 }
521 // Since the incoming_queue_ may contain a task that destroys this message
522 // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
523 // We use a stack-based reference to the message pump so that we can call
524 // ScheduleWork outside of incoming_queue_lock_.
525
526 pump->ScheduleWork();
527}
528
529//------------------------------------------------------------------------------
530// Method and data for histogramming events and actions taken by each instance
531// on each thread.
532
533void MessageLoop::StartHistogrammer() {
534 if (enable_histogrammer_ && !message_histogram_.get()
535 && base::StatisticsRecorder::IsActive()) {
536 DCHECK(!thread_name_.empty());
537 message_histogram_ = base::LinearHistogram::FactoryGet(
538 "MsgLoop:" + thread_name_,
539 kLeastNonZeroMessageId, kMaxMessageId,
540 kNumberOfDistinctMessagesDisplayed,
541 message_histogram_->kHexRangePrintingFlag);
542 message_histogram_->SetRangeDescriptions(event_descriptions_);
543 }
544}
545
546void MessageLoop::HistogramEvent(int event) {
547 if (message_histogram_.get())
548 message_histogram_->Add(event);
549}
550
darin@google.com981f3552008-08-16 12:09:05 +0900551bool MessageLoop::DoWork() {
darin@google.combe165ae2008-09-07 17:08:29 +0900552 if (!nestable_tasks_allowed_) {
553 // Task can't be executed right now.
554 return false;
555 }
556
557 for (;;) {
558 ReloadWorkQueue();
559 if (work_queue_.empty())
560 break;
561
562 // Execute oldest task.
563 do {
564 PendingTask pending_task = work_queue_.front();
565 work_queue_.pop();
566 if (!pending_task.delayed_run_time.is_null()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900567 AddToDelayedWorkQueue(pending_task);
darin@chromium.orgb2d33452008-09-24 04:19:20 +0900568 // If we changed the topmost task, then it is time to re-schedule.
jar@chromium.org40355072010-10-21 15:32:33 +0900569 if (delayed_work_queue_.top().task == pending_task.task)
darin@google.combe165ae2008-09-07 17:08:29 +0900570 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
571 } else {
572 if (DeferOrRunPendingTask(pending_task))
573 return true;
574 }
575 } while (!work_queue_.empty());
576 }
577
578 // Nothing happened.
579 return false;
darin@google.com981f3552008-08-16 12:09:05 +0900580}
581
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900582bool MessageLoop::DoDelayedWork(base::TimeTicks* next_delayed_work_time) {
jar@chromium.org40355072010-10-21 15:32:33 +0900583 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900584 recent_time_ = *next_delayed_work_time = TimeTicks();
darin@google.combe165ae2008-09-07 17:08:29 +0900585 return false;
586 }
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900587
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900588 // When we "fall behind," there will be a lot of tasks in the delayed work
jar@chromium.org94f73832010-11-05 08:23:42 +0900589 // queue that are ready to run. To increase efficiency when we fall behind,
590 // we will only call Time::Now() intermittently, and then process all tasks
591 // that are ready to run before calling it again. As a result, the more we
592 // fall behind (and have a lot of ready-to-run delayed tasks), the more
593 // efficient we'll be at handling the tasks.
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900594
595 TimeTicks next_run_time = delayed_work_queue_.top().delayed_run_time;
jar@chromium.org94f73832010-11-05 08:23:42 +0900596 if (next_run_time > recent_time_) {
jar@chromium.org9b0fb062010-11-07 07:23:29 +0900597 recent_time_ = TimeTicks::Now(); // Get a better view of Now();
jar@chromium.org94f73832010-11-05 08:23:42 +0900598 if (next_run_time > recent_time_) {
599 *next_delayed_work_time = next_run_time;
600 return false;
601 }
darin@google.combe165ae2008-09-07 17:08:29 +0900602 }
darin@google.com981f3552008-08-16 12:09:05 +0900603
jar@chromium.org40355072010-10-21 15:32:33 +0900604 PendingTask pending_task = delayed_work_queue_.top();
605 delayed_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900606
jar@chromium.org40355072010-10-21 15:32:33 +0900607 if (!delayed_work_queue_.empty())
darin@google.combe165ae2008-09-07 17:08:29 +0900608 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
darin@google.com981f3552008-08-16 12:09:05 +0900609
darin@google.combe165ae2008-09-07 17:08:29 +0900610 return DeferOrRunPendingTask(pending_task);
darin@google.com981f3552008-08-16 12:09:05 +0900611}
612
613bool MessageLoop::DoIdleWork() {
614 if (ProcessNextDelayedNonNestableTask())
615 return true;
616
617 if (state_->quit_received)
618 pump_->Quit();
619
620 return false;
621}
622
623//------------------------------------------------------------------------------
624// MessageLoop::AutoRunState
625
626MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
627 // Make the loop reference us.
628 previous_state_ = loop_->state_;
629 if (previous_state_) {
630 run_depth = previous_state_->run_depth + 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900631 } else {
darin@google.com981f3552008-08-16 12:09:05 +0900632 run_depth = 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900633 }
darin@google.com981f3552008-08-16 12:09:05 +0900634 loop_->state_ = this;
635
636 // Initialize the other fields:
637 quit_received = false;
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900638#if !defined(OS_MACOSX)
darin@google.com981f3552008-08-16 12:09:05 +0900639 dispatcher = NULL;
640#endif
641}
642
643MessageLoop::AutoRunState::~AutoRunState() {
644 loop_->state_ = previous_state_;
darin@google.comee6fa722008-08-13 08:25:43 +0900645}
646
initial.commit3f4a7322008-07-27 06:49:38 +0900647//------------------------------------------------------------------------------
darin@google.combe165ae2008-09-07 17:08:29 +0900648// MessageLoop::PendingTask
initial.commit3f4a7322008-07-27 06:49:38 +0900649
darin@google.combe165ae2008-09-07 17:08:29 +0900650bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
651 // Since the top of a priority queue is defined as the "greatest" element, we
652 // need to invert the comparison here. We want the smaller time to be at the
653 // top of the heap.
initial.commit3f4a7322008-07-27 06:49:38 +0900654
darin@google.combe165ae2008-09-07 17:08:29 +0900655 if (delayed_run_time < other.delayed_run_time)
656 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900657
darin@google.combe165ae2008-09-07 17:08:29 +0900658 if (delayed_run_time > other.delayed_run_time)
659 return true;
initial.commit3f4a7322008-07-27 06:49:38 +0900660
darin@google.combe165ae2008-09-07 17:08:29 +0900661 // If the times happen to match, then we use the sequence number to decide.
662 // Compare the difference to support integer roll-over.
663 return (sequence_num - other.sequence_num) > 0;
initial.commit3f4a7322008-07-27 06:49:38 +0900664}
665
666//------------------------------------------------------------------------------
darin@google.comd936b5b2008-08-26 14:53:57 +0900667// MessageLoopForUI
668
669#if defined(OS_WIN)
darin@google.comd936b5b2008-08-26 14:53:57 +0900670void MessageLoopForUI::DidProcessMessage(const MSG& message) {
671 pump_win()->DidProcessMessage(message);
672}
darin@google.comd936b5b2008-08-26 14:53:57 +0900673#endif // defined(OS_WIN)
674
ajwong@chromium.orgc2064f12011-02-26 03:43:23 +0900675#if defined(USE_X11)
676Display* MessageLoopForUI::GetDisplay() {
ajwong@chromium.org440e0762011-02-19 09:32:44 +0900677 return gdk_x11_get_default_xdisplay();
678}
ajwong@chromium.orgc2064f12011-02-26 03:43:23 +0900679#endif // defined(USE_X11)
ajwong@chromium.org440e0762011-02-19 09:32:44 +0900680
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900681#if !defined(OS_MACOSX) && !defined(OS_NACL)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900682void MessageLoopForUI::AddObserver(Observer* observer) {
683 pump_ui()->AddObserver(observer);
684}
685
686void MessageLoopForUI::RemoveObserver(Observer* observer) {
687 pump_ui()->RemoveObserver(observer);
688}
689
690void MessageLoopForUI::Run(Dispatcher* dispatcher) {
691 AutoRunState save_state(this);
692 state_->dispatcher = dispatcher;
693 RunHandler();
694}
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900695#endif // !defined(OS_MACOSX) && !defined(OS_NACL)
jcampan@chromium.org05423582009-08-01 07:53:37 +0900696
darin@google.comd936b5b2008-08-26 14:53:57 +0900697//------------------------------------------------------------------------------
698// MessageLoopForIO
699
700#if defined(OS_WIN)
701
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900702void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
703 pump_io()->RegisterIOHandler(file, handler);
704}
705
rvargas@google.com73887542008-11-08 06:52:15 +0900706bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
707 return pump_io()->WaitForIOCompletion(timeout, filter);
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900708}
709
abarth@chromium.org1f1c2172010-12-01 17:45:51 +0900710#elif defined(OS_POSIX) && !defined(OS_NACL)
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900711
jeremy@chromium.orgefc0db02008-12-16 07:02:17 +0900712bool MessageLoopForIO::WatchFileDescriptor(int fd,
713 bool persistent,
714 Mode mode,
715 FileDescriptorWatcher *controller,
716 Watcher *delegate) {
717 return pump_libevent()->WatchFileDescriptor(
718 fd,
719 persistent,
720 static_cast<base::MessagePumpLibevent::Mode>(mode),
721 controller,
722 delegate);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900723}
724
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900725#endif