Home | History | Annotate | Download | only in threading
      1 // Copyright (c) 2012 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_THREADING_THREAD_H_
      6 #define BASE_THREADING_THREAD_H_
      7 
      8 #include <string>
      9 
     10 #include "base/base_export.h"
     11 #include "base/message_loop/message_loop.h"
     12 #include "base/message_loop/message_loop_proxy.h"
     13 #include "base/threading/platform_thread.h"
     14 
     15 namespace base {
     16 
     17 // A simple thread abstraction that establishes a MessageLoop on a new thread.
     18 // The consumer uses the MessageLoop of the thread to cause code to execute on
     19 // the thread.  When this object is destroyed the thread is terminated.  All
     20 // pending tasks queued on the thread's message loop will run to completion
     21 // before the thread is terminated.
     22 //
     23 // WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS!  See ~Thread().
     24 //
     25 // After the thread is stopped, the destruction sequence is:
     26 //
     27 //  (1) Thread::CleanUp()
     28 //  (2) MessageLoop::~MessageLoop
     29 //  (3.b)    MessageLoop::DestructionObserver::WillDestroyCurrentMessageLoop
     30 class BASE_EXPORT Thread : PlatformThread::Delegate {
     31  public:
     32   struct Options {
     33     Options() : message_loop_type(MessageLoop::TYPE_DEFAULT), stack_size(0) {}
     34     Options(MessageLoop::Type type, size_t size)
     35         : message_loop_type(type), stack_size(size) {}
     36 
     37     // Specifies the type of message loop that will be allocated on the thread.
     38     MessageLoop::Type message_loop_type;
     39 
     40     // Specifies the maximum stack size that the thread is allowed to use.
     41     // This does not necessarily correspond to the thread's initial stack size.
     42     // A value of 0 indicates that the default maximum should be used.
     43     size_t stack_size;
     44   };
     45 
     46   // Constructor.
     47   // name is a display string to identify the thread.
     48   explicit Thread(const char* name);
     49 
     50   // Destroys the thread, stopping it if necessary.
     51   //
     52   // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
     53   // guarantee Stop() is explicitly called before the subclass is destroyed).
     54   // This is required to avoid a data race between the destructor modifying the
     55   // vtable, and the thread's ThreadMain calling the virtual method Run().  It
     56   // also ensures that the CleanUp() virtual method is called on the subclass
     57   // before it is destructed.
     58   virtual ~Thread();
     59 
     60 #if defined(OS_WIN)
     61   // Causes the thread to initialize COM.  This must be called before calling
     62   // Start() or StartWithOptions().  If |use_mta| is false, the thread is also
     63   // started with a TYPE_UI message loop.  It is an error to call
     64   // init_com_with_mta(false) and then StartWithOptions() with any message loop
     65   // type other than TYPE_UI.
     66   void init_com_with_mta(bool use_mta) {
     67     DCHECK(!started_);
     68     com_status_ = use_mta ? MTA : STA;
     69   }
     70 #endif
     71 
     72   // Starts the thread.  Returns true if the thread was successfully started;
     73   // otherwise, returns false.  Upon successful return, the message_loop()
     74   // getter will return non-null.
     75   //
     76   // Note: This function can't be called on Windows with the loader lock held;
     77   // i.e. during a DllMain, global object construction or destruction, atexit()
     78   // callback.
     79   bool Start();
     80 
     81   // Starts the thread. Behaves exactly like Start in addition to allow to
     82   // override the default options.
     83   //
     84   // Note: This function can't be called on Windows with the loader lock held;
     85   // i.e. during a DllMain, global object construction or destruction, atexit()
     86   // callback.
     87   bool StartWithOptions(const Options& options);
     88 
     89   // Signals the thread to exit and returns once the thread has exited.  After
     90   // this method returns, the Thread object is completely reset and may be used
     91   // as if it were newly constructed (i.e., Start may be called again).
     92   //
     93   // Stop may be called multiple times and is simply ignored if the thread is
     94   // already stopped.
     95   //
     96   // NOTE: If you are a consumer of Thread, it is not necessary to call this
     97   // before deleting your Thread objects, as the destructor will do it.
     98   // IF YOU ARE A SUBCLASS OF Thread, YOU MUST CALL THIS IN YOUR DESTRUCTOR.
     99   void Stop();
    100 
    101   // Signals the thread to exit in the near future.
    102   //
    103   // WARNING: This function is not meant to be commonly used. Use at your own
    104   // risk. Calling this function will cause message_loop() to become invalid in
    105   // the near future. This function was created to workaround a specific
    106   // deadlock on Windows with printer worker thread. In any other case, Stop()
    107   // should be used.
    108   //
    109   // StopSoon should not be called multiple times as it is risky to do so. It
    110   // could cause a timing issue in message_loop() access. Call Stop() to reset
    111   // the thread object once it is known that the thread has quit.
    112   void StopSoon();
    113 
    114   // Returns the message loop for this thread.  Use the MessageLoop's
    115   // PostTask methods to execute code on the thread.  This only returns
    116   // non-null after a successful call to Start.  After Stop has been called,
    117   // this will return NULL.
    118   //
    119   // NOTE: You must not call this MessageLoop's Quit method directly.  Use
    120   // the Thread's Stop method instead.
    121   //
    122   MessageLoop* message_loop() const { return message_loop_; }
    123 
    124   // Returns a MessageLoopProxy for this thread.  Use the MessageLoopProxy's
    125   // PostTask methods to execute code on the thread.  This only returns
    126   // non-NULL after a successful call to Start. After Stop has been called,
    127   // this will return NULL. Callers can hold on to this even after the thread
    128   // is gone.
    129   scoped_refptr<MessageLoopProxy> message_loop_proxy() const {
    130     return message_loop_ ? message_loop_->message_loop_proxy() : NULL;
    131   }
    132 
    133   // Returns the name of this thread (for display in debugger too).
    134   const std::string& thread_name() const { return name_; }
    135 
    136   // The native thread handle.
    137   PlatformThreadHandle thread_handle() { return thread_; }
    138 
    139   // The thread ID.
    140   PlatformThreadId thread_id() const { return thread_id_; }
    141 
    142   // Returns true if the thread has been started, and not yet stopped.
    143   bool IsRunning() const;
    144 
    145   // Sets the thread priority. The thread must already be started.
    146   void SetPriority(ThreadPriority priority);
    147 
    148  protected:
    149   // Called just prior to starting the message loop
    150   virtual void Init() {}
    151 
    152   // Called to start the message loop
    153   virtual void Run(MessageLoop* message_loop);
    154 
    155   // Called just after the message loop ends
    156   virtual void CleanUp() {}
    157 
    158   static void SetThreadWasQuitProperly(bool flag);
    159   static bool GetThreadWasQuitProperly();
    160 
    161   void set_message_loop(MessageLoop* message_loop) {
    162     message_loop_ = message_loop;
    163   }
    164 
    165  private:
    166 #if defined(OS_WIN)
    167   enum ComStatus {
    168     NONE,
    169     STA,
    170     MTA,
    171   };
    172 #endif
    173 
    174   // PlatformThread::Delegate methods:
    175   virtual void ThreadMain() OVERRIDE;
    176 
    177 #if defined(OS_WIN)
    178   // Whether this thread needs to initialize COM, and if so, in what mode.
    179   ComStatus com_status_;
    180 #endif
    181 
    182   // Whether we successfully started the thread.
    183   bool started_;
    184 
    185   // If true, we're in the middle of stopping, and shouldn't access
    186   // |message_loop_|. It may non-NULL and invalid.
    187   bool stopping_;
    188 
    189   // True while inside of Run().
    190   bool running_;
    191 
    192   // Used to pass data to ThreadMain.
    193   struct StartupData;
    194   StartupData* startup_data_;
    195 
    196   // The thread's handle.
    197   PlatformThreadHandle thread_;
    198 
    199   // The thread's message loop.  Valid only while the thread is alive.  Set
    200   // by the created thread.
    201   MessageLoop* message_loop_;
    202 
    203   // Our thread's ID.
    204   PlatformThreadId thread_id_;
    205 
    206   // The name of the thread.  Used for debugging purposes.
    207   std::string name_;
    208 
    209   friend void ThreadQuitHelper();
    210 
    211   DISALLOW_COPY_AND_ASSIGN(Thread);
    212 };
    213 
    214 }  // namespace base
    215 
    216 #endif  // BASE_THREADING_THREAD_H_
    217