thread.h 13 KB

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