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