simple_thread.h 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. // Copyright (c) 2011 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. // WARNING: You should probably be using Thread (thread.h) instead. Thread is
  5. // Chrome's message-loop based Thread abstraction, and if you are a
  6. // thread running in the browser, there will likely be assumptions
  7. // that your thread will have an associated message loop.
  8. //
  9. // This is a simple thread interface that backs to a native operating system
  10. // thread. You should use this only when you want a thread that does not have
  11. // an associated MessageLoop. Unittesting is the best example of this.
  12. //
  13. // The simplest interface to use is DelegateSimpleThread, which will create
  14. // a new thread, and execute the Delegate's virtual Run() in this new thread
  15. // until it has completed, exiting the thread.
  16. //
  17. // NOTE: You *MUST* call Join on the thread to clean up the underlying thread
  18. // resources. You are also responsible for destructing the SimpleThread object.
  19. // It is invalid to destroy a SimpleThread while it is running, or without
  20. // Start() having been called (and a thread never created). The Delegate
  21. // object should live as long as a DelegateSimpleThread.
  22. //
  23. // Thread Safety: A SimpleThread is not completely thread safe. It is safe to
  24. // access it from the creating thread or from the newly created thread. This
  25. // implies that the creator thread should be the thread that calls Join.
  26. //
  27. // Example:
  28. // class MyThreadRunner : public DelegateSimpleThread::Delegate { ... };
  29. // MyThreadRunner runner;
  30. // DelegateSimpleThread thread(&runner, "good_name_here");
  31. // thread.Start();
  32. // // Start will return after the Thread has been successfully started and
  33. // // initialized. The newly created thread will invoke runner->Run(), and
  34. // // run until it returns.
  35. // thread.Join(); // Wait until the thread has exited. You *MUST* Join!
  36. // // The SimpleThread object is still valid, however you may not call Join
  37. // // or Start again.
  38. #ifndef BASE_THREADING_SIMPLE_THREAD_H_
  39. #define BASE_THREADING_SIMPLE_THREAD_H_
  40. #include <stddef.h>
  41. #include <string>
  42. #include <vector>
  43. #include "base/base_export.h"
  44. #include "base/compiler_specific.h"
  45. #include "base/containers/queue.h"
  46. #include "base/memory/raw_ptr.h"
  47. #include "base/synchronization/lock.h"
  48. #include "base/synchronization/waitable_event.h"
  49. #include "base/threading/platform_thread.h"
  50. namespace base {
  51. // This is the base SimpleThread. You can derive from it and implement the
  52. // virtual Run method, or you can use the DelegateSimpleThread interface.
  53. // SimpleThread should not be used to run a MessagePump, `base::Thread` must be
  54. // used for that.
  55. class BASE_EXPORT SimpleThread : public PlatformThread::Delegate {
  56. public:
  57. struct BASE_EXPORT Options {
  58. public:
  59. Options() = default;
  60. explicit Options(ThreadType thread_type) : thread_type(thread_type) {}
  61. ~Options() = default;
  62. // Allow copies.
  63. Options(const Options& other) = default;
  64. Options& operator=(const Options& other) = default;
  65. // A custom stack size, or 0 for the system default.
  66. size_t stack_size = 0;
  67. ThreadType thread_type = ThreadType::kDefault;
  68. // If false, the underlying thread's PlatformThreadHandle will not be kept
  69. // around and as such the SimpleThread instance will not be Join()able and
  70. // must not be deleted before Run() is invoked. After that, it's up to
  71. // the subclass to determine when it is safe to delete itself.
  72. bool joinable = true;
  73. };
  74. // Creates a SimpleThread. |options| should be used to manage any specific
  75. // configuration involving the thread creation and management.
  76. // Every thread has a name, which is a display string to identify the thread.
  77. // The thread will not be created until Start() is called.
  78. explicit SimpleThread(const std::string& name);
  79. SimpleThread(const std::string& name, const Options& options);
  80. SimpleThread(const SimpleThread&) = delete;
  81. SimpleThread& operator=(const SimpleThread&) = delete;
  82. ~SimpleThread() override;
  83. // Starts the thread and returns only after the thread has started and
  84. // initialized (i.e. ThreadMain() has been called).
  85. void Start();
  86. // Joins the thread. If StartAsync() was used to start the thread, then this
  87. // first waits for the thread to start cleanly, then it joins.
  88. void Join();
  89. // Starts the thread, but returns immediately, without waiting for the thread
  90. // to have initialized first (i.e. this does not wait for ThreadMain() to have
  91. // been run first).
  92. void StartAsync();
  93. // Subclasses should override the Run method.
  94. virtual void Run() = 0;
  95. // Returns the thread id, only valid after the thread has started. If the
  96. // thread was started using Start(), then this will be valid after the call to
  97. // Start(). If StartAsync() was used to start the thread, then this must not
  98. // be called before HasBeenStarted() returns True.
  99. PlatformThreadId tid();
  100. // Returns True if the thread has been started and initialized (i.e. if
  101. // ThreadMain() has run). If the thread was started with StartAsync(), but it
  102. // hasn't been initialized yet (i.e. ThreadMain() has not run), then this will
  103. // return False.
  104. bool HasBeenStarted();
  105. // Returns True if Join() has ever been called.
  106. bool HasBeenJoined() const { return joined_; }
  107. // Returns true if Start() or StartAsync() has been called.
  108. bool HasStartBeenAttempted() { return start_called_; }
  109. // Overridden from PlatformThread::Delegate:
  110. void ThreadMain() override;
  111. private:
  112. // This is called just before the thread is started. This is called regardless
  113. // of whether Start() or StartAsync() is used to start the thread.
  114. virtual void BeforeStart() {}
  115. // This is called just after the thread has been initialized and just before
  116. // Run() is called. This is called on the newly started thread.
  117. virtual void BeforeRun() {}
  118. // This is called just before the thread is joined. The thread is started and
  119. // has been initialized before this is called.
  120. virtual void BeforeJoin() {}
  121. const std::string name_;
  122. const Options options_;
  123. PlatformThreadHandle thread_; // PlatformThread handle, reset after Join.
  124. WaitableEvent event_; // Signaled if Start() was ever called.
  125. PlatformThreadId tid_ = kInvalidThreadId; // The backing thread's id.
  126. bool joined_ = false; // True if Join has been called.
  127. // Set to true when the platform-thread creation has started.
  128. bool start_called_ = false;
  129. };
  130. // A SimpleThread which delegates Run() to its Delegate. Non-joinable
  131. // DelegateSimpleThread are safe to delete after Run() was invoked, their
  132. // Delegates are also safe to delete after that point from this class' point of
  133. // view (although implementations must of course make sure that Run() will not
  134. // use their Delegate's member state after its deletion).
  135. class BASE_EXPORT DelegateSimpleThread : public SimpleThread {
  136. public:
  137. class BASE_EXPORT Delegate {
  138. public:
  139. virtual ~Delegate() = default;
  140. virtual void Run() = 0;
  141. };
  142. DelegateSimpleThread(Delegate* delegate,
  143. const std::string& name_prefix);
  144. DelegateSimpleThread(Delegate* delegate,
  145. const std::string& name_prefix,
  146. const Options& options);
  147. DelegateSimpleThread(const DelegateSimpleThread&) = delete;
  148. DelegateSimpleThread& operator=(const DelegateSimpleThread&) = delete;
  149. ~DelegateSimpleThread() override;
  150. void Run() override;
  151. private:
  152. raw_ptr<Delegate> delegate_;
  153. };
  154. // DelegateSimpleThreadPool allows you to start up a fixed number of threads,
  155. // and then add jobs which will be dispatched to the threads. This is
  156. // convenient when you have a lot of small work that you want done
  157. // multi-threaded, but don't want to spawn a thread for each small bit of work.
  158. //
  159. // You just call AddWork() to add a delegate to the list of work to be done.
  160. // JoinAll() will make sure that all outstanding work is processed, and wait
  161. // for everything to finish. You can reuse a pool, so you can call Start()
  162. // again after you've called JoinAll().
  163. class BASE_EXPORT DelegateSimpleThreadPool
  164. : public DelegateSimpleThread::Delegate {
  165. public:
  166. typedef DelegateSimpleThread::Delegate Delegate;
  167. DelegateSimpleThreadPool(const std::string& name_prefix, size_t num_threads);
  168. DelegateSimpleThreadPool(const DelegateSimpleThreadPool&) = delete;
  169. DelegateSimpleThreadPool& operator=(const DelegateSimpleThreadPool&) = delete;
  170. ~DelegateSimpleThreadPool() override;
  171. // Start up all of the underlying threads, and start processing work if we
  172. // have any.
  173. void Start();
  174. // Make sure all outstanding work is finished, and wait for and destroy all
  175. // of the underlying threads in the pool.
  176. void JoinAll();
  177. // It is safe to AddWork() any time, before or after Start().
  178. // Delegate* should always be a valid pointer, NULL is reserved internally.
  179. void AddWork(Delegate* work, size_t repeat_count = 1);
  180. // We implement the Delegate interface, for running our internal threads.
  181. void Run() override;
  182. private:
  183. const std::string name_prefix_;
  184. size_t num_threads_;
  185. std::vector<DelegateSimpleThread*> threads_;
  186. base::queue<Delegate*> delegates_;
  187. base::Lock lock_; // Locks delegates_
  188. WaitableEvent dry_; // Not signaled when there is no work to do.
  189. };
  190. } // namespace base
  191. #endif // BASE_THREADING_SIMPLE_THREAD_H_