| 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/callback.h" |
| 15 | #include "base/macros.h" |
| 16 | #include "base/message_loop/message_pump_type.h" |
| 17 | #include "base/message_loop/timer_slack.h" |
| 18 | #include "base/sequence_checker.h" |
| 19 | #include "base/single_thread_task_runner.h" |
| 20 | #include "base/synchronization/atomic_flag.h" |
| 21 | #include "base/synchronization/lock.h" |
| 22 | #include "base/synchronization/waitable_event.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 | namespace sequence_manager { |
| 31 | class TimeDomain; |
| 32 | } |
| 33 |
| 34 | // IMPORTANT: Instead of creating a base::Thread, consider using |
| 35 | // base::Create(Sequenced|SingleThread)TaskRunner(). |
| 36 | // |
| 37 | // A simple thread abstraction that establishes a MessageLoop on a new thread. |
| 38 | // The consumer uses the MessageLoop of the thread to cause code to execute on |
| 39 | // the thread. When this object is destroyed the thread is terminated. All |
| 40 | // pending tasks queued on the thread's message loop will run to completion |
| 41 | // before the thread is terminated. |
| 42 | // |
| 43 | // WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread(). |
| 44 | // |
| 45 | // After the thread is stopped, the destruction sequence is: |
| 46 | // |
| 47 | // (1) Thread::CleanUp() |
| 48 | // (2) MessageLoop::~MessageLoop |
| 49 | // (3.b) MessageLoopCurrent::DestructionObserver::WillDestroyCurrentMessageLoop |
| 50 | // |
| 51 | // This API is not thread-safe: unless indicated otherwise its methods are only |
| 52 | // valid from the owning sequence (which is the one from which Start() is |
| 53 | // invoked -- should it differ from the one on which it was constructed). |
| 54 | // |
| 55 | // Sometimes it's useful to kick things off on the initial sequence (e.g. |
| 56 | // construction, Start(), task_runner()), but to then hand the Thread over to a |
| 57 | // pool of users for the last one of them to destroy it when done. For that use |
| 58 | // case, Thread::DetachFromSequence() allows the owning sequence to give up |
| 59 | // ownership. The caller is then responsible to ensure a happens-after |
| 60 | // relationship between the DetachFromSequence() call and the next use of that |
| 61 | // Thread object (including ~Thread()). |
| 62 | class BASE_EXPORT Thread : PlatformThread::Delegate { |
| 63 | public: |
| 64 | class BASE_EXPORT Delegate { |
| 65 | public: |
| 66 | virtual ~Delegate() {} |
| 67 |
| 68 | virtual scoped_refptr<SingleThreadTaskRunner> GetDefaultTaskRunner() = 0; |
| 69 |
| 70 | // Binds a RunLoop::Delegate and TaskRunnerHandle to the thread. The |
| 71 | // underlying MessagePump will have its |timer_slack| set to the specified |
| 72 | // amount. |
| 73 | virtual void BindToCurrentThread(TimerSlack timer_slack) = 0; |
| 74 | }; |
| 75 |
| 76 | struct BASE_EXPORT Options { |
| 77 | using MessagePumpFactory = |
| 78 | RepeatingCallback<std::unique_ptr<MessagePump>()>; |
| 79 |
| 80 | Options(); |
| 81 | Options(MessagePumpType type, size_t size); |
| 82 | Options(Options&& other); |
| 83 | ~Options(); |
| 84 |
| 85 | // Specifies the type of message pump that will be allocated on the thread. |
| 86 | // This is ignored if message_pump_factory.is_null() is false. |
| 87 | MessagePumpType message_pump_type = MessagePumpType::DEFAULT; |
| 88 |
| 89 | // An unbound Delegate that will be bound to the thread. Ownership |
| 90 | // of |delegate| will be transferred to the thread. |
| 91 | // TODO(alexclarke): This should be a std::unique_ptr |
| 92 | Delegate* delegate = nullptr; |
| 93 |
| 94 | // Specifies timer slack for thread message loop. |
| 95 | TimerSlack timer_slack = TIMER_SLACK_NONE; |
| 96 |
| 97 | // The time domain to be used by the task queue. This is not compatible with |
| 98 | // a non-null |delegate|. |
| 99 | sequence_manager::TimeDomain* task_queue_time_domain = nullptr; |
| 100 |
| 101 | // Used to create the MessagePump for the MessageLoop. The callback is Run() |
| 102 | // on the thread. If message_pump_factory.is_null(), then a MessagePump |
| 103 | // appropriate for |message_pump_type| is created. Setting this forces the |
| 104 | // MessagePumpType to TYPE_CUSTOM. This is not compatible with a non-null |
| 105 | // |delegate|. |
| 106 | MessagePumpFactory message_pump_factory; |
| 107 |
| 108 | // Specifies the maximum stack size that the thread is allowed to use. |
| 109 | // This does not necessarily correspond to the thread's initial stack size. |
| 110 | // A value of 0 indicates that the default maximum should be used. |
| 111 | size_t stack_size = 0; |
| 112 |
| 113 | // Specifies the initial thread priority. |
| 114 | ThreadPriority priority = ThreadPriority::NORMAL; |
| 115 |
| 116 | // If false, the thread will not be joined on destruction. This is intended |
| 117 | // for threads that want TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN |
| 118 | // semantics. Non-joinable threads can't be joined (must be leaked and |
| 119 | // can't be destroyed or Stop()'ed). |
| 120 | // TODO(gab): allow non-joinable instances to be deleted without causing |
| 121 | // user-after-frees (proposal @ https://crbug.com/629139#c14) |
| 122 | bool joinable = true; |
| 123 | }; |
| 124 |
| 125 | // Constructor. |
| 126 | // name is a display string to identify the thread. |
| 127 | explicit Thread(const std::string& name); |
| 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 defined(OS_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. |
| 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(const 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. |
| 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). |
| 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 |
| 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 |
| 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 defined(OS_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 defined(OS_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 | RunLoop* run_loop_ = nullptr; |
| 321 |
| 322 | // Stores Options::timer_slack_ until the sequence manager has been bound to |
| 323 | // a thread. |
| 324 | TimerSlack timer_slack_ = TIMER_SLACK_NONE; |
| 325 |
| 326 | // The name of the thread. Used for debugging purposes. |
| 327 | const std::string name_; |
| 328 |
| 329 | // Signaled when the created thread gets ready to use the message loop. |
| 330 | mutable WaitableEvent start_event_; |
| 331 |
| 332 | // This class is not thread-safe, use this to verify access from the owning |
| 333 | // sequence of the Thread. |
| 334 | SequenceChecker owning_sequence_checker_; |
| 335 |
| 336 | DISALLOW_COPY_AND_ASSIGN(Thread); |
| 337 | }; |
| 338 |
| 339 | } // namespace base |
| 340 |
| 341 | #endif // BASE_THREADING_THREAD_H_ |
| 342 |