• 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/single_thread_task_runner.h"
19 #include "base/synchronization/lock.h"
20 #include "base/synchronization/waitable_event.h"
21 #include "base/threading/platform_thread.h"
22 #include "build/build_config.h"
23 
24 namespace base {
25 
26 class MessagePump;
27 
28 // A simple thread abstraction that establishes a MessageLoop on a new thread.
29 // The consumer uses the MessageLoop of the thread to cause code to execute on
30 // the thread.  When this object is destroyed the thread is terminated.  All
31 // pending tasks queued on the thread's message loop will run to completion
32 // before the thread is terminated.
33 //
34 // WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS!  See ~Thread().
35 //
36 // After the thread is stopped, the destruction sequence is:
37 //
38 //  (1) Thread::CleanUp()
39 //  (2) MessageLoop::~MessageLoop
40 //  (3.b)    MessageLoop::DestructionObserver::WillDestroyCurrentMessageLoop
41 class BASE_EXPORT Thread : PlatformThread::Delegate {
42  public:
43   struct BASE_EXPORT Options {
44     typedef Callback<std::unique_ptr<MessagePump>()> MessagePumpFactory;
45 
46     Options();
47     Options(MessageLoop::Type type, size_t size);
48     Options(const Options& other);
49     ~Options();
50 
51     // Specifies the type of message loop that will be allocated on the thread.
52     // This is ignored if message_pump_factory.is_null() is false.
53     MessageLoop::Type message_loop_type;
54 
55     // Specifies timer slack for thread message loop.
56     TimerSlack timer_slack;
57 
58     // Used to create the MessagePump for the MessageLoop. The callback is Run()
59     // on the thread. If message_pump_factory.is_null(), then a MessagePump
60     // appropriate for |message_loop_type| is created. Setting this forces the
61     // MessageLoop::Type to TYPE_CUSTOM.
62     MessagePumpFactory message_pump_factory;
63 
64     // Specifies the maximum stack size that the thread is allowed to use.
65     // This does not necessarily correspond to the thread's initial stack size.
66     // A value of 0 indicates that the default maximum should be used.
67     size_t stack_size;
68 
69     // Specifies the initial thread priority.
70     ThreadPriority priority;
71   };
72 
73   // Constructor.
74   // name is a display string to identify the thread.
75   explicit Thread(const std::string& name);
76 
77   // Destroys the thread, stopping it if necessary.
78   //
79   // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
80   // guarantee Stop() is explicitly called before the subclass is destroyed).
81   // This is required to avoid a data race between the destructor modifying the
82   // vtable, and the thread's ThreadMain calling the virtual method Run().  It
83   // also ensures that the CleanUp() virtual method is called on the subclass
84   // before it is destructed.
85   ~Thread() override;
86 
87 #if defined(OS_WIN)
88   // Causes the thread to initialize COM.  This must be called before calling
89   // Start() or StartWithOptions().  If |use_mta| is false, the thread is also
90   // started with a TYPE_UI message loop.  It is an error to call
91   // init_com_with_mta(false) and then StartWithOptions() with any message loop
92   // type other than TYPE_UI.
init_com_with_mta(bool use_mta)93   void init_com_with_mta(bool use_mta) {
94     DCHECK(!message_loop_);
95     com_status_ = use_mta ? MTA : STA;
96   }
97 #endif
98 
99   // Starts the thread.  Returns true if the thread was successfully started;
100   // otherwise, returns false.  Upon successful return, the message_loop()
101   // getter will return non-null.
102   //
103   // Note: This function can't be called on Windows with the loader lock held;
104   // i.e. during a DllMain, global object construction or destruction, atexit()
105   // callback.
106   bool Start();
107 
108   // Starts the thread. Behaves exactly like Start in addition to allow to
109   // override the default options.
110   //
111   // Note: This function can't be called on Windows with the loader lock held;
112   // i.e. during a DllMain, global object construction or destruction, atexit()
113   // callback.
114   bool StartWithOptions(const Options& options);
115 
116   // Starts the thread and wait for the thread to start and run initialization
117   // before returning. It's same as calling Start() and then
118   // WaitUntilThreadStarted().
119   // Note that using this (instead of Start() or StartWithOptions() causes
120   // jank on the calling thread, should be used only in testing code.
121   bool StartAndWaitForTesting();
122 
123   // Blocks until the thread starts running. Called within StartAndWait().
124   // Note that calling this causes jank on the calling thread, must be used
125   // carefully for production code.
126   bool WaitUntilThreadStarted() const;
127 
128   // Signals the thread to exit and returns once the thread has exited.  After
129   // this method returns, the Thread object is completely reset and may be used
130   // as if it were newly constructed (i.e., Start may be called again).
131   //
132   // Stop may be called multiple times and is simply ignored if the thread is
133   // already stopped.
134   //
135   // NOTE: If you are a consumer of Thread, it is not necessary to call this
136   // before deleting your Thread objects, as the destructor will do it.
137   // IF YOU ARE A SUBCLASS OF Thread, YOU MUST CALL THIS IN YOUR DESTRUCTOR.
138   void Stop();
139 
140   // Signals the thread to exit in the near future.
141   //
142   // WARNING: This function is not meant to be commonly used. Use at your own
143   // risk. Calling this function will cause message_loop() to become invalid in
144   // the near future. This function was created to workaround a specific
145   // deadlock on Windows with printer worker thread. In any other case, Stop()
146   // should be used.
147   //
148   // StopSoon should not be called multiple times as it is risky to do so. It
149   // could cause a timing issue in message_loop() access. Call Stop() to reset
150   // the thread object once it is known that the thread has quit.
151   void StopSoon();
152 
153   // Returns the message loop for this thread.  Use the MessageLoop's
154   // PostTask methods to execute code on the thread.  This only returns
155   // non-null after a successful call to Start.  After Stop has been called,
156   // this will return nullptr.
157   //
158   // NOTE: You must not call this MessageLoop's Quit method directly.  Use
159   // the Thread's Stop method instead.
160   //
message_loop()161   MessageLoop* message_loop() const { return message_loop_; }
162 
163   // Returns a TaskRunner for this thread. Use the TaskRunner's PostTask
164   // methods to execute code on the thread. Returns nullptr if the thread is not
165   // running (e.g. before Start or after Stop have been called). Callers can
166   // hold on to this even after the thread is gone; in this situation, attempts
167   // to PostTask() will fail.
task_runner()168   scoped_refptr<SingleThreadTaskRunner> task_runner() const {
169     return message_loop_ ? message_loop_->task_runner() : nullptr;
170   }
171 
172   // Returns the name of this thread (for display in debugger too).
thread_name()173   const std::string& thread_name() const { return name_; }
174 
175   // The native thread handle.
thread_handle()176   PlatformThreadHandle thread_handle() { return thread_; }
177 
178   // Returns the thread ID.  Should not be called before the first Start*()
179   // call.  Keeps on returning the same ID even after a Stop() call. The next
180   // Start*() call renews the ID.
181   //
182   // WARNING: This function will block if the thread hasn't started yet.
183   //
184   PlatformThreadId GetThreadId() const;
185 
186   // Returns true if the thread has been started, and not yet stopped.
187   bool IsRunning() const;
188 
189  protected:
190   // Called just prior to starting the message loop
Init()191   virtual void Init() {}
192 
193   // Called to start the message loop
194   virtual void Run(MessageLoop* message_loop);
195 
196   // Called just after the message loop ends
CleanUp()197   virtual void CleanUp() {}
198 
199   static void SetThreadWasQuitProperly(bool flag);
200   static bool GetThreadWasQuitProperly();
201 
set_message_loop(MessageLoop * message_loop)202   void set_message_loop(MessageLoop* message_loop) {
203     message_loop_ = message_loop;
204   }
205 
206  private:
207 #if defined(OS_WIN)
208   enum ComStatus {
209     NONE,
210     STA,
211     MTA,
212   };
213 #endif
214 
215   // PlatformThread::Delegate methods:
216   void ThreadMain() override;
217 
218 #if defined(OS_WIN)
219   // Whether this thread needs to initialize COM, and if so, in what mode.
220   ComStatus com_status_;
221 #endif
222 
223   // If true, we're in the middle of stopping, and shouldn't access
224   // |message_loop_|. It may non-nullptr and invalid.
225   // Should be written on the thread that created this thread. Also read data
226   // could be wrong on other threads.
227   bool stopping_;
228 
229   // True while inside of Run().
230   bool running_;
231   mutable base::Lock running_lock_;  // Protects |running_|.
232 
233   // The thread's handle.
234   PlatformThreadHandle thread_;
235   mutable base::Lock thread_lock_;  // Protects |thread_|.
236 
237   // The thread's id once it has started.
238   PlatformThreadId id_;
239   mutable WaitableEvent id_event_;  // Protects |id_|.
240 
241   // The thread's message loop.  Valid only while the thread is alive.  Set
242   // by the created thread.
243   MessageLoop* message_loop_;
244 
245   // Stores Options::timer_slack_ until the message loop has been bound to
246   // a thread.
247   TimerSlack message_loop_timer_slack_;
248 
249   // The name of the thread.  Used for debugging purposes.
250   std::string name_;
251 
252   // Signaled when the created thread gets ready to use the message loop.
253   mutable WaitableEvent start_event_;
254 
255   friend void ThreadQuitHelper();
256 
257   DISALLOW_COPY_AND_ASSIGN(Thread);
258 };
259 
260 }  // namespace base
261 
262 #endif  // BASE_THREADING_THREAD_H_
263