• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
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/callback.h"
15 #include "base/macros.h"
16 #include "base/message_loop/message_loop.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 
31 // IMPORTANT: Instead of creating a base::Thread, consider using
32 // base::Create(Sequenced|SingleThread)TaskRunnerWithTraits().
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) MessageLoopCurrent::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   struct BASE_EXPORT Options {
62     typedef Callback<std::unique_ptr<MessagePump>()> MessagePumpFactory;
63 
64     Options();
65     Options(MessageLoop::Type type, size_t size);
66     Options(const Options& other);
67     ~Options();
68 
69     // Specifies the type of message loop that will be allocated on the thread.
70     // This is ignored if message_pump_factory.is_null() is false.
71     MessageLoop::Type message_loop_type = MessageLoop::TYPE_DEFAULT;
72 
73     // Specifies timer slack for thread message loop.
74     TimerSlack timer_slack = TIMER_SLACK_NONE;
75 
76     // Used to create the MessagePump for the MessageLoop. The callback is Run()
77     // on the thread. If message_pump_factory.is_null(), then a MessagePump
78     // appropriate for |message_loop_type| is created. Setting this forces the
79     // MessageLoop::Type to TYPE_CUSTOM.
80     MessagePumpFactory message_pump_factory;
81 
82     // Specifies the maximum stack size that the thread is allowed to use.
83     // This does not necessarily correspond to the thread's initial stack size.
84     // A value of 0 indicates that the default maximum should be used.
85     size_t stack_size = 0;
86 
87     // Specifies the initial thread priority.
88     ThreadPriority priority = ThreadPriority::NORMAL;
89 
90     // If false, the thread will not be joined on destruction. This is intended
91     // for threads that want TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN
92     // semantics. Non-joinable threads can't be joined (must be leaked and
93     // can't be destroyed or Stop()'ed).
94     // TODO(gab): allow non-joinable instances to be deleted without causing
95     // user-after-frees (proposal @ https://crbug.com/629139#c14)
96     bool joinable = true;
97   };
98 
99   // Constructor.
100   // name is a display string to identify the thread.
101   explicit Thread(const std::string& name);
102 
103   // Destroys the thread, stopping it if necessary.
104   //
105   // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
106   // guarantee Stop() is explicitly called before the subclass is destroyed).
107   // This is required to avoid a data race between the destructor modifying the
108   // vtable, and the thread's ThreadMain calling the virtual method Run().  It
109   // also ensures that the CleanUp() virtual method is called on the subclass
110   // before it is destructed.
111   ~Thread() override;
112 
113 #if defined(OS_WIN)
114   // Causes the thread to initialize COM.  This must be called before calling
115   // Start() or StartWithOptions().  If |use_mta| is false, the thread is also
116   // started with a TYPE_UI message loop.  It is an error to call
117   // init_com_with_mta(false) and then StartWithOptions() with any message loop
118   // type other than TYPE_UI.
init_com_with_mta(bool use_mta)119   void init_com_with_mta(bool use_mta) {
120     DCHECK(!message_loop_);
121     com_status_ = use_mta ? MTA : STA;
122   }
123 #endif
124 
125   // Starts the thread.  Returns true if the thread was successfully started;
126   // otherwise, returns false.  Upon successful return, the message_loop()
127   // getter will return non-null.
128   //
129   // Note: This function can't be called on Windows with the loader lock held;
130   // i.e. during a DllMain, global object construction or destruction, atexit()
131   // callback.
132   bool Start();
133 
134   // Starts the thread. Behaves exactly like Start in addition to allow to
135   // override the default options.
136   //
137   // Note: This function can't be called on Windows with the loader lock held;
138   // i.e. during a DllMain, global object construction or destruction, atexit()
139   // callback.
140   bool StartWithOptions(const Options& options);
141 
142   // Starts the thread and wait for the thread to start and run initialization
143   // before returning. It's same as calling Start() and then
144   // WaitUntilThreadStarted().
145   // Note that using this (instead of Start() or StartWithOptions() causes
146   // jank on the calling thread, should be used only in testing code.
147   bool StartAndWaitForTesting();
148 
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 
154   // Blocks until all tasks previously posted to this thread have been executed.
155   void FlushForTesting();
156 
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 
173   // Signals the thread to exit in the near future.
174   //
175   // WARNING: This function is not meant to be commonly used. Use at your own
176   // risk. Calling this function will cause message_loop() to become invalid in
177   // the near future. This function was created to workaround a specific
178   // deadlock on Windows with printer worker thread. In any other case, Stop()
179   // should be used.
180   //
181   // Call Stop() to reset the thread object once it is known that the thread has
182   // quit.
183   void StopSoon();
184 
185   // Detaches the owning sequence, indicating that the next call to this API
186   // (including ~Thread()) can happen from a different sequence (to which it
187   // will be rebound). This call itself must happen on the current owning
188   // sequence and the caller must ensure the next API call has a happens-after
189   // relationship with this one.
190   void DetachFromSequence();
191 
192   // Returns the message loop for this thread.  Use the MessageLoop's
193   // PostTask methods to execute code on the thread.  This only returns
194   // non-null after a successful call to Start.  After Stop has been called,
195   // this will return nullptr.
196   //
197   // NOTE: You must not call this MessageLoop's Quit method directly.  Use
198   // the Thread's Stop method instead.
199   //
200   // In addition to this Thread's owning sequence, this can also safely be
201   // called from the underlying thread itself.
message_loop()202   MessageLoop* message_loop() const {
203     // This class doesn't provide synchronization around |message_loop_| and as
204     // such only the owner should access it (and the underlying thread which
205     // never sees it before it's set). In practice, many callers are coming from
206     // unrelated threads but provide their own implicit (e.g. memory barriers
207     // from task posting) or explicit (e.g. locks) synchronization making the
208     // access of |message_loop_| safe... Changing all of those callers is
209     // unfeasible; instead verify that they can reliably see
210     // |message_loop_ != nullptr| without synchronization as a proof that their
211     // external synchronization catches the unsynchronized effects of Start().
212     // TODO(gab): Despite all of the above this test has to be disabled for now
213     // per crbug.com/629139#c6.
214     // DCHECK(owning_sequence_checker_.CalledOnValidSequence() ||
215     //        (id_event_.IsSignaled() && id_ == PlatformThread::CurrentId()) ||
216     //        message_loop_);
217     return message_loop_;
218   }
219 
220   // Returns a TaskRunner for this thread. Use the TaskRunner's PostTask
221   // methods to execute code on the thread. Returns nullptr if the thread is not
222   // running (e.g. before Start or after Stop have been called). Callers can
223   // hold on to this even after the thread is gone; in this situation, attempts
224   // to PostTask() will fail.
225   //
226   // In addition to this Thread's owning sequence, this can also safely be
227   // called from the underlying thread itself.
task_runner()228   scoped_refptr<SingleThreadTaskRunner> task_runner() const {
229     // Refer to the DCHECK and comment inside |message_loop()|.
230     DCHECK(owning_sequence_checker_.CalledOnValidSequence() ||
231            (id_event_.IsSignaled() && id_ == PlatformThread::CurrentId()) ||
232            message_loop_);
233     return message_loop_ ? message_loop_->task_runner() : nullptr;
234   }
235 
236   // Returns the name of this thread (for display in debugger too).
thread_name()237   const std::string& thread_name() const { return name_; }
238 
239   // Returns the thread ID.  Should not be called before the first Start*()
240   // call.  Keeps on returning the same ID even after a Stop() call. The next
241   // Start*() call renews the ID.
242   //
243   // WARNING: This function will block if the thread hasn't started yet.
244   //
245   // This method is thread-safe.
246   PlatformThreadId GetThreadId() const;
247 
248   // Returns the current thread handle. If called before Start*() returns or
249   // after Stop() returns, an empty thread handle will be returned.
250   //
251   // This method is thread-safe.
252   //
253   // TODO(robliao): Remove this when it no longer needs to be temporarily
254   // exposed for http://crbug.com/717380.
255   PlatformThreadHandle GetThreadHandle() const;
256 
257   // Returns true if the thread has been started, and not yet stopped.
258   bool IsRunning() const;
259 
260  protected:
261   // Called just prior to starting the message loop
Init()262   virtual void Init() {}
263 
264   // Called to start the run loop
265   virtual void Run(RunLoop* run_loop);
266 
267   // Called just after the message loop ends
CleanUp()268   virtual void CleanUp() {}
269 
270   static void SetThreadWasQuitProperly(bool flag);
271   static bool GetThreadWasQuitProperly();
272 
273   // Bind this Thread to an existing MessageLoop instead of starting a new one.
274   // TODO(gab): Remove this after ios/ has undergone the same surgery as
275   // BrowserThreadImpl (ref.
276   // https://chromium-review.googlesource.com/c/chromium/src/+/969104).
277   void SetMessageLoop(MessageLoop* message_loop);
278 
using_external_message_loop()279   bool using_external_message_loop() const {
280     return using_external_message_loop_;
281   }
282 
283  private:
284 #if defined(OS_WIN)
285   enum ComStatus {
286     NONE,
287     STA,
288     MTA,
289   };
290 #endif
291 
292   // PlatformThread::Delegate methods:
293   void ThreadMain() override;
294 
295   void ThreadQuitHelper();
296 
297 #if defined(OS_WIN)
298   // Whether this thread needs to initialize COM, and if so, in what mode.
299   ComStatus com_status_ = NONE;
300 #endif
301 
302   // Mirrors the Options::joinable field used to start this thread. Verified
303   // on Stop() -- non-joinable threads can't be joined (must be leaked).
304   bool joinable_ = true;
305 
306   // If true, we're in the middle of stopping, and shouldn't access
307   // |message_loop_|. It may non-nullptr and invalid.
308   // Should be written on the thread that created this thread. Also read data
309   // could be wrong on other threads.
310   bool stopping_ = false;
311 
312   // True while inside of Run().
313   bool running_ = false;
314   mutable base::Lock running_lock_;  // Protects |running_|.
315 
316   // The thread's handle.
317   PlatformThreadHandle thread_;
318   mutable base::Lock thread_lock_;  // Protects |thread_|.
319 
320   // The thread's id once it has started.
321   PlatformThreadId id_ = kInvalidThreadId;
322   // Protects |id_| which must only be read while it's signaled.
323   mutable WaitableEvent id_event_;
324 
325   // The thread's MessageLoop and RunLoop. Valid only while the thread is alive.
326   // Set by the created thread.
327   MessageLoop* message_loop_ = nullptr;
328   RunLoop* run_loop_ = nullptr;
329 
330   // True only if |message_loop_| was externally provided by |SetMessageLoop()|
331   // in which case this Thread has no underlying |thread_| and should merely
332   // drop |message_loop_| on Stop(). In that event, this remains true after
333   // Stop() was invoked so that subclasses can use this state to build their own
334   // cleanup logic as required.
335   bool using_external_message_loop_ = false;
336 
337   // Stores Options::timer_slack_ until the message loop has been bound to
338   // a thread.
339   TimerSlack message_loop_timer_slack_ = TIMER_SLACK_NONE;
340 
341   // The name of the thread.  Used for debugging purposes.
342   const std::string name_;
343 
344   // Signaled when the created thread gets ready to use the message loop.
345   mutable WaitableEvent start_event_;
346 
347   // This class is not thread-safe, use this to verify access from the owning
348   // sequence of the Thread.
349   SequenceChecker owning_sequence_checker_;
350 
351   DISALLOW_COPY_AND_ASSIGN(Thread);
352 };
353 
354 }  // namespace base
355 
356 #endif  // BASE_THREADING_THREAD_H_
357