message_loop.h revision 3f50c38dc070f4bb515c1b64450dae14f316474e
1// Copyright (c) 2011 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#ifndef BASE_MESSAGE_LOOP_H_ 6#define BASE_MESSAGE_LOOP_H_ 7#pragma once 8 9#include <queue> 10#include <string> 11 12#include "base/basictypes.h" 13#include "base/lock.h" 14#include "base/message_pump.h" 15#include "base/observer_list.h" 16#include "base/ref_counted.h" 17#include "base/task.h" 18 19#if defined(OS_WIN) 20// We need this to declare base::MessagePumpWin::Dispatcher, which we should 21// really just eliminate. 22#include "base/message_pump_win.h" 23#elif defined(OS_POSIX) 24#include "base/message_pump_libevent.h" 25#if !defined(OS_MACOSX) 26#include "base/message_pump_glib.h" 27#endif 28#endif 29#if defined(TOUCH_UI) 30#include "base/message_pump_glib_x_dispatch.h" 31#endif 32 33namespace base { 34class Histogram; 35} 36 37// A MessageLoop is used to process events for a particular thread. There is 38// at most one MessageLoop instance per thread. 39// 40// Events include at a minimum Task instances submitted to PostTask or those 41// managed by TimerManager. Depending on the type of message pump used by the 42// MessageLoop other events such as UI messages may be processed. On Windows 43// APC calls (as time permits) and signals sent to a registered set of HANDLEs 44// may also be processed. 45// 46// NOTE: Unless otherwise specified, a MessageLoop's methods may only be called 47// on the thread where the MessageLoop's Run method executes. 48// 49// NOTE: MessageLoop has task reentrancy protection. This means that if a 50// task is being processed, a second task cannot start until the first task is 51// finished. Reentrancy can happen when processing a task, and an inner 52// message pump is created. That inner pump then processes native messages 53// which could implicitly start an inner task. Inner message pumps are created 54// with dialogs (DialogBox), common dialogs (GetOpenFileName), OLE functions 55// (DoDragDrop), printer functions (StartDoc) and *many* others. 56// 57// Sample workaround when inner task processing is needed: 58// bool old_state = MessageLoop::current()->NestableTasksAllowed(); 59// MessageLoop::current()->SetNestableTasksAllowed(true); 60// HRESULT hr = DoDragDrop(...); // Implicitly runs a modal message loop here. 61// MessageLoop::current()->SetNestableTasksAllowed(old_state); 62// // Process hr (the result returned by DoDragDrop(). 63// 64// Please be SURE your task is reentrant (nestable) and all global variables 65// are stable and accessible before calling SetNestableTasksAllowed(true). 66// 67class MessageLoop : public base::MessagePump::Delegate { 68 public: 69#if defined(OS_WIN) 70 typedef base::MessagePumpWin::Dispatcher Dispatcher; 71 typedef base::MessagePumpForUI::Observer Observer; 72#elif !defined(OS_MACOSX) 73#if defined(TOUCH_UI) 74 typedef base::MessagePumpGlibXDispatcher Dispatcher; 75#else 76 typedef base::MessagePumpForUI::Dispatcher Dispatcher; 77#endif 78 typedef base::MessagePumpForUI::Observer Observer; 79#endif 80 81 // A MessageLoop has a particular type, which indicates the set of 82 // asynchronous events it may process in addition to tasks and timers. 83 // 84 // TYPE_DEFAULT 85 // This type of ML only supports tasks and timers. 86 // 87 // TYPE_UI 88 // This type of ML also supports native UI events (e.g., Windows messages). 89 // See also MessageLoopForUI. 90 // 91 // TYPE_IO 92 // This type of ML also supports asynchronous IO. See also 93 // MessageLoopForIO. 94 // 95 enum Type { 96 TYPE_DEFAULT, 97 TYPE_UI, 98 TYPE_IO 99 }; 100 101 // Normally, it is not necessary to instantiate a MessageLoop. Instead, it 102 // is typical to make use of the current thread's MessageLoop instance. 103 explicit MessageLoop(Type type = TYPE_DEFAULT); 104 ~MessageLoop(); 105 106 // Returns the MessageLoop object for the current thread, or null if none. 107 static MessageLoop* current(); 108 109 static void EnableHistogrammer(bool enable_histogrammer); 110 111 // A DestructionObserver is notified when the current MessageLoop is being 112 // destroyed. These obsevers are notified prior to MessageLoop::current() 113 // being changed to return NULL. This gives interested parties the chance to 114 // do final cleanup that depends on the MessageLoop. 115 // 116 // NOTE: Any tasks posted to the MessageLoop during this notification will 117 // not be run. Instead, they will be deleted. 118 // 119 class DestructionObserver { 120 public: 121 virtual void WillDestroyCurrentMessageLoop() = 0; 122 123 protected: 124 virtual ~DestructionObserver(); 125 }; 126 127 // Add a DestructionObserver, which will start receiving notifications 128 // immediately. 129 void AddDestructionObserver(DestructionObserver* destruction_observer); 130 131 // Remove a DestructionObserver. It is safe to call this method while a 132 // DestructionObserver is receiving a notification callback. 133 void RemoveDestructionObserver(DestructionObserver* destruction_observer); 134 135 // The "PostTask" family of methods call the task's Run method asynchronously 136 // from within a message loop at some point in the future. 137 // 138 // With the PostTask variant, tasks are invoked in FIFO order, inter-mixed 139 // with normal UI or IO event processing. With the PostDelayedTask variant, 140 // tasks are called after at least approximately 'delay_ms' have elapsed. 141 // 142 // The NonNestable variants work similarly except that they promise never to 143 // dispatch the task from a nested invocation of MessageLoop::Run. Instead, 144 // such tasks get deferred until the top-most MessageLoop::Run is executing. 145 // 146 // The MessageLoop takes ownership of the Task, and deletes it after it has 147 // been Run(). 148 // 149 // NOTE: These methods may be called on any thread. The Task will be invoked 150 // on the thread that executes MessageLoop::Run(). 151 152 void PostTask( 153 const tracked_objects::Location& from_here, Task* task); 154 155 void PostDelayedTask( 156 const tracked_objects::Location& from_here, Task* task, int64 delay_ms); 157 158 void PostNonNestableTask( 159 const tracked_objects::Location& from_here, Task* task); 160 161 void PostNonNestableDelayedTask( 162 const tracked_objects::Location& from_here, Task* task, int64 delay_ms); 163 164 // A variant on PostTask that deletes the given object. This is useful 165 // if the object needs to live until the next run of the MessageLoop (for 166 // example, deleting a RenderProcessHost from within an IPC callback is not 167 // good). 168 // 169 // NOTE: This method may be called on any thread. The object will be deleted 170 // on the thread that executes MessageLoop::Run(). If this is not the same 171 // as the thread that calls PostDelayedTask(FROM_HERE, ), then T MUST inherit 172 // from RefCountedThreadSafe<T>! 173 template <class T> 174 void DeleteSoon(const tracked_objects::Location& from_here, const T* object) { 175 PostNonNestableTask(from_here, new DeleteTask<T>(object)); 176 } 177 178 // A variant on PostTask that releases the given reference counted object 179 // (by calling its Release method). This is useful if the object needs to 180 // live until the next run of the MessageLoop, or if the object needs to be 181 // released on a particular thread. 182 // 183 // NOTE: This method may be called on any thread. The object will be 184 // released (and thus possibly deleted) on the thread that executes 185 // MessageLoop::Run(). If this is not the same as the thread that calls 186 // PostDelayedTask(FROM_HERE, ), then T MUST inherit from 187 // RefCountedThreadSafe<T>! 188 template <class T> 189 void ReleaseSoon(const tracked_objects::Location& from_here, 190 const T* object) { 191 PostNonNestableTask(from_here, new ReleaseTask<T>(object)); 192 } 193 194 // Run the message loop. 195 void Run(); 196 197 // Process all pending tasks, windows messages, etc., but don't wait/sleep. 198 // Return as soon as all items that can be run are taken care of. 199 void RunAllPending(); 200 201 // Signals the Run method to return after it is done processing all pending 202 // messages. This method may only be called on the same thread that called 203 // Run, and Run must still be on the call stack. 204 // 205 // Use QuitTask if you need to Quit another thread's MessageLoop, but note 206 // that doing so is fairly dangerous if the target thread makes nested calls 207 // to MessageLoop::Run. The problem being that you won't know which nested 208 // run loop you are quiting, so be careful! 209 // 210 void Quit(); 211 212 // This method is a variant of Quit, that does not wait for pending messages 213 // to be processed before returning from Run. 214 void QuitNow(); 215 216 // Invokes Quit on the current MessageLoop when run. Useful to schedule an 217 // arbitrary MessageLoop to Quit. 218 class QuitTask : public Task { 219 public: 220 virtual void Run() { 221 MessageLoop::current()->Quit(); 222 } 223 }; 224 225 // Returns the type passed to the constructor. 226 Type type() const { return type_; } 227 228 // Optional call to connect the thread name with this loop. 229 void set_thread_name(const std::string& thread_name) { 230 DCHECK(thread_name_.empty()) << "Should not rename this thread!"; 231 thread_name_ = thread_name; 232 } 233 const std::string& thread_name() const { return thread_name_; } 234 235 // Enables or disables the recursive task processing. This happens in the case 236 // of recursive message loops. Some unwanted message loop may occurs when 237 // using common controls or printer functions. By default, recursive task 238 // processing is disabled. 239 // 240 // The specific case where tasks get queued is: 241 // - The thread is running a message loop. 242 // - It receives a task #1 and execute it. 243 // - The task #1 implicitly start a message loop, like a MessageBox in the 244 // unit test. This can also be StartDoc or GetSaveFileName. 245 // - The thread receives a task #2 before or while in this second message 246 // loop. 247 // - With NestableTasksAllowed set to true, the task #2 will run right away. 248 // Otherwise, it will get executed right after task #1 completes at "thread 249 // message loop level". 250 void SetNestableTasksAllowed(bool allowed); 251 bool NestableTasksAllowed() const; 252 253 // Enables nestable tasks on |loop| while in scope. 254 class ScopedNestableTaskAllower { 255 public: 256 explicit ScopedNestableTaskAllower(MessageLoop* loop) 257 : loop_(loop), 258 old_state_(loop_->NestableTasksAllowed()) { 259 loop_->SetNestableTasksAllowed(true); 260 } 261 ~ScopedNestableTaskAllower() { 262 loop_->SetNestableTasksAllowed(old_state_); 263 } 264 265 private: 266 MessageLoop* loop_; 267 bool old_state_; 268 }; 269 270 // Enables or disables the restoration during an exception of the unhandled 271 // exception filter that was active when Run() was called. This can happen 272 // if some third party code call SetUnhandledExceptionFilter() and never 273 // restores the previous filter. 274 void set_exception_restoration(bool restore) { 275 exception_restoration_ = restore; 276 } 277 278 // Returns true if we are currently running a nested message loop. 279 bool IsNested(); 280 281 // A TaskObserver is an object that receives task notifications from the 282 // MessageLoop. 283 // 284 // NOTE: A TaskObserver implementation should be extremely fast! 285 class TaskObserver { 286 public: 287 TaskObserver(); 288 289 // This method is called before processing a task. 290 virtual void WillProcessTask(const Task* task) = 0; 291 292 // This method is called after processing a task. 293 virtual void DidProcessTask(const Task* task) = 0; 294 295 protected: 296 virtual ~TaskObserver(); 297 }; 298 299 // These functions can only be called on the same thread that |this| is 300 // running on. 301 void AddTaskObserver(TaskObserver* task_observer); 302 void RemoveTaskObserver(TaskObserver* task_observer); 303 304 // Returns true if the message loop has high resolution timers enabled. 305 // Provided for testing. 306 bool high_resolution_timers_enabled() { 307#if defined(OS_WIN) 308 return !high_resolution_timer_expiration_.is_null(); 309#else 310 return true; 311#endif 312 } 313 314 // When we go into high resolution timer mode, we will stay in hi-res mode 315 // for at least 1s. 316 static const int kHighResolutionTimerModeLeaseTimeMs = 1000; 317 318 //---------------------------------------------------------------------------- 319 protected: 320 struct RunState { 321 // Used to count how many Run() invocations are on the stack. 322 int run_depth; 323 324 // Used to record that Quit() was called, or that we should quit the pump 325 // once it becomes idle. 326 bool quit_received; 327 328#if !defined(OS_MACOSX) 329 Dispatcher* dispatcher; 330#endif 331 }; 332 333 class AutoRunState : RunState { 334 public: 335 explicit AutoRunState(MessageLoop* loop); 336 ~AutoRunState(); 337 private: 338 MessageLoop* loop_; 339 RunState* previous_state_; 340 }; 341 342 // This structure is copied around by value. 343 struct PendingTask { 344 PendingTask(Task* task, bool nestable) 345 : task(task), sequence_num(0), nestable(nestable) { 346 } 347 348 // Used to support sorting. 349 bool operator<(const PendingTask& other) const; 350 351 Task* task; // The task to run. 352 base::TimeTicks delayed_run_time; // The time when the task should be run. 353 int sequence_num; // Secondary sort key for run time. 354 bool nestable; // OK to dispatch from a nested loop. 355 }; 356 357 class TaskQueue : public std::queue<PendingTask> { 358 public: 359 void Swap(TaskQueue* queue) { 360 c.swap(queue->c); // Calls std::deque::swap 361 } 362 }; 363 364 typedef std::priority_queue<PendingTask> DelayedTaskQueue; 365 366#if defined(OS_WIN) 367 base::MessagePumpWin* pump_win() { 368 return static_cast<base::MessagePumpWin*>(pump_.get()); 369 } 370#elif defined(OS_POSIX) 371 base::MessagePumpLibevent* pump_libevent() { 372 return static_cast<base::MessagePumpLibevent*>(pump_.get()); 373 } 374#endif 375 376 // A function to encapsulate all the exception handling capability in the 377 // stacks around the running of a main message loop. It will run the message 378 // loop in a SEH try block or not depending on the set_SEH_restoration() 379 // flag invoking respectively RunInternalInSEHFrame() or RunInternal(). 380 void RunHandler(); 381 382#if defined(OS_WIN) 383 __declspec(noinline) void RunInternalInSEHFrame(); 384#endif 385 386 // A surrounding stack frame around the running of the message loop that 387 // supports all saving and restoring of state, as is needed for any/all (ugly) 388 // recursive calls. 389 void RunInternal(); 390 391 // Called to process any delayed non-nestable tasks. 392 bool ProcessNextDelayedNonNestableTask(); 393 394 // Runs the specified task and deletes it. 395 void RunTask(Task* task); 396 397 // Calls RunTask or queues the pending_task on the deferred task list if it 398 // cannot be run right now. Returns true if the task was run. 399 bool DeferOrRunPendingTask(const PendingTask& pending_task); 400 401 // Adds the pending task to delayed_work_queue_. 402 void AddToDelayedWorkQueue(const PendingTask& pending_task); 403 404 // Load tasks from the incoming_queue_ into work_queue_ if the latter is 405 // empty. The former requires a lock to access, while the latter is directly 406 // accessible on this thread. 407 void ReloadWorkQueue(); 408 409 // Delete tasks that haven't run yet without running them. Used in the 410 // destructor to make sure all the task's destructors get called. Returns 411 // true if some work was done. 412 bool DeletePendingTasks(); 413 414 // Post a task to our incomming queue. 415 void PostTask_Helper(const tracked_objects::Location& from_here, Task* task, 416 int64 delay_ms, bool nestable); 417 418 // Start recording histogram info about events and action IF it was enabled 419 // and IF the statistics recorder can accept a registration of our histogram. 420 void StartHistogrammer(); 421 422 // Add occurence of event to our histogram, so that we can see what is being 423 // done in a specific MessageLoop instance (i.e., specific thread). 424 // If message_histogram_ is NULL, this is a no-op. 425 void HistogramEvent(int event); 426 427 // base::MessagePump::Delegate methods: 428 virtual bool DoWork(); 429 virtual bool DoDelayedWork(base::TimeTicks* next_delayed_work_time); 430 virtual bool DoIdleWork(); 431 432 Type type_; 433 434 // A list of tasks that need to be processed by this instance. Note that 435 // this queue is only accessed (push/pop) by our current thread. 436 TaskQueue work_queue_; 437 438 // Contains delayed tasks, sorted by their 'delayed_run_time' property. 439 DelayedTaskQueue delayed_work_queue_; 440 441 // A recent snapshot of Time::Now(), used to check delayed_work_queue_. 442 base::TimeTicks recent_time_; 443 444 // A queue of non-nestable tasks that we had to defer because when it came 445 // time to execute them we were in a nested message loop. They will execute 446 // once we're out of nested message loops. 447 TaskQueue deferred_non_nestable_work_queue_; 448 449 scoped_refptr<base::MessagePump> pump_; 450 451 ObserverList<DestructionObserver> destruction_observers_; 452 453 // A recursion block that prevents accidentally running additonal tasks when 454 // insider a (accidentally induced?) nested message pump. 455 bool nestable_tasks_allowed_; 456 457 bool exception_restoration_; 458 459 std::string thread_name_; 460 // A profiling histogram showing the counts of various messages and events. 461 scoped_refptr<base::Histogram> message_histogram_; 462 463 // A null terminated list which creates an incoming_queue of tasks that are 464 // aquired under a mutex for processing on this instance's thread. These tasks 465 // have not yet been sorted out into items for our work_queue_ vs items that 466 // will be handled by the TimerManager. 467 TaskQueue incoming_queue_; 468 // Protect access to incoming_queue_. 469 Lock incoming_queue_lock_; 470 471 RunState* state_; 472 473#if defined(OS_WIN) 474 base::TimeTicks high_resolution_timer_expiration_; 475#endif 476 477 // The next sequence number to use for delayed tasks. 478 int next_sequence_num_; 479 480 ObserverList<TaskObserver> task_observers_; 481 482 DISALLOW_COPY_AND_ASSIGN(MessageLoop); 483}; 484 485//----------------------------------------------------------------------------- 486// MessageLoopForUI extends MessageLoop with methods that are particular to a 487// MessageLoop instantiated with TYPE_UI. 488// 489// This class is typically used like so: 490// MessageLoopForUI::current()->...call some method... 491// 492class MessageLoopForUI : public MessageLoop { 493 public: 494 MessageLoopForUI() : MessageLoop(TYPE_UI) { 495 } 496 497 // Returns the MessageLoopForUI of the current thread. 498 static MessageLoopForUI* current() { 499 MessageLoop* loop = MessageLoop::current(); 500 DCHECK_EQ(MessageLoop::TYPE_UI, loop->type()); 501 return static_cast<MessageLoopForUI*>(loop); 502 } 503 504#if defined(OS_WIN) 505 void DidProcessMessage(const MSG& message); 506#endif // defined(OS_WIN) 507 508#if !defined(OS_MACOSX) 509 // Please see message_pump_win/message_pump_glib for definitions of these 510 // methods. 511 void AddObserver(Observer* observer); 512 void RemoveObserver(Observer* observer); 513 void Run(Dispatcher* dispatcher); 514 515 protected: 516 // TODO(rvargas): Make this platform independent. 517 base::MessagePumpForUI* pump_ui() { 518 return static_cast<base::MessagePumpForUI*>(pump_.get()); 519 } 520#endif // !defined(OS_MACOSX) 521}; 522 523// Do not add any member variables to MessageLoopForUI! This is important b/c 524// MessageLoopForUI is often allocated via MessageLoop(TYPE_UI). Any extra 525// data that you need should be stored on the MessageLoop's pump_ instance. 526COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForUI), 527 MessageLoopForUI_should_not_have_extra_member_variables); 528 529//----------------------------------------------------------------------------- 530// MessageLoopForIO extends MessageLoop with methods that are particular to a 531// MessageLoop instantiated with TYPE_IO. 532// 533// This class is typically used like so: 534// MessageLoopForIO::current()->...call some method... 535// 536class MessageLoopForIO : public MessageLoop { 537 public: 538#if defined(OS_WIN) 539 typedef base::MessagePumpForIO::IOHandler IOHandler; 540 typedef base::MessagePumpForIO::IOContext IOContext; 541 typedef base::MessagePumpForIO::IOObserver IOObserver; 542#elif defined(OS_POSIX) 543 typedef base::MessagePumpLibevent::Watcher Watcher; 544 typedef base::MessagePumpLibevent::FileDescriptorWatcher 545 FileDescriptorWatcher; 546 typedef base::MessagePumpLibevent::IOObserver IOObserver; 547 548 enum Mode { 549 WATCH_READ = base::MessagePumpLibevent::WATCH_READ, 550 WATCH_WRITE = base::MessagePumpLibevent::WATCH_WRITE, 551 WATCH_READ_WRITE = base::MessagePumpLibevent::WATCH_READ_WRITE 552 }; 553 554#endif 555 556 MessageLoopForIO() : MessageLoop(TYPE_IO) { 557 } 558 559 // Returns the MessageLoopForIO of the current thread. 560 static MessageLoopForIO* current() { 561 MessageLoop* loop = MessageLoop::current(); 562 DCHECK_EQ(MessageLoop::TYPE_IO, loop->type()); 563 return static_cast<MessageLoopForIO*>(loop); 564 } 565 566 void AddIOObserver(IOObserver* io_observer) { 567 pump_io()->AddIOObserver(io_observer); 568 } 569 570 void RemoveIOObserver(IOObserver* io_observer) { 571 pump_io()->RemoveIOObserver(io_observer); 572 } 573 574#if defined(OS_WIN) 575 // Please see MessagePumpWin for definitions of these methods. 576 void RegisterIOHandler(HANDLE file_handle, IOHandler* handler); 577 bool WaitForIOCompletion(DWORD timeout, IOHandler* filter); 578 579 protected: 580 // TODO(rvargas): Make this platform independent. 581 base::MessagePumpForIO* pump_io() { 582 return static_cast<base::MessagePumpForIO*>(pump_.get()); 583 } 584 585#elif defined(OS_POSIX) 586 // Please see MessagePumpLibevent for definition. 587 bool WatchFileDescriptor(int fd, 588 bool persistent, 589 Mode mode, 590 FileDescriptorWatcher *controller, 591 Watcher *delegate); 592 593 private: 594 base::MessagePumpLibevent* pump_io() { 595 return static_cast<base::MessagePumpLibevent*>(pump_.get()); 596 } 597#endif // defined(OS_POSIX) 598}; 599 600// Do not add any member variables to MessageLoopForIO! This is important b/c 601// MessageLoopForIO is often allocated via MessageLoop(TYPE_IO). Any extra 602// data that you need should be stored on the MessageLoop's pump_ instance. 603COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForIO), 604 MessageLoopForIO_should_not_have_extra_member_variables); 605 606#endif // BASE_MESSAGE_LOOP_H_ 607