Home | History | Annotate | Download | only in message_loop
      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 #ifndef BASE_MESSAGE_LOOP_MESSAGE_LOOP_H_
      6 #define BASE_MESSAGE_LOOP_MESSAGE_LOOP_H_
      7 
      8 #include <memory>
      9 #include <queue>
     10 #include <string>
     11 
     12 #include "base/base_export.h"
     13 #include "base/callback_forward.h"
     14 #include "base/gtest_prod_util.h"
     15 #include "base/macros.h"
     16 #include "base/memory/scoped_refptr.h"
     17 #include "base/message_loop/incoming_task_queue.h"
     18 #include "base/message_loop/message_loop_current.h"
     19 #include "base/message_loop/message_loop_task_runner.h"
     20 #include "base/message_loop/message_pump.h"
     21 #include "base/message_loop/timer_slack.h"
     22 #include "base/observer_list.h"
     23 #include "base/pending_task.h"
     24 #include "base/run_loop.h"
     25 #include "base/synchronization/lock.h"
     26 #include "base/threading/sequence_local_storage_map.h"
     27 #include "base/threading/thread_checker.h"
     28 #include "base/time/time.h"
     29 #include "build/build_config.h"
     30 
     31 // Just in libchrome
     32 namespace brillo {
     33 class BaseMessageLoop;
     34 }
     35 
     36 namespace base {
     37 
     38 class ThreadTaskRunnerHandle;
     39 
     40 // A MessageLoop is used to process events for a particular thread.  There is
     41 // at most one MessageLoop instance per thread.
     42 //
     43 // Events include at a minimum Task instances submitted to the MessageLoop's
     44 // TaskRunner. Depending on the type of message pump used by the MessageLoop
     45 // other events such as UI messages may be processed.  On Windows APC calls (as
     46 // time permits) and signals sent to a registered set of HANDLEs may also be
     47 // processed.
     48 //
     49 // The MessageLoop's API should only be used directly by its owner (and users
     50 // which the owner opts to share a MessageLoop* with). Other ways to access
     51 // subsets of the MessageLoop API:
     52 //   - base::RunLoop : Drive the MessageLoop from the thread it's bound to.
     53 //   - base::Thread/SequencedTaskRunnerHandle : Post back to the MessageLoop
     54 //     from a task running on it.
     55 //   - SequenceLocalStorageSlot : Bind external state to this MessageLoop.
     56 //   - base::MessageLoopCurrent : Access statically exposed APIs of this
     57 //     MessageLoop.
     58 //   - Embedders may provide their own static accessors to post tasks on
     59 //     specific loops (e.g. content::BrowserThreads).
     60 //
     61 // NOTE: Unless otherwise specified, a MessageLoop's methods may only be called
     62 // on the thread where the MessageLoop's Run method executes.
     63 //
     64 // NOTE: MessageLoop has task reentrancy protection.  This means that if a
     65 // task is being processed, a second task cannot start until the first task is
     66 // finished.  Reentrancy can happen when processing a task, and an inner
     67 // message pump is created.  That inner pump then processes native messages
     68 // which could implicitly start an inner task.  Inner message pumps are created
     69 // with dialogs (DialogBox), common dialogs (GetOpenFileName), OLE functions
     70 // (DoDragDrop), printer functions (StartDoc) and *many* others.
     71 //
     72 // Sample workaround when inner task processing is needed:
     73 //   HRESULT hr;
     74 //   {
     75 //     MessageLoopCurrent::ScopedNestableTaskAllower allow;
     76 //     hr = DoDragDrop(...); // Implicitly runs a modal message loop.
     77 //   }
     78 //   // Process |hr| (the result returned by DoDragDrop()).
     79 //
     80 // Please be SURE your task is reentrant (nestable) and all global variables
     81 // are stable and accessible before calling SetNestableTasksAllowed(true).
     82 //
     83 // TODO(gab): MessageLoop doesn't need to be a MessageLoopCurrent once callers
     84 // that store MessageLoop::current() in a MessageLoop* variable have been
     85 // updated to use a MessageLoopCurrent variable.
     86 class BASE_EXPORT MessageLoop : public MessagePump::Delegate,
     87                                 public RunLoop::Delegate,
     88                                 public MessageLoopCurrent {
     89  public:
     90   // TODO(gab): Migrate usage of this class to MessageLoopCurrent and remove
     91   // this forwarded declaration.
     92   using DestructionObserver = MessageLoopCurrent::DestructionObserver;
     93 
     94   // A MessageLoop has a particular type, which indicates the set of
     95   // asynchronous events it may process in addition to tasks and timers.
     96   //
     97   // TYPE_DEFAULT
     98   //   This type of ML only supports tasks and timers.
     99   //
    100   // TYPE_UI
    101   //   This type of ML also supports native UI events (e.g., Windows messages).
    102   //   See also MessageLoopForUI.
    103   //
    104   // TYPE_IO
    105   //   This type of ML also supports asynchronous IO.  See also
    106   //   MessageLoopForIO.
    107   //
    108   // TYPE_JAVA
    109   //   This type of ML is backed by a Java message handler which is responsible
    110   //   for running the tasks added to the ML. This is only for use on Android.
    111   //   TYPE_JAVA behaves in essence like TYPE_UI, except during construction
    112   //   where it does not use the main thread specific pump factory.
    113   //
    114   // TYPE_CUSTOM
    115   //   MessagePump was supplied to constructor.
    116   //
    117   enum Type {
    118     TYPE_DEFAULT,
    119     TYPE_UI,
    120     TYPE_CUSTOM,
    121     TYPE_IO,
    122 #if defined(OS_ANDROID)
    123     TYPE_JAVA,
    124 #endif  // defined(OS_ANDROID)
    125   };
    126 
    127   // Normally, it is not necessary to instantiate a MessageLoop.  Instead, it
    128   // is typical to make use of the current thread's MessageLoop instance.
    129   explicit MessageLoop(Type type = TYPE_DEFAULT);
    130   // Creates a TYPE_CUSTOM MessageLoop with the supplied MessagePump, which must
    131   // be non-NULL.
    132   explicit MessageLoop(std::unique_ptr<MessagePump> pump);
    133 
    134   ~MessageLoop() override;
    135 
    136   // TODO(gab): Mass migrate callers to MessageLoopCurrent::Get().
    137   static MessageLoopCurrent current();
    138 
    139   using MessagePumpFactory = std::unique_ptr<MessagePump>();
    140   // Uses the given base::MessagePumpForUIFactory to override the default
    141   // MessagePump implementation for 'TYPE_UI'. Returns true if the factory
    142   // was successfully registered.
    143   static bool InitMessagePumpForUIFactory(MessagePumpFactory* factory);
    144 
    145   // Creates the default MessagePump based on |type|. Caller owns return
    146   // value.
    147   static std::unique_ptr<MessagePump> CreateMessagePumpForType(Type type);
    148 
    149   // Set the timer slack for this message loop.
    150   void SetTimerSlack(TimerSlack timer_slack) {
    151     pump_->SetTimerSlack(timer_slack);
    152   }
    153 
    154   // Returns true if this loop is |type|. This allows subclasses (especially
    155   // those in tests) to specialize how they are identified.
    156   virtual bool IsType(Type type) const;
    157 
    158   // Returns the type passed to the constructor.
    159   Type type() const { return type_; }
    160 
    161   // Returns the name of the thread this message loop is bound to. This function
    162   // is only valid when this message loop is running, BindToCurrentThread has
    163   // already been called and has an "happens-before" relationship with this call
    164   // (this relationship is obtained implicitly by the MessageLoop's task posting
    165   // system unless calling this very early).
    166   std::string GetThreadName() const;
    167 
    168   // Gets the TaskRunner associated with this message loop.
    169   const scoped_refptr<SingleThreadTaskRunner>& task_runner() const {
    170     return task_runner_;
    171   }
    172 
    173   // Sets a new TaskRunner for this message loop. The message loop must already
    174   // have been bound to a thread prior to this call, and the task runner must
    175   // belong to that thread. Note that changing the task runner will also affect
    176   // the ThreadTaskRunnerHandle for the target thread. Must be called on the
    177   // thread to which the message loop is bound.
    178   void SetTaskRunner(scoped_refptr<SingleThreadTaskRunner> task_runner);
    179 
    180   // Clears task_runner() and the ThreadTaskRunnerHandle for the target thread.
    181   // Must be called on the thread to which the message loop is bound.
    182   void ClearTaskRunnerForTesting();
    183 
    184   // TODO(https://crbug.com/825327): Remove users of TaskObservers through
    185   // MessageLoop::current() and migrate the type back here.
    186   using TaskObserver = MessageLoopCurrent::TaskObserver;
    187 
    188   // These functions can only be called on the same thread that |this| is
    189   // running on.
    190   void AddTaskObserver(TaskObserver* task_observer);
    191   void RemoveTaskObserver(TaskObserver* task_observer);
    192 
    193   // Returns true if the message loop is idle (ignoring delayed tasks). This is
    194   // the same condition which triggers DoWork() to return false: i.e.
    195   // out of tasks which can be processed at the current run-level -- there might
    196   // be deferred non-nestable tasks remaining if currently in a nested run
    197   // level.
    198   bool IsIdleForTesting();
    199 
    200   // Runs the specified PendingTask.
    201   void RunTask(PendingTask* pending_task);
    202 
    203   //----------------------------------------------------------------------------
    204  protected:
    205   std::unique_ptr<MessagePump> pump_;
    206 
    207   using MessagePumpFactoryCallback =
    208       OnceCallback<std::unique_ptr<MessagePump>()>;
    209 
    210   // Common protected constructor. Other constructors delegate the
    211   // initialization to this constructor.
    212   // A subclass can invoke this constructor to create a message_loop of a
    213   // specific type with a custom loop. The implementation does not call
    214   // BindToCurrentThread. If this constructor is invoked directly by a subclass,
    215   // then the subclass must subsequently bind the message loop.
    216   MessageLoop(Type type, MessagePumpFactoryCallback pump_factory);
    217 
    218   // Configure various members and bind this message loop to the current thread.
    219   void BindToCurrentThread();
    220 
    221  private:
    222   //only in libchrome
    223   friend class brillo::BaseMessageLoop;
    224   friend class internal::IncomingTaskQueue;
    225   friend class MessageLoopCurrent;
    226   friend class MessageLoopCurrentForIO;
    227   friend class MessageLoopCurrentForUI;
    228   friend class ScheduleWorkTest;
    229   friend class Thread;
    230   FRIEND_TEST_ALL_PREFIXES(MessageLoopTest, DeleteUnboundLoop);
    231 
    232   class Controller;
    233 
    234   // Creates a MessageLoop without binding to a thread.
    235   // If |type| is TYPE_CUSTOM non-null |pump_factory| must be also given
    236   // to create a message pump for this message loop.  Otherwise a default
    237   // message pump for the |type| is created.
    238   //
    239   // It is valid to call this to create a new message loop on one thread,
    240   // and then pass it to the thread where the message loop actually runs.
    241   // The message loop's BindToCurrentThread() method must be called on the
    242   // thread the message loop runs on, before calling Run().
    243   // Before BindToCurrentThread() is called, only Post*Task() functions can
    244   // be called on the message loop.
    245   static std::unique_ptr<MessageLoop> CreateUnbound(
    246       Type type,
    247       MessagePumpFactoryCallback pump_factory);
    248 
    249   // Sets the ThreadTaskRunnerHandle for the current thread to point to the
    250   // task runner for this message loop.
    251   void SetThreadTaskRunnerHandle();
    252 
    253   // RunLoop::Delegate:
    254   void Run(bool application_tasks_allowed) override;
    255   void Quit() override;
    256   void EnsureWorkScheduled() override;
    257 
    258   // Called to process any delayed non-nestable tasks.
    259   bool ProcessNextDelayedNonNestableTask();
    260 
    261   // Calls RunTask or queues the pending_task on the deferred task list if it
    262   // cannot be run right now.  Returns true if the task was run.
    263   bool DeferOrRunPendingTask(PendingTask pending_task);
    264 
    265   // Delete tasks that haven't run yet without running them.  Used in the
    266   // destructor to make sure all the task's destructors get called.
    267   void DeletePendingTasks();
    268 
    269   // Wakes up the message pump. Can be called on any thread. The caller is
    270   // responsible for synchronizing ScheduleWork() calls.
    271   void ScheduleWork();
    272 
    273   // MessagePump::Delegate methods:
    274   bool DoWork() override;
    275   bool DoDelayedWork(TimeTicks* next_delayed_work_time) override;
    276   bool DoIdleWork() override;
    277 
    278   const Type type_;
    279 
    280 #if defined(OS_WIN)
    281   // Tracks if we have requested high resolution timers. Its only use is to
    282   // turn off the high resolution timer upon loop destruction.
    283   bool in_high_res_mode_ = false;
    284 #endif
    285 
    286   // A recent snapshot of Time::Now(), used to check delayed_work_queue_.
    287   TimeTicks recent_time_;
    288 
    289   // Non-null when the last thing this MessageLoop did is become idle with
    290   // pending delayed tasks. Used to report metrics on the following wake up.
    291   struct ScheduledWakeup {
    292     // The scheduled time of the next delayed task when this loop became idle.
    293     TimeTicks next_run_time;
    294     // The delta until |next_run_time| when this loop became idle.
    295     TimeDelta intended_sleep;
    296   } scheduled_wakeup_;
    297 
    298   ObserverList<DestructionObserver> destruction_observers_;
    299 
    300   // A boolean which prevents unintentional reentrant task execution (e.g. from
    301   // induced nested message loops). As such, nested message loops will only
    302   // process system messages (not application tasks) by default. A nested loop
    303   // layer must have been explicitly granted permission to be able to execute
    304   // application tasks. This is granted either by
    305   // RunLoop::Type::kNestableTasksAllowed when the loop is driven by the
    306   // application or by a ScopedNestableTaskAllower preceding a system call that
    307   // is known to generate a system-driven nested loop.
    308   bool task_execution_allowed_ = true;
    309 
    310   // pump_factory_.Run() is called to create a message pump for this loop
    311   // if type_ is TYPE_CUSTOM and pump_ is null.
    312   MessagePumpFactoryCallback pump_factory_;
    313 
    314   ObserverList<TaskObserver> task_observers_;
    315 
    316   // Pointer to this MessageLoop's Controller, valid until the reference to
    317   // |incoming_task_queue_| is dropped below.
    318   Controller* const message_loop_controller_;
    319   scoped_refptr<internal::IncomingTaskQueue> incoming_task_queue_;
    320 
    321   // A task runner which we haven't bound to a thread yet.
    322   scoped_refptr<internal::MessageLoopTaskRunner> unbound_task_runner_;
    323 
    324   // The task runner associated with this message loop.
    325   scoped_refptr<SingleThreadTaskRunner> task_runner_;
    326   std::unique_ptr<ThreadTaskRunnerHandle> thread_task_runner_handle_;
    327 
    328   // Id of the thread this message loop is bound to. Initialized once when the
    329   // MessageLoop is bound to its thread and constant forever after.
    330   PlatformThreadId thread_id_ = kInvalidThreadId;
    331 
    332   // Holds data stored through the SequenceLocalStorageSlot API.
    333   internal::SequenceLocalStorageMap sequence_local_storage_map_;
    334 
    335   // Enables the SequenceLocalStorageSlot API within its scope.
    336   // Instantiated in BindToCurrentThread().
    337   std::unique_ptr<internal::ScopedSetSequenceLocalStorageMapForCurrentThread>
    338       scoped_set_sequence_local_storage_map_for_current_thread_;
    339 
    340   // Verifies that calls are made on the thread on which BindToCurrentThread()
    341   // was invoked.
    342   THREAD_CHECKER(bound_thread_checker_);
    343 
    344   DISALLOW_COPY_AND_ASSIGN(MessageLoop);
    345 };
    346 
    347 #if !defined(OS_NACL)
    348 
    349 //-----------------------------------------------------------------------------
    350 // MessageLoopForUI extends MessageLoop with methods that are particular to a
    351 // MessageLoop instantiated with TYPE_UI.
    352 //
    353 // By instantiating a MessageLoopForUI on the current thread, the owner enables
    354 // native UI message pumping.
    355 //
    356 // MessageLoopCurrentForUI is exposed statically on its thread via
    357 // MessageLoopCurrentForUI::Get() to provide additional functionality.
    358 //
    359 class BASE_EXPORT MessageLoopForUI : public MessageLoop {
    360  public:
    361   explicit MessageLoopForUI(Type type = TYPE_UI);
    362 
    363   // TODO(gab): Mass migrate callers to MessageLoopCurrentForUI::Get()/IsSet().
    364   static MessageLoopCurrentForUI current();
    365   static bool IsCurrent();
    366 
    367 #if defined(OS_IOS)
    368   // On iOS, the main message loop cannot be Run().  Instead call Attach(),
    369   // which connects this MessageLoop to the UI thread's CFRunLoop and allows
    370   // PostTask() to work.
    371   void Attach();
    372 #endif
    373 
    374 #if defined(OS_ANDROID)
    375   // On Android there are cases where we want to abort immediately without
    376   // calling Quit(), in these cases we call Abort().
    377   void Abort();
    378 
    379   // True if this message pump has been aborted.
    380   bool IsAborted();
    381 
    382   // Since Run() is never called on Android, and the message loop is run by the
    383   // java Looper, quitting the RunLoop won't join the thread, so we need a
    384   // callback to run when the RunLoop goes idle to let the Java thread know when
    385   // it can safely quit.
    386   void QuitWhenIdle(base::OnceClosure callback);
    387 #endif
    388 
    389 #if defined(OS_WIN)
    390   // See method of the same name in the Windows MessagePumpForUI implementation.
    391   void EnableWmQuit();
    392 #endif
    393 };
    394 
    395 // Do not add any member variables to MessageLoopForUI!  This is important b/c
    396 // MessageLoopForUI is often allocated via MessageLoop(TYPE_UI).  Any extra
    397 // data that you need should be stored on the MessageLoop's pump_ instance.
    398 static_assert(sizeof(MessageLoop) == sizeof(MessageLoopForUI),
    399               "MessageLoopForUI should not have extra member variables");
    400 
    401 #endif  // !defined(OS_NACL)
    402 
    403 //-----------------------------------------------------------------------------
    404 // MessageLoopForIO extends MessageLoop with methods that are particular to a
    405 // MessageLoop instantiated with TYPE_IO.
    406 //
    407 // By instantiating a MessageLoopForIO on the current thread, the owner enables
    408 // native async IO message pumping.
    409 //
    410 // MessageLoopCurrentForIO is exposed statically on its thread via
    411 // MessageLoopCurrentForIO::Get() to provide additional functionality.
    412 //
    413 class BASE_EXPORT MessageLoopForIO : public MessageLoop {
    414  public:
    415   MessageLoopForIO() : MessageLoop(TYPE_IO) {}
    416 
    417   // TODO(gab): Mass migrate callers to MessageLoopCurrentForIO::Get()/IsSet().
    418   static MessageLoopCurrentForIO current();
    419   static bool IsCurrent();
    420 };
    421 
    422 // Do not add any member variables to MessageLoopForIO!  This is important b/c
    423 // MessageLoopForIO is often allocated via MessageLoop(TYPE_IO).  Any extra
    424 // data that you need should be stored on the MessageLoop's pump_ instance.
    425 static_assert(sizeof(MessageLoop) == sizeof(MessageLoopForIO),
    426               "MessageLoopForIO should not have extra member variables");
    427 
    428 }  // namespace base
    429 
    430 #endif  // BASE_MESSAGE_LOOP_MESSAGE_LOOP_H_
    431