James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 1 | // Copyright 2013 The Chromium Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #include "base/message_loop/message_loop.h" |
| 6 | |
| 7 | #include <algorithm> |
| 8 | |
| 9 | #include "base/bind.h" |
| 10 | #include "base/compiler_specific.h" |
| 11 | #include "base/lazy_instance.h" |
| 12 | #include "base/logging.h" |
| 13 | #include "base/memory/scoped_ptr.h" |
| 14 | #include "base/message_loop/message_pump_default.h" |
| 15 | #include "base/metrics/histogram.h" |
| 16 | #include "base/metrics/statistics_recorder.h" |
| 17 | #include "base/run_loop.h" |
| 18 | #include "base/third_party/dynamic_annotations/dynamic_annotations.h" |
| 19 | #include "base/thread_task_runner_handle.h" |
| 20 | #include "base/threading/thread_local.h" |
| 21 | #include "base/time/time.h" |
| 22 | #include "base/tracked_objects.h" |
| 23 | |
| 24 | #if defined(OS_MACOSX) |
| 25 | #include "base/message_loop/message_pump_mac.h" |
| 26 | #endif |
| 27 | #if defined(OS_POSIX) && !defined(OS_IOS) |
| 28 | #include "base/message_loop/message_pump_libevent.h" |
| 29 | #endif |
| 30 | #if defined(OS_ANDROID) |
| 31 | #include "base/message_loop/message_pump_android.h" |
| 32 | #endif |
| 33 | #if defined(USE_GLIB) |
| 34 | #include "base/message_loop/message_pump_glib.h" |
| 35 | #endif |
| 36 | |
| 37 | namespace base { |
| 38 | |
| 39 | namespace { |
| 40 | |
| 41 | // A lazily created thread local storage for quick access to a thread's message |
| 42 | // loop, if one exists. This should be safe and free of static constructors. |
| 43 | LazyInstance<base::ThreadLocalPointer<MessageLoop> >::Leaky lazy_tls_ptr = |
| 44 | LAZY_INSTANCE_INITIALIZER; |
| 45 | |
| 46 | // Logical events for Histogram profiling. Run with -message-loop-histogrammer |
| 47 | // to get an accounting of messages and actions taken on each thread. |
| 48 | const int kTaskRunEvent = 0x1; |
| 49 | #if !defined(OS_NACL) |
| 50 | const int kTimerEvent = 0x2; |
| 51 | |
| 52 | // Provide range of message IDs for use in histogramming and debug display. |
| 53 | const int kLeastNonZeroMessageId = 1; |
| 54 | const int kMaxMessageId = 1099; |
| 55 | const int kNumberOfDistinctMessagesDisplayed = 1100; |
| 56 | |
| 57 | // Provide a macro that takes an expression (such as a constant, or macro |
| 58 | // constant) and creates a pair to initalize an array of pairs. In this case, |
| 59 | // our pair consists of the expressions value, and the "stringized" version |
| 60 | // of the expression (i.e., the exrpression put in quotes). For example, if |
| 61 | // we have: |
| 62 | // #define FOO 2 |
| 63 | // #define BAR 5 |
| 64 | // then the following: |
| 65 | // VALUE_TO_NUMBER_AND_NAME(FOO + BAR) |
| 66 | // will expand to: |
| 67 | // {7, "FOO + BAR"} |
| 68 | // We use the resulting array as an argument to our histogram, which reads the |
| 69 | // number as a bucket identifier, and proceeds to use the corresponding name |
| 70 | // in the pair (i.e., the quoted string) when printing out a histogram. |
| 71 | #define VALUE_TO_NUMBER_AND_NAME(name) {name, #name}, |
| 72 | |
| 73 | const LinearHistogram::DescriptionPair event_descriptions_[] = { |
| 74 | // Provide some pretty print capability in our histogram for our internal |
| 75 | // messages. |
| 76 | |
| 77 | // A few events we handle (kindred to messages), and used to profile actions. |
| 78 | VALUE_TO_NUMBER_AND_NAME(kTaskRunEvent) |
| 79 | VALUE_TO_NUMBER_AND_NAME(kTimerEvent) |
| 80 | |
| 81 | {-1, NULL} // The list must be null terminated, per API to histogram. |
| 82 | }; |
| 83 | #endif // !defined(OS_NACL) |
| 84 | |
| 85 | bool enable_histogrammer_ = false; |
| 86 | |
| 87 | MessageLoop::MessagePumpFactory* message_pump_for_ui_factory_ = NULL; |
| 88 | |
| 89 | // Returns true if MessagePump::ScheduleWork() must be called one |
| 90 | // time for every task that is added to the MessageLoop incoming queue. |
| 91 | bool AlwaysNotifyPump(MessageLoop::Type type) { |
| 92 | #if defined(OS_ANDROID) |
| 93 | // The Android UI message loop needs to get notified each time a task is added |
| 94 | // to the incoming queue. |
| 95 | return type == MessageLoop::TYPE_UI || type == MessageLoop::TYPE_JAVA; |
| 96 | #else |
| 97 | return false; |
| 98 | #endif |
| 99 | } |
| 100 | |
| 101 | #if defined(OS_IOS) |
| 102 | typedef MessagePumpIOSForIO MessagePumpForIO; |
James Robinson | 1ae030a | 2014-11-07 08:32:47 -0800 | [diff] [blame] | 103 | #elif defined(OS_NACL_SFI) |
James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 104 | typedef MessagePumpDefault MessagePumpForIO; |
| 105 | #elif defined(OS_POSIX) |
| 106 | typedef MessagePumpLibevent MessagePumpForIO; |
| 107 | #endif |
| 108 | |
James Robinson | 6e9a1c9 | 2014-11-13 17:05:42 -0800 | [diff] [blame^] | 109 | #if !defined(OS_NACL_SFI) |
James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 110 | MessagePumpForIO* ToPumpIO(MessagePump* pump) { |
| 111 | return static_cast<MessagePumpForIO*>(pump); |
| 112 | } |
James Robinson | 6e9a1c9 | 2014-11-13 17:05:42 -0800 | [diff] [blame^] | 113 | #endif // !defined(OS_NACL_SFI) |
James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 114 | |
| 115 | } // namespace |
| 116 | |
| 117 | //------------------------------------------------------------------------------ |
| 118 | |
| 119 | MessageLoop::TaskObserver::TaskObserver() { |
| 120 | } |
| 121 | |
| 122 | MessageLoop::TaskObserver::~TaskObserver() { |
| 123 | } |
| 124 | |
| 125 | MessageLoop::DestructionObserver::~DestructionObserver() { |
| 126 | } |
| 127 | |
| 128 | //------------------------------------------------------------------------------ |
| 129 | |
| 130 | MessageLoop::MessageLoop(Type type) |
| 131 | : type_(type), |
| 132 | pending_high_res_tasks_(0), |
| 133 | in_high_res_mode_(false), |
| 134 | nestable_tasks_allowed_(true), |
| 135 | #if defined(OS_WIN) |
| 136 | os_modal_loop_(false), |
| 137 | #endif // OS_WIN |
| 138 | message_histogram_(NULL), |
| 139 | run_loop_(NULL) { |
| 140 | Init(); |
| 141 | |
| 142 | pump_ = CreateMessagePumpForType(type).Pass(); |
| 143 | } |
| 144 | |
| 145 | MessageLoop::MessageLoop(scoped_ptr<MessagePump> pump) |
| 146 | : pump_(pump.Pass()), |
| 147 | type_(TYPE_CUSTOM), |
| 148 | pending_high_res_tasks_(0), |
| 149 | in_high_res_mode_(false), |
| 150 | nestable_tasks_allowed_(true), |
| 151 | #if defined(OS_WIN) |
| 152 | os_modal_loop_(false), |
| 153 | #endif // OS_WIN |
| 154 | message_histogram_(NULL), |
| 155 | run_loop_(NULL) { |
| 156 | DCHECK(pump_.get()); |
| 157 | Init(); |
| 158 | } |
| 159 | |
| 160 | MessageLoop::~MessageLoop() { |
| 161 | DCHECK_EQ(this, current()); |
| 162 | |
| 163 | DCHECK(!run_loop_); |
| 164 | #if defined(OS_WIN) |
| 165 | if (in_high_res_mode_) |
| 166 | Time::ActivateHighResolutionTimer(false); |
| 167 | #endif |
| 168 | // Clean up any unprocessed tasks, but take care: deleting a task could |
| 169 | // result in the addition of more tasks (e.g., via DeleteSoon). We set a |
| 170 | // limit on the number of times we will allow a deleted task to generate more |
| 171 | // tasks. Normally, we should only pass through this loop once or twice. If |
| 172 | // we end up hitting the loop limit, then it is probably due to one task that |
| 173 | // is being stubborn. Inspect the queues to see who is left. |
| 174 | bool did_work; |
| 175 | for (int i = 0; i < 100; ++i) { |
| 176 | DeletePendingTasks(); |
| 177 | ReloadWorkQueue(); |
| 178 | // If we end up with empty queues, then break out of the loop. |
| 179 | did_work = DeletePendingTasks(); |
| 180 | if (!did_work) |
| 181 | break; |
| 182 | } |
| 183 | DCHECK(!did_work); |
| 184 | |
| 185 | // Let interested parties have one last shot at accessing this. |
| 186 | FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_, |
| 187 | WillDestroyCurrentMessageLoop()); |
| 188 | |
| 189 | thread_task_runner_handle_.reset(); |
| 190 | |
| 191 | // Tell the incoming queue that we are dying. |
| 192 | incoming_task_queue_->WillDestroyCurrentMessageLoop(); |
| 193 | incoming_task_queue_ = NULL; |
| 194 | message_loop_proxy_ = NULL; |
| 195 | |
| 196 | // OK, now make it so that no one can find us. |
| 197 | lazy_tls_ptr.Pointer()->Set(NULL); |
| 198 | } |
| 199 | |
| 200 | // static |
| 201 | MessageLoop* MessageLoop::current() { |
| 202 | // TODO(darin): sadly, we cannot enable this yet since people call us even |
| 203 | // when they have no intention of using us. |
| 204 | // DCHECK(loop) << "Ouch, did you forget to initialize me?"; |
| 205 | return lazy_tls_ptr.Pointer()->Get(); |
| 206 | } |
| 207 | |
| 208 | // static |
| 209 | void MessageLoop::EnableHistogrammer(bool enable) { |
| 210 | enable_histogrammer_ = enable; |
| 211 | } |
| 212 | |
| 213 | // static |
| 214 | bool MessageLoop::InitMessagePumpForUIFactory(MessagePumpFactory* factory) { |
| 215 | if (message_pump_for_ui_factory_) |
| 216 | return false; |
| 217 | |
| 218 | message_pump_for_ui_factory_ = factory; |
| 219 | return true; |
| 220 | } |
| 221 | |
| 222 | // static |
| 223 | scoped_ptr<MessagePump> MessageLoop::CreateMessagePumpForType(Type type) { |
| 224 | // TODO(rvargas): Get rid of the OS guards. |
| 225 | #if defined(USE_GLIB) && !defined(OS_NACL) |
| 226 | typedef MessagePumpGlib MessagePumpForUI; |
| 227 | #elif defined(OS_LINUX) && !defined(OS_NACL) |
| 228 | typedef MessagePumpLibevent MessagePumpForUI; |
| 229 | #endif |
| 230 | |
| 231 | #if defined(OS_IOS) || defined(OS_MACOSX) |
| 232 | #define MESSAGE_PUMP_UI scoped_ptr<MessagePump>(MessagePumpMac::Create()) |
| 233 | #elif defined(OS_NACL) |
| 234 | // Currently NaCl doesn't have a UI MessageLoop. |
| 235 | // TODO(abarth): Figure out if we need this. |
| 236 | #define MESSAGE_PUMP_UI scoped_ptr<MessagePump>() |
| 237 | #else |
| 238 | #define MESSAGE_PUMP_UI scoped_ptr<MessagePump>(new MessagePumpForUI()) |
| 239 | #endif |
| 240 | |
| 241 | #if defined(OS_MACOSX) |
| 242 | // Use an OS native runloop on Mac to support timer coalescing. |
| 243 | #define MESSAGE_PUMP_DEFAULT \ |
| 244 | scoped_ptr<MessagePump>(new MessagePumpCFRunLoop()) |
| 245 | #else |
| 246 | #define MESSAGE_PUMP_DEFAULT scoped_ptr<MessagePump>(new MessagePumpDefault()) |
| 247 | #endif |
| 248 | |
| 249 | if (type == MessageLoop::TYPE_UI) { |
| 250 | if (message_pump_for_ui_factory_) |
| 251 | return message_pump_for_ui_factory_(); |
| 252 | return MESSAGE_PUMP_UI; |
| 253 | } |
| 254 | if (type == MessageLoop::TYPE_IO) |
| 255 | return scoped_ptr<MessagePump>(new MessagePumpForIO()); |
| 256 | |
| 257 | #if defined(OS_ANDROID) |
| 258 | if (type == MessageLoop::TYPE_JAVA) |
| 259 | return scoped_ptr<MessagePump>(new MessagePumpForUI()); |
| 260 | #endif |
| 261 | |
| 262 | DCHECK_EQ(MessageLoop::TYPE_DEFAULT, type); |
| 263 | return MESSAGE_PUMP_DEFAULT; |
| 264 | } |
| 265 | |
| 266 | void MessageLoop::AddDestructionObserver( |
| 267 | DestructionObserver* destruction_observer) { |
| 268 | DCHECK_EQ(this, current()); |
| 269 | destruction_observers_.AddObserver(destruction_observer); |
| 270 | } |
| 271 | |
| 272 | void MessageLoop::RemoveDestructionObserver( |
| 273 | DestructionObserver* destruction_observer) { |
| 274 | DCHECK_EQ(this, current()); |
| 275 | destruction_observers_.RemoveObserver(destruction_observer); |
| 276 | } |
| 277 | |
| 278 | void MessageLoop::PostTask( |
| 279 | const tracked_objects::Location& from_here, |
| 280 | const Closure& task) { |
| 281 | DCHECK(!task.is_null()) << from_here.ToString(); |
| 282 | incoming_task_queue_->AddToIncomingQueue(from_here, task, TimeDelta(), true); |
| 283 | } |
| 284 | |
| 285 | void MessageLoop::PostDelayedTask( |
| 286 | const tracked_objects::Location& from_here, |
| 287 | const Closure& task, |
| 288 | TimeDelta delay) { |
| 289 | DCHECK(!task.is_null()) << from_here.ToString(); |
| 290 | incoming_task_queue_->AddToIncomingQueue(from_here, task, delay, true); |
| 291 | } |
| 292 | |
| 293 | void MessageLoop::PostNonNestableTask( |
| 294 | const tracked_objects::Location& from_here, |
| 295 | const Closure& task) { |
| 296 | DCHECK(!task.is_null()) << from_here.ToString(); |
| 297 | incoming_task_queue_->AddToIncomingQueue(from_here, task, TimeDelta(), false); |
| 298 | } |
| 299 | |
| 300 | void MessageLoop::PostNonNestableDelayedTask( |
| 301 | const tracked_objects::Location& from_here, |
| 302 | const Closure& task, |
| 303 | TimeDelta delay) { |
| 304 | DCHECK(!task.is_null()) << from_here.ToString(); |
| 305 | incoming_task_queue_->AddToIncomingQueue(from_here, task, delay, false); |
| 306 | } |
| 307 | |
| 308 | void MessageLoop::Run() { |
| 309 | RunLoop run_loop; |
| 310 | run_loop.Run(); |
| 311 | } |
| 312 | |
| 313 | void MessageLoop::RunUntilIdle() { |
| 314 | RunLoop run_loop; |
| 315 | run_loop.RunUntilIdle(); |
| 316 | } |
| 317 | |
| 318 | void MessageLoop::QuitWhenIdle() { |
| 319 | DCHECK_EQ(this, current()); |
| 320 | if (run_loop_) { |
| 321 | run_loop_->quit_when_idle_received_ = true; |
| 322 | } else { |
| 323 | NOTREACHED() << "Must be inside Run to call Quit"; |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | void MessageLoop::QuitNow() { |
| 328 | DCHECK_EQ(this, current()); |
| 329 | if (run_loop_) { |
| 330 | pump_->Quit(); |
| 331 | } else { |
| 332 | NOTREACHED() << "Must be inside Run to call Quit"; |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | bool MessageLoop::IsType(Type type) const { |
| 337 | return type_ == type; |
| 338 | } |
| 339 | |
| 340 | static void QuitCurrentWhenIdle() { |
| 341 | MessageLoop::current()->QuitWhenIdle(); |
| 342 | } |
| 343 | |
| 344 | // static |
| 345 | Closure MessageLoop::QuitWhenIdleClosure() { |
| 346 | return Bind(&QuitCurrentWhenIdle); |
| 347 | } |
| 348 | |
| 349 | void MessageLoop::SetNestableTasksAllowed(bool allowed) { |
| 350 | if (allowed) { |
| 351 | // Kick the native pump just in case we enter a OS-driven nested message |
| 352 | // loop. |
| 353 | pump_->ScheduleWork(); |
| 354 | } |
| 355 | nestable_tasks_allowed_ = allowed; |
| 356 | } |
| 357 | |
| 358 | bool MessageLoop::NestableTasksAllowed() const { |
| 359 | return nestable_tasks_allowed_; |
| 360 | } |
| 361 | |
| 362 | bool MessageLoop::IsNested() { |
| 363 | return run_loop_->run_depth_ > 1; |
| 364 | } |
| 365 | |
| 366 | void MessageLoop::AddTaskObserver(TaskObserver* task_observer) { |
| 367 | DCHECK_EQ(this, current()); |
| 368 | task_observers_.AddObserver(task_observer); |
| 369 | } |
| 370 | |
| 371 | void MessageLoop::RemoveTaskObserver(TaskObserver* task_observer) { |
| 372 | DCHECK_EQ(this, current()); |
| 373 | task_observers_.RemoveObserver(task_observer); |
| 374 | } |
| 375 | |
| 376 | bool MessageLoop::is_running() const { |
| 377 | DCHECK_EQ(this, current()); |
| 378 | return run_loop_ != NULL; |
| 379 | } |
| 380 | |
| 381 | bool MessageLoop::HasHighResolutionTasks() { |
| 382 | return incoming_task_queue_->HasHighResolutionTasks(); |
| 383 | } |
| 384 | |
| 385 | bool MessageLoop::IsIdleForTesting() { |
| 386 | // We only check the imcoming queue|, since we don't want to lock the work |
| 387 | // queue. |
| 388 | return incoming_task_queue_->IsIdleForTesting(); |
| 389 | } |
| 390 | |
| 391 | //------------------------------------------------------------------------------ |
| 392 | |
| 393 | void MessageLoop::Init() { |
| 394 | DCHECK(!current()) << "should only have one message loop per thread"; |
| 395 | lazy_tls_ptr.Pointer()->Set(this); |
| 396 | |
| 397 | incoming_task_queue_ = new internal::IncomingTaskQueue(this); |
| 398 | message_loop_proxy_ = |
| 399 | new internal::MessageLoopProxyImpl(incoming_task_queue_); |
| 400 | thread_task_runner_handle_.reset( |
| 401 | new ThreadTaskRunnerHandle(message_loop_proxy_)); |
| 402 | } |
| 403 | |
| 404 | void MessageLoop::RunHandler() { |
| 405 | DCHECK_EQ(this, current()); |
| 406 | |
| 407 | StartHistogrammer(); |
| 408 | |
| 409 | #if defined(OS_WIN) |
| 410 | if (run_loop_->dispatcher_ && type() == TYPE_UI) { |
| 411 | static_cast<MessagePumpForUI*>(pump_.get())-> |
| 412 | RunWithDispatcher(this, run_loop_->dispatcher_); |
| 413 | return; |
| 414 | } |
| 415 | #endif |
| 416 | |
| 417 | pump_->Run(this); |
| 418 | } |
| 419 | |
| 420 | bool MessageLoop::ProcessNextDelayedNonNestableTask() { |
| 421 | if (run_loop_->run_depth_ != 1) |
| 422 | return false; |
| 423 | |
| 424 | if (deferred_non_nestable_work_queue_.empty()) |
| 425 | return false; |
| 426 | |
| 427 | PendingTask pending_task = deferred_non_nestable_work_queue_.front(); |
| 428 | deferred_non_nestable_work_queue_.pop(); |
| 429 | |
| 430 | RunTask(pending_task); |
| 431 | return true; |
| 432 | } |
| 433 | |
| 434 | void MessageLoop::RunTask(const PendingTask& pending_task) { |
| 435 | DCHECK(nestable_tasks_allowed_); |
| 436 | |
| 437 | if (pending_task.is_high_res) { |
| 438 | pending_high_res_tasks_--; |
| 439 | CHECK(pending_high_res_tasks_ >= 0); |
| 440 | } |
| 441 | // Execute the task and assume the worst: It is probably not reentrant. |
| 442 | nestable_tasks_allowed_ = false; |
| 443 | |
| 444 | HistogramEvent(kTaskRunEvent); |
| 445 | |
| 446 | FOR_EACH_OBSERVER(TaskObserver, task_observers_, |
| 447 | WillProcessTask(pending_task)); |
| 448 | task_annotator_.RunTask( |
| 449 | "MessageLoop::PostTask", "MessageLoop::RunTask", pending_task); |
| 450 | FOR_EACH_OBSERVER(TaskObserver, task_observers_, |
| 451 | DidProcessTask(pending_task)); |
| 452 | |
| 453 | nestable_tasks_allowed_ = true; |
| 454 | } |
| 455 | |
| 456 | bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) { |
| 457 | if (pending_task.nestable || run_loop_->run_depth_ == 1) { |
| 458 | RunTask(pending_task); |
| 459 | // Show that we ran a task (Note: a new one might arrive as a |
| 460 | // consequence!). |
| 461 | return true; |
| 462 | } |
| 463 | |
| 464 | // We couldn't run the task now because we're in a nested message loop |
| 465 | // and the task isn't nestable. |
| 466 | deferred_non_nestable_work_queue_.push(pending_task); |
| 467 | return false; |
| 468 | } |
| 469 | |
| 470 | void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) { |
| 471 | // Move to the delayed work queue. |
| 472 | delayed_work_queue_.push(pending_task); |
| 473 | } |
| 474 | |
| 475 | bool MessageLoop::DeletePendingTasks() { |
| 476 | bool did_work = !work_queue_.empty(); |
| 477 | while (!work_queue_.empty()) { |
| 478 | PendingTask pending_task = work_queue_.front(); |
| 479 | work_queue_.pop(); |
| 480 | if (!pending_task.delayed_run_time.is_null()) { |
| 481 | // We want to delete delayed tasks in the same order in which they would |
| 482 | // normally be deleted in case of any funny dependencies between delayed |
| 483 | // tasks. |
| 484 | AddToDelayedWorkQueue(pending_task); |
| 485 | } |
| 486 | } |
| 487 | did_work |= !deferred_non_nestable_work_queue_.empty(); |
| 488 | while (!deferred_non_nestable_work_queue_.empty()) { |
| 489 | deferred_non_nestable_work_queue_.pop(); |
| 490 | } |
| 491 | did_work |= !delayed_work_queue_.empty(); |
| 492 | |
| 493 | // Historically, we always delete the task regardless of valgrind status. It's |
| 494 | // not completely clear why we want to leak them in the loops above. This |
| 495 | // code is replicating legacy behavior, and should not be considered |
| 496 | // absolutely "correct" behavior. See TODO above about deleting all tasks |
| 497 | // when it's safe. |
| 498 | while (!delayed_work_queue_.empty()) { |
| 499 | delayed_work_queue_.pop(); |
| 500 | } |
| 501 | return did_work; |
| 502 | } |
| 503 | |
| 504 | void MessageLoop::ReloadWorkQueue() { |
| 505 | // We can improve performance of our loading tasks from the incoming queue to |
| 506 | // |*work_queue| by waiting until the last minute (|*work_queue| is empty) to |
| 507 | // load. That reduces the number of locks-per-task significantly when our |
| 508 | // queues get large. |
| 509 | if (work_queue_.empty()) { |
| 510 | pending_high_res_tasks_ += |
| 511 | incoming_task_queue_->ReloadWorkQueue(&work_queue_); |
| 512 | } |
| 513 | } |
| 514 | |
| 515 | void MessageLoop::ScheduleWork(bool was_empty) { |
| 516 | if (was_empty || AlwaysNotifyPump(type_)) |
| 517 | pump_->ScheduleWork(); |
| 518 | } |
| 519 | |
| 520 | //------------------------------------------------------------------------------ |
| 521 | // Method and data for histogramming events and actions taken by each instance |
| 522 | // on each thread. |
| 523 | |
| 524 | void MessageLoop::StartHistogrammer() { |
| 525 | #if !defined(OS_NACL) // NaCl build has no metrics code. |
| 526 | if (enable_histogrammer_ && !message_histogram_ |
| 527 | && StatisticsRecorder::IsActive()) { |
| 528 | DCHECK(!thread_name_.empty()); |
| 529 | message_histogram_ = LinearHistogram::FactoryGetWithRangeDescription( |
| 530 | "MsgLoop:" + thread_name_, |
| 531 | kLeastNonZeroMessageId, kMaxMessageId, |
| 532 | kNumberOfDistinctMessagesDisplayed, |
| 533 | message_histogram_->kHexRangePrintingFlag, |
| 534 | event_descriptions_); |
| 535 | } |
| 536 | #endif |
| 537 | } |
| 538 | |
| 539 | void MessageLoop::HistogramEvent(int event) { |
| 540 | #if !defined(OS_NACL) |
| 541 | if (message_histogram_) |
| 542 | message_histogram_->Add(event); |
| 543 | #endif |
| 544 | } |
| 545 | |
| 546 | bool MessageLoop::DoWork() { |
| 547 | if (!nestable_tasks_allowed_) { |
| 548 | // Task can't be executed right now. |
| 549 | return false; |
| 550 | } |
| 551 | |
| 552 | for (;;) { |
| 553 | ReloadWorkQueue(); |
| 554 | if (work_queue_.empty()) |
| 555 | break; |
| 556 | |
| 557 | // Execute oldest task. |
| 558 | do { |
| 559 | PendingTask pending_task = work_queue_.front(); |
| 560 | work_queue_.pop(); |
| 561 | if (!pending_task.delayed_run_time.is_null()) { |
| 562 | AddToDelayedWorkQueue(pending_task); |
| 563 | // If we changed the topmost task, then it is time to reschedule. |
| 564 | if (delayed_work_queue_.top().task.Equals(pending_task.task)) |
| 565 | pump_->ScheduleDelayedWork(pending_task.delayed_run_time); |
| 566 | } else { |
| 567 | if (DeferOrRunPendingTask(pending_task)) |
| 568 | return true; |
| 569 | } |
| 570 | } while (!work_queue_.empty()); |
| 571 | } |
| 572 | |
| 573 | // Nothing happened. |
| 574 | return false; |
| 575 | } |
| 576 | |
| 577 | bool MessageLoop::DoDelayedWork(TimeTicks* next_delayed_work_time) { |
| 578 | if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) { |
| 579 | recent_time_ = *next_delayed_work_time = TimeTicks(); |
| 580 | return false; |
| 581 | } |
| 582 | |
| 583 | // When we "fall behind," there will be a lot of tasks in the delayed work |
| 584 | // queue that are ready to run. To increase efficiency when we fall behind, |
| 585 | // we will only call Time::Now() intermittently, and then process all tasks |
| 586 | // that are ready to run before calling it again. As a result, the more we |
| 587 | // fall behind (and have a lot of ready-to-run delayed tasks), the more |
| 588 | // efficient we'll be at handling the tasks. |
| 589 | |
| 590 | TimeTicks next_run_time = delayed_work_queue_.top().delayed_run_time; |
| 591 | if (next_run_time > recent_time_) { |
| 592 | recent_time_ = TimeTicks::Now(); // Get a better view of Now(); |
| 593 | if (next_run_time > recent_time_) { |
| 594 | *next_delayed_work_time = next_run_time; |
| 595 | return false; |
| 596 | } |
| 597 | } |
| 598 | |
| 599 | PendingTask pending_task = delayed_work_queue_.top(); |
| 600 | delayed_work_queue_.pop(); |
| 601 | |
| 602 | if (!delayed_work_queue_.empty()) |
| 603 | *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time; |
| 604 | |
| 605 | return DeferOrRunPendingTask(pending_task); |
| 606 | } |
| 607 | |
| 608 | bool MessageLoop::DoIdleWork() { |
| 609 | if (ProcessNextDelayedNonNestableTask()) |
| 610 | return true; |
| 611 | |
| 612 | if (run_loop_->quit_when_idle_received_) |
| 613 | pump_->Quit(); |
| 614 | |
| 615 | // When we return we will do a kernel wait for more tasks. |
| 616 | #if defined(OS_WIN) |
| 617 | // On Windows we activate the high resolution timer so that the wait |
| 618 | // _if_ triggered by the timer happens with good resolution. If we don't |
| 619 | // do this the default resolution is 15ms which might not be acceptable |
| 620 | // for some tasks. |
| 621 | bool high_res = pending_high_res_tasks_ > 0; |
| 622 | if (high_res != in_high_res_mode_) { |
| 623 | in_high_res_mode_ = high_res; |
| 624 | Time::ActivateHighResolutionTimer(in_high_res_mode_); |
| 625 | } |
| 626 | #endif |
| 627 | return false; |
| 628 | } |
| 629 | |
| 630 | void MessageLoop::DeleteSoonInternal(const tracked_objects::Location& from_here, |
| 631 | void(*deleter)(const void*), |
| 632 | const void* object) { |
| 633 | PostNonNestableTask(from_here, Bind(deleter, object)); |
| 634 | } |
| 635 | |
| 636 | void MessageLoop::ReleaseSoonInternal( |
| 637 | const tracked_objects::Location& from_here, |
| 638 | void(*releaser)(const void*), |
| 639 | const void* object) { |
| 640 | PostNonNestableTask(from_here, Bind(releaser, object)); |
| 641 | } |
| 642 | |
| 643 | #if !defined(OS_NACL) |
| 644 | //------------------------------------------------------------------------------ |
| 645 | // MessageLoopForUI |
| 646 | |
| 647 | #if defined(OS_ANDROID) |
| 648 | void MessageLoopForUI::Start() { |
| 649 | // No Histogram support for UI message loop as it is managed by Java side |
| 650 | static_cast<MessagePumpForUI*>(pump_.get())->Start(this); |
| 651 | } |
| 652 | #endif |
| 653 | |
| 654 | #if defined(OS_IOS) |
| 655 | void MessageLoopForUI::Attach() { |
| 656 | static_cast<MessagePumpUIApplication*>(pump_.get())->Attach(this); |
| 657 | } |
| 658 | #endif |
| 659 | |
| 660 | #if defined(USE_OZONE) || (defined(USE_X11) && !defined(USE_GLIB)) |
| 661 | bool MessageLoopForUI::WatchFileDescriptor( |
| 662 | int fd, |
| 663 | bool persistent, |
| 664 | MessagePumpLibevent::Mode mode, |
| 665 | MessagePumpLibevent::FileDescriptorWatcher *controller, |
| 666 | MessagePumpLibevent::Watcher *delegate) { |
| 667 | return static_cast<MessagePumpLibevent*>(pump_.get())->WatchFileDescriptor( |
| 668 | fd, |
| 669 | persistent, |
| 670 | mode, |
| 671 | controller, |
| 672 | delegate); |
| 673 | } |
| 674 | #endif |
| 675 | |
| 676 | #endif // !defined(OS_NACL) |
| 677 | |
| 678 | //------------------------------------------------------------------------------ |
| 679 | // MessageLoopForIO |
| 680 | |
James Robinson | 1ae030a | 2014-11-07 08:32:47 -0800 | [diff] [blame] | 681 | #if !defined(OS_NACL_SFI) |
James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 682 | void MessageLoopForIO::AddIOObserver( |
| 683 | MessageLoopForIO::IOObserver* io_observer) { |
| 684 | ToPumpIO(pump_.get())->AddIOObserver(io_observer); |
| 685 | } |
| 686 | |
| 687 | void MessageLoopForIO::RemoveIOObserver( |
| 688 | MessageLoopForIO::IOObserver* io_observer) { |
| 689 | ToPumpIO(pump_.get())->RemoveIOObserver(io_observer); |
| 690 | } |
| 691 | |
| 692 | #if defined(OS_WIN) |
| 693 | void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) { |
| 694 | ToPumpIO(pump_.get())->RegisterIOHandler(file, handler); |
| 695 | } |
| 696 | |
| 697 | bool MessageLoopForIO::RegisterJobObject(HANDLE job, IOHandler* handler) { |
| 698 | return ToPumpIO(pump_.get())->RegisterJobObject(job, handler); |
| 699 | } |
| 700 | |
| 701 | bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) { |
| 702 | return ToPumpIO(pump_.get())->WaitForIOCompletion(timeout, filter); |
| 703 | } |
| 704 | #elif defined(OS_POSIX) |
| 705 | bool MessageLoopForIO::WatchFileDescriptor(int fd, |
| 706 | bool persistent, |
| 707 | Mode mode, |
| 708 | FileDescriptorWatcher *controller, |
| 709 | Watcher *delegate) { |
| 710 | return ToPumpIO(pump_.get())->WatchFileDescriptor( |
| 711 | fd, |
| 712 | persistent, |
| 713 | mode, |
| 714 | controller, |
| 715 | delegate); |
| 716 | } |
| 717 | #endif |
| 718 | |
James Robinson | 1ae030a | 2014-11-07 08:32:47 -0800 | [diff] [blame] | 719 | #endif // !defined(OS_NACL_SFI) |
James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 720 | |
| 721 | } // namespace base |