thread.h 13 KB

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