1 // Copyright 2012 The Chromium Authors 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 <memory> 11 #include <string> 12 13 #include "base/base_export.h" 14 #include "base/check.h" 15 #include "base/functional/callback.h" 16 #include "base/memory/raw_ptr.h" 17 #include "base/message_loop/message_pump_type.h" 18 #include "base/sequence_checker.h" 19 #include "base/synchronization/atomic_flag.h" 20 #include "base/synchronization/lock.h" 21 #include "base/synchronization/waitable_event.h" 22 #include "base/task/single_thread_task_runner.h" 23 #include "base/threading/platform_thread.h" 24 #include "build/build_config.h" 25 26 namespace base { 27 28 class MessagePump; 29 class RunLoop; 30 31 // IMPORTANT: Instead of creating a base::Thread, consider using 32 // base::ThreadPool::Create(Sequenced|SingleThread)TaskRunner(). 33 // 34 // A simple thread abstraction that establishes a MessageLoop on a new thread. 35 // The consumer uses the MessageLoop of the thread to cause code to execute on 36 // the thread. When this object is destroyed the thread is terminated. All 37 // pending tasks queued on the thread's message loop will run to completion 38 // before the thread is terminated. 39 // 40 // WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread(). 41 // 42 // After the thread is stopped, the destruction sequence is: 43 // 44 // (1) Thread::CleanUp() 45 // (2) MessageLoop::~MessageLoop 46 // (3.b) CurrentThread::DestructionObserver::WillDestroyCurrentMessageLoop 47 // 48 // This API is not thread-safe: unless indicated otherwise its methods are only 49 // valid from the owning sequence (which is the one from which Start() is 50 // invoked -- should it differ from the one on which it was constructed). 51 // 52 // Sometimes it's useful to kick things off on the initial sequence (e.g. 53 // construction, Start(), task_runner()), but to then hand the Thread over to a 54 // pool of users for the last one of them to destroy it when done. For that use 55 // case, Thread::DetachFromSequence() allows the owning sequence to give up 56 // ownership. The caller is then responsible to ensure a happens-after 57 // relationship between the DetachFromSequence() call and the next use of that 58 // Thread object (including ~Thread()). 59 class BASE_EXPORT Thread : PlatformThread::Delegate { 60 public: 61 class BASE_EXPORT Delegate { 62 public: ~Delegate()63 virtual ~Delegate() {} 64 65 virtual scoped_refptr<SingleThreadTaskRunner> GetDefaultTaskRunner() = 0; 66 67 // Binds a RunLoop::Delegate and task runner CurrentDefaultHandle to the 68 // thread. 69 virtual void BindToCurrentThread() = 0; 70 }; 71 72 struct BASE_EXPORT Options { 73 using MessagePumpFactory = 74 RepeatingCallback<std::unique_ptr<MessagePump>()>; 75 76 Options(); 77 Options(MessagePumpType type, size_t size); 78 explicit Options(ThreadType thread_type); 79 Options(Options&& other); 80 Options& operator=(Options&& other); 81 ~Options(); 82 83 // Specifies the type of message pump that will be allocated on the thread. 84 // This is ignored if message_pump_factory.is_null() is false. 85 MessagePumpType message_pump_type = MessagePumpType::DEFAULT; 86 87 // An unbound Delegate that will be bound to the thread. Ownership 88 // of |delegate| will be transferred to the thread. 89 std::unique_ptr<Delegate> delegate = nullptr; 90 91 // Used to create the MessagePump for the MessageLoop. The callback is Run() 92 // on the thread. If message_pump_factory.is_null(), then a MessagePump 93 // appropriate for |message_pump_type| is created. Setting this forces the 94 // MessagePumpType to TYPE_CUSTOM. This is not compatible with a non-null 95 // |delegate|. 96 MessagePumpFactory message_pump_factory; 97 98 // Specifies the maximum stack size that the thread is allowed to use. 99 // This does not necessarily correspond to the thread's initial stack size. 100 // A value of 0 indicates that the default maximum should be used. 101 size_t stack_size = 0; 102 103 // Specifies the initial thread type. 104 ThreadType thread_type = ThreadType::kDefault; 105 106 // If false, the thread will not be joined on destruction. This is intended 107 // for threads that want TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN 108 // semantics. Non-joinable threads can't be joined (must be leaked and 109 // can't be destroyed or Stop()'ed). 110 // TODO(gab): allow non-joinable instances to be deleted without causing 111 // user-after-frees (proposal @ https://crbug.com/629139#c14) 112 bool joinable = true; 113 IsValidOptions114 bool IsValid() const { return !moved_from; } 115 116 private: 117 // Set to true when the object is moved into another. Use to prevent reuse 118 // of a moved-from object. 119 bool moved_from = false; 120 }; 121 122 // Constructor. 123 // name is a display string to identify the thread. 124 explicit Thread(const std::string& name); 125 126 Thread(const Thread&) = delete; 127 Thread& operator=(const Thread&) = delete; 128 129 // Destroys the thread, stopping it if necessary. 130 // 131 // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or 132 // guarantee Stop() is explicitly called before the subclass is destroyed). 133 // This is required to avoid a data race between the destructor modifying the 134 // vtable, and the thread's ThreadMain calling the virtual method Run(). It 135 // also ensures that the CleanUp() virtual method is called on the subclass 136 // before it is destructed. 137 ~Thread() override; 138 139 #if BUILDFLAG(IS_WIN) 140 // Causes the thread to initialize COM. This must be called before calling 141 // Start() or StartWithOptions(). If |use_mta| is false, the thread is also 142 // started with a TYPE_UI message loop. It is an error to call 143 // init_com_with_mta(false) and then StartWithOptions() with any message loop 144 // type other than TYPE_UI. init_com_with_mta(bool use_mta)145 void init_com_with_mta(bool use_mta) { 146 DCHECK(!delegate_); 147 com_status_ = use_mta ? MTA : STA; 148 } 149 #endif 150 151 // Starts the thread. Returns true if the thread was successfully started; 152 // otherwise, returns false. Upon successful return, the message_loop() 153 // getter will return non-null. 154 // 155 // Note: This function can't be called on Windows with the loader lock held; 156 // i.e. during a DllMain, global object construction or destruction, atexit() 157 // callback. 158 bool Start(); 159 160 // Starts the thread. Behaves exactly like Start in addition to allow to 161 // override the default options. 162 // 163 // Note: This function can't be called on Windows with the loader lock held; 164 // i.e. during a DllMain, global object construction or destruction, atexit() 165 // callback. 166 bool StartWithOptions(Options options); 167 168 // Starts the thread and wait for the thread to start and run initialization 169 // before returning. It's same as calling Start() and then 170 // WaitUntilThreadStarted(). 171 // Note that using this (instead of Start() or StartWithOptions() causes 172 // jank on the calling thread, should be used only in testing code. 173 bool StartAndWaitForTesting(); 174 175 // Blocks until the thread starts running. Called within StartAndWait(). 176 // Note that calling this causes jank on the calling thread, must be used 177 // carefully for production code. 178 bool WaitUntilThreadStarted() const; 179 180 // Blocks until all tasks previously posted to this thread have been executed. 181 void FlushForTesting(); 182 183 // Signals the thread to exit and returns once the thread has exited. The 184 // Thread object is completely reset and may be used as if it were newly 185 // constructed (i.e., Start may be called again). Can only be called if 186 // |joinable_|. 187 // 188 // Stop may be called multiple times and is simply ignored if the thread is 189 // already stopped or currently stopping. 190 // 191 // Start/Stop are not thread-safe and callers that desire to invoke them from 192 // different threads must ensure mutual exclusion. 193 // 194 // NOTE: If you are a consumer of Thread, it is not necessary to call this 195 // before deleting your Thread objects, as the destructor will do it. 196 // IF YOU ARE A SUBCLASS OF Thread, YOU MUST CALL THIS IN YOUR DESTRUCTOR. 197 void Stop(); 198 199 // Signals the thread to exit in the near future. 200 // 201 // WARNING: This function is not meant to be commonly used. Use at your own 202 // risk. Calling this function will cause message_loop() to become invalid in 203 // the near future. This function was created to workaround a specific 204 // deadlock on Windows with printer worker thread. In any other case, Stop() 205 // should be used. 206 // 207 // Call Stop() to reset the thread object once it is known that the thread has 208 // quit. 209 void StopSoon(); 210 211 // Detaches the owning sequence, indicating that the next call to this API 212 // (including ~Thread()) can happen from a different sequence (to which it 213 // will be rebound). This call itself must happen on the current owning 214 // sequence and the caller must ensure the next API call has a happens-after 215 // relationship with this one. 216 void DetachFromSequence(); 217 218 // Returns a TaskRunner for this thread. Use the TaskRunner's PostTask 219 // methods to execute code on the thread. Returns nullptr if the thread is not 220 // running (e.g. before Start or after Stop have been called). Callers can 221 // hold on to this even after the thread is gone; in this situation, attempts 222 // to PostTask() will fail. 223 // 224 // In addition to this Thread's owning sequence, this can also safely be 225 // called from the underlying thread itself. task_runner()226 scoped_refptr<SingleThreadTaskRunner> task_runner() const { 227 // This class doesn't provide synchronization around |message_loop_base_| 228 // and as such only the owner should access it (and the underlying thread 229 // which never sees it before it's set). In practice, many callers are 230 // coming from unrelated threads but provide their own implicit (e.g. memory 231 // barriers from task posting) or explicit (e.g. locks) synchronization 232 // making the access of |message_loop_base_| safe... Changing all of those 233 // callers is unfeasible; instead verify that they can reliably see 234 // |message_loop_base_ != nullptr| without synchronization as a proof that 235 // their external synchronization catches the unsynchronized effects of 236 // Start(). 237 DCHECK(owning_sequence_checker_.CalledOnValidSequence() || 238 (id_event_.IsSignaled() && id_ == PlatformThread::CurrentId()) || 239 delegate_); 240 return delegate_ ? delegate_->GetDefaultTaskRunner() : nullptr; 241 } 242 243 // Returns the name of this thread (for display in debugger too). thread_name()244 const std::string& thread_name() const { return name_; } 245 246 // Returns the thread ID. Should not be called before the first Start*() 247 // call. Keeps on returning the same ID even after a Stop() call. The next 248 // Start*() call renews the ID. 249 // 250 // WARNING: This function will block if the thread hasn't started yet. 251 // 252 // This method is thread-safe. 253 PlatformThreadId GetThreadId() const; 254 255 // Returns true if the thread has been started, and not yet stopped. 256 bool IsRunning() const; 257 258 protected: 259 // Called just prior to starting the message loop Init()260 virtual void Init() {} 261 262 // Called to start the run loop 263 virtual void Run(RunLoop* run_loop); 264 265 // Called just after the message loop ends CleanUp()266 virtual void CleanUp() {} 267 268 static void SetThreadWasQuitProperly(bool flag); 269 static bool GetThreadWasQuitProperly(); 270 271 private: 272 // Friends for message_loop() access: 273 friend class MessageLoopTaskRunnerTest; 274 friend class ScheduleWorkTest; 275 276 #if BUILDFLAG(IS_WIN) 277 enum ComStatus { 278 NONE, 279 STA, 280 MTA, 281 }; 282 #endif 283 284 // PlatformThread::Delegate methods: 285 void ThreadMain() override; 286 287 void ThreadQuitHelper(); 288 289 #if BUILDFLAG(IS_WIN) 290 // Whether this thread needs to initialize COM, and if so, in what mode. 291 ComStatus com_status_ = NONE; 292 #endif 293 294 // Mirrors the Options::joinable field used to start this thread. Verified 295 // on Stop() -- non-joinable threads can't be joined (must be leaked). 296 bool joinable_ = true; 297 298 // If true, we're in the middle of stopping, and shouldn't access 299 // |message_loop_|. It may non-nullptr and invalid. 300 // Should be written on the thread that created this thread. Also read data 301 // could be wrong on other threads. 302 bool stopping_ = false; 303 304 // True while inside of Run(). 305 bool running_ = false; 306 mutable base::Lock running_lock_; // Protects |running_|. 307 308 // The thread's handle. 309 PlatformThreadHandle thread_; 310 mutable base::Lock thread_lock_; // Protects |thread_|. 311 312 // The thread's id once it has started. 313 PlatformThreadId id_ = kInvalidThreadId; 314 // Protects |id_| which must only be read while it's signaled. 315 mutable WaitableEvent id_event_; 316 317 // The thread's Delegate and RunLoop are valid only while the thread is 318 // alive. Set by the created thread. 319 std::unique_ptr<Delegate> delegate_; 320 321 raw_ptr<RunLoop> run_loop_ = nullptr; 322 323 // The name of the thread. Used for debugging purposes. 324 const std::string name_; 325 326 // Signaled when the created thread gets ready to use the message loop. 327 mutable WaitableEvent start_event_; 328 329 // This class is not thread-safe, use this to verify access from the owning 330 // sequence of the Thread. 331 SequenceChecker owning_sequence_checker_; 332 }; 333 334 } // namespace base 335 336 #endif // BASE_THREADING_THREAD_H_ 337