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 <stddef.h> 9 10 #include <string> 11 12 #include "base/base_export.h" 13 #include "base/callback.h" 14 #include "base/macros.h" 15 #include "base/memory/scoped_ptr.h" 16 #include "base/message_loop/message_loop.h" 17 #include "base/message_loop/timer_slack.h" 18 #include "base/single_thread_task_runner.h" 19 #include "base/synchronization/lock.h" 20 #include "base/synchronization/waitable_event.h" 21 #include "base/threading/platform_thread.h" 22 #include "build/build_config.h" 23 24 namespace base { 25 26 class MessagePump; 27 28 // A simple thread abstraction that establishes a MessageLoop on a new thread. 29 // The consumer uses the MessageLoop of the thread to cause code to execute on 30 // the thread. When this object is destroyed the thread is terminated. All 31 // pending tasks queued on the thread's message loop will run to completion 32 // before the thread is terminated. 33 // 34 // WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread(). 35 // 36 // After the thread is stopped, the destruction sequence is: 37 // 38 // (1) Thread::CleanUp() 39 // (2) MessageLoop::~MessageLoop 40 // (3.b) MessageLoop::DestructionObserver::WillDestroyCurrentMessageLoop 41 class BASE_EXPORT Thread : PlatformThread::Delegate { 42 public: 43 struct BASE_EXPORT Options { 44 typedef Callback<scoped_ptr<MessagePump>()> MessagePumpFactory; 45 46 Options(); 47 Options(MessageLoop::Type type, size_t size); 48 ~Options(); 49 50 // Specifies the type of message loop that will be allocated on the thread. 51 // This is ignored if message_pump_factory.is_null() is false. 52 MessageLoop::Type message_loop_type; 53 54 // Specifies timer slack for thread message loop. 55 TimerSlack timer_slack; 56 57 // Used to create the MessagePump for the MessageLoop. The callback is Run() 58 // on the thread. If message_pump_factory.is_null(), then a MessagePump 59 // appropriate for |message_loop_type| is created. Setting this forces the 60 // MessageLoop::Type to TYPE_CUSTOM. 61 MessagePumpFactory message_pump_factory; 62 63 // Specifies the maximum stack size that the thread is allowed to use. 64 // This does not necessarily correspond to the thread's initial stack size. 65 // A value of 0 indicates that the default maximum should be used. 66 size_t stack_size; 67 68 // Specifies the initial thread priority. 69 ThreadPriority priority; 70 }; 71 72 // Constructor. 73 // name is a display string to identify the thread. 74 explicit Thread(const std::string& name); 75 76 // Destroys the thread, stopping it if necessary. 77 // 78 // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or 79 // guarantee Stop() is explicitly called before the subclass is destroyed). 80 // This is required to avoid a data race between the destructor modifying the 81 // vtable, and the thread's ThreadMain calling the virtual method Run(). It 82 // also ensures that the CleanUp() virtual method is called on the subclass 83 // before it is destructed. 84 ~Thread() override; 85 86 #if defined(OS_WIN) 87 // Causes the thread to initialize COM. This must be called before calling 88 // Start() or StartWithOptions(). If |use_mta| is false, the thread is also 89 // started with a TYPE_UI message loop. It is an error to call 90 // init_com_with_mta(false) and then StartWithOptions() with any message loop 91 // type other than TYPE_UI. init_com_with_mta(bool use_mta)92 void init_com_with_mta(bool use_mta) { 93 DCHECK(!message_loop_); 94 com_status_ = use_mta ? MTA : STA; 95 } 96 #endif 97 98 // Starts the thread. Returns true if the thread was successfully started; 99 // otherwise, returns false. Upon successful return, the message_loop() 100 // getter will return non-null. 101 // 102 // Note: This function can't be called on Windows with the loader lock held; 103 // i.e. during a DllMain, global object construction or destruction, atexit() 104 // callback. 105 bool Start(); 106 107 // Starts the thread. Behaves exactly like Start in addition to allow to 108 // override the default options. 109 // 110 // Note: This function can't be called on Windows with the loader lock held; 111 // i.e. during a DllMain, global object construction or destruction, atexit() 112 // callback. 113 bool StartWithOptions(const Options& options); 114 115 // Starts the thread and wait for the thread to start and run initialization 116 // before returning. It's same as calling Start() and then 117 // WaitUntilThreadStarted(). 118 // Note that using this (instead of Start() or StartWithOptions() causes 119 // jank on the calling thread, should be used only in testing code. 120 bool StartAndWaitForTesting(); 121 122 // Blocks until the thread starts running. Called within StartAndWait(). 123 // Note that calling this causes jank on the calling thread, must be used 124 // carefully for production code. 125 bool WaitUntilThreadStarted() const; 126 127 // Signals the thread to exit and returns once the thread has exited. After 128 // this method returns, the Thread object is completely reset and may be used 129 // as if it were newly constructed (i.e., Start may be called again). 130 // 131 // Stop may be called multiple times and is simply ignored if the thread is 132 // already stopped. 133 // 134 // NOTE: If you are a consumer of Thread, it is not necessary to call this 135 // before deleting your Thread objects, as the destructor will do it. 136 // IF YOU ARE A SUBCLASS OF Thread, YOU MUST CALL THIS IN YOUR DESTRUCTOR. 137 void Stop(); 138 139 // Signals the thread to exit in the near future. 140 // 141 // WARNING: This function is not meant to be commonly used. Use at your own 142 // risk. Calling this function will cause message_loop() to become invalid in 143 // the near future. This function was created to workaround a specific 144 // deadlock on Windows with printer worker thread. In any other case, Stop() 145 // should be used. 146 // 147 // StopSoon should not be called multiple times as it is risky to do so. It 148 // could cause a timing issue in message_loop() access. Call Stop() to reset 149 // the thread object once it is known that the thread has quit. 150 void StopSoon(); 151 152 // Returns the message loop for this thread. Use the MessageLoop's 153 // PostTask methods to execute code on the thread. This only returns 154 // non-null after a successful call to Start. After Stop has been called, 155 // this will return nullptr. 156 // 157 // NOTE: You must not call this MessageLoop's Quit method directly. Use 158 // the Thread's Stop method instead. 159 // message_loop()160 MessageLoop* message_loop() const { return message_loop_; } 161 162 // Returns a TaskRunner for this thread. Use the TaskRunner's PostTask 163 // methods to execute code on the thread. Returns nullptr if the thread is not 164 // running (e.g. before Start or after Stop have been called). Callers can 165 // hold on to this even after the thread is gone; in this situation, attempts 166 // to PostTask() will fail. task_runner()167 scoped_refptr<SingleThreadTaskRunner> task_runner() const { 168 return message_loop_ ? message_loop_->task_runner() : nullptr; 169 } 170 171 // Returns the name of this thread (for display in debugger too). thread_name()172 const std::string& thread_name() const { return name_; } 173 174 // The native thread handle. thread_handle()175 PlatformThreadHandle thread_handle() { return thread_; } 176 177 // Returns the thread ID. Should not be called before the first Start*() 178 // call. Keeps on returning the same ID even after a Stop() call. The next 179 // Start*() call renews the ID. 180 // 181 // WARNING: This function will block if the thread hasn't started yet. 182 // 183 PlatformThreadId GetThreadId() const; 184 185 // Returns true if the thread has been started, and not yet stopped. 186 bool IsRunning() const; 187 188 protected: 189 // Called just prior to starting the message loop Init()190 virtual void Init() {} 191 192 // Called to start the message loop 193 virtual void Run(MessageLoop* message_loop); 194 195 // Called just after the message loop ends CleanUp()196 virtual void CleanUp() {} 197 198 static void SetThreadWasQuitProperly(bool flag); 199 static bool GetThreadWasQuitProperly(); 200 set_message_loop(MessageLoop * message_loop)201 void set_message_loop(MessageLoop* message_loop) { 202 message_loop_ = message_loop; 203 } 204 205 private: 206 #if defined(OS_WIN) 207 enum ComStatus { 208 NONE, 209 STA, 210 MTA, 211 }; 212 #endif 213 214 // PlatformThread::Delegate methods: 215 void ThreadMain() override; 216 217 #if defined(OS_WIN) 218 // Whether this thread needs to initialize COM, and if so, in what mode. 219 ComStatus com_status_; 220 #endif 221 222 // If true, we're in the middle of stopping, and shouldn't access 223 // |message_loop_|. It may non-nullptr and invalid. 224 // Should be written on the thread that created this thread. Also read data 225 // could be wrong on other threads. 226 bool stopping_; 227 228 // True while inside of Run(). 229 bool running_; 230 mutable base::Lock running_lock_; // Protects |running_|. 231 232 // The thread's handle. 233 PlatformThreadHandle thread_; 234 mutable base::Lock thread_lock_; // Protects |thread_|. 235 236 // The thread's id once it has started. 237 PlatformThreadId id_; 238 mutable WaitableEvent id_event_; // Protects |id_|. 239 240 // The thread's message loop. Valid only while the thread is alive. Set 241 // by the created thread. 242 MessageLoop* message_loop_; 243 244 // Stores Options::timer_slack_ until the message loop has been bound to 245 // a thread. 246 TimerSlack message_loop_timer_slack_; 247 248 // The name of the thread. Used for debugging purposes. 249 std::string name_; 250 251 // Signaled when the created thread gets ready to use the message loop. 252 mutable WaitableEvent start_event_; 253 254 friend void ThreadQuitHelper(); 255 256 DISALLOW_COPY_AND_ASSIGN(Thread); 257 }; 258 259 } // namespace base 260 261 #endif // BASE_THREADING_THREAD_H_ 262