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_
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/threading/platform_thread.h"
22 // A simple thread abstraction that establishes a MessageLoop on a new thread.
23 // The consumer uses the MessageLoop of the thread to cause code to execute on
24 // the thread. When this object is destroyed the thread is terminated. All
25 // pending tasks queued on the thread's message loop will run to completion
26 // before the thread is terminated.
28 // WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
30 // After the thread is stopped, the destruction sequence is:
32 // (1) Thread::CleanUp()
33 // (2) MessageLoop::~MessageLoop
34 // (3.b) MessageLoop::DestructionObserver::WillDestroyCurrentMessageLoop
35 class BASE_EXPORT Thread
: PlatformThread::Delegate
{
37 struct BASE_EXPORT Options
{
38 typedef Callback
<scoped_ptr
<MessagePump
>()> MessagePumpFactory
;
41 Options(MessageLoop::Type type
, size_t size
);
44 // Specifies the type of message loop that will be allocated on the thread.
45 // This is ignored if message_pump_factory.is_null() is false.
46 MessageLoop::Type message_loop_type
;
48 // Specify timer slack for thread message loop.
49 TimerSlack timer_slack
;
51 // Used to create the MessagePump for the MessageLoop. The callback is Run()
52 // on the thread. If message_pump_factory.is_null(), then a MessagePump
53 // appropriate for |message_loop_type| is created. Setting this forces the
54 // MessageLoop::Type to TYPE_CUSTOM.
55 MessagePumpFactory message_pump_factory
;
57 // Specifies the maximum stack size that the thread is allowed to use.
58 // This does not necessarily correspond to the thread's initial stack size.
59 // A value of 0 indicates that the default maximum should be used.
64 // name is a display string to identify the thread.
65 explicit Thread(const std::string
& name
);
67 // Destroys the thread, stopping it if necessary.
69 // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
70 // guarantee Stop() is explicitly called before the subclass is destroyed).
71 // This is required to avoid a data race between the destructor modifying the
72 // vtable, and the thread's ThreadMain calling the virtual method Run(). It
73 // also ensures that the CleanUp() virtual method is called on the subclass
74 // before it is destructed.
78 // Causes the thread to initialize COM. This must be called before calling
79 // Start() or StartWithOptions(). If |use_mta| is false, the thread is also
80 // started with a TYPE_UI message loop. It is an error to call
81 // init_com_with_mta(false) and then StartWithOptions() with any message loop
82 // type other than TYPE_UI.
83 void init_com_with_mta(bool use_mta
) {
85 com_status_
= use_mta
? MTA
: STA
;
89 // Starts the thread. Returns true if the thread was successfully started;
90 // otherwise, returns false. Upon successful return, the message_loop()
91 // getter will return non-null.
93 // Note: This function can't be called on Windows with the loader lock held;
94 // i.e. during a DllMain, global object construction or destruction, atexit()
98 // Starts the thread. Behaves exactly like Start in addition to allow to
99 // override the default options.
101 // Note: This function can't be called on Windows with the loader lock held;
102 // i.e. during a DllMain, global object construction or destruction, atexit()
104 bool StartWithOptions(const Options
& options
);
106 // Signals the thread to exit and returns once the thread has exited. After
107 // this method returns, the Thread object is completely reset and may be used
108 // as if it were newly constructed (i.e., Start may be called again).
110 // Stop may be called multiple times and is simply ignored if the thread is
113 // NOTE: If you are a consumer of Thread, it is not necessary to call this
114 // before deleting your Thread objects, as the destructor will do it.
115 // IF YOU ARE A SUBCLASS OF Thread, YOU MUST CALL THIS IN YOUR DESTRUCTOR.
118 // Signals the thread to exit in the near future.
120 // WARNING: This function is not meant to be commonly used. Use at your own
121 // risk. Calling this function will cause message_loop() to become invalid in
122 // the near future. This function was created to workaround a specific
123 // deadlock on Windows with printer worker thread. In any other case, Stop()
126 // StopSoon should not be called multiple times as it is risky to do so. It
127 // could cause a timing issue in message_loop() access. Call Stop() to reset
128 // the thread object once it is known that the thread has quit.
131 // Returns the message loop for this thread. Use the MessageLoop's
132 // PostTask methods to execute code on the thread. This only returns
133 // non-null after a successful call to Start. After Stop has been called,
134 // this will return NULL.
136 // NOTE: You must not call this MessageLoop's Quit method directly. Use
137 // the Thread's Stop method instead.
139 MessageLoop
* message_loop() const { return message_loop_
; }
141 // Returns a MessageLoopProxy for this thread. Use the MessageLoopProxy's
142 // PostTask methods to execute code on the thread. Returns NULL if the thread
143 // is not running (e.g. before Start or after Stop have been called). Callers
144 // can hold on to this even after the thread is gone; in this situation,
145 // attempts to PostTask() will fail.
147 // Note: This method is deprecated. Callers should call task_runner() instead
148 // and use the TaskRunner interfaces for safely interfacing with the Thread.
149 scoped_refptr
<MessageLoopProxy
> message_loop_proxy() const {
150 return message_loop_
? message_loop_
->message_loop_proxy() : NULL
;
153 // Returns a TaskRunner for this thread. Use the TaskRunner's PostTask
154 // methods to execute code on the thread. Returns NULL if the thread is not
155 // running (e.g. before Start or after Stop have been called). Callers can
156 // hold on to this even after the thread is gone; in this situation, attempts
157 // to PostTask() will fail.
158 scoped_refptr
<SingleThreadTaskRunner
> task_runner() const {
159 return message_loop_
->task_runner();
162 // Returns the name of this thread (for display in debugger too).
163 const std::string
& thread_name() const { return name_
; }
165 // The native thread handle.
166 PlatformThreadHandle
thread_handle() { return thread_
; }
169 PlatformThreadId
thread_id() const { return thread_id_
; }
171 // Returns true if the thread has been started, and not yet stopped.
172 bool IsRunning() const;
174 // Sets the thread priority. The thread must already be started.
175 void SetPriority(ThreadPriority priority
);
178 // Called just prior to starting the message loop
179 virtual void Init() {}
181 // Called to start the message loop
182 virtual void Run(MessageLoop
* message_loop
);
184 // Called just after the message loop ends
185 virtual void CleanUp() {}
187 static void SetThreadWasQuitProperly(bool flag
);
188 static bool GetThreadWasQuitProperly();
190 void set_message_loop(MessageLoop
* message_loop
) {
191 message_loop_
= message_loop
;
203 // PlatformThread::Delegate methods:
204 void ThreadMain() override
;
207 // Whether this thread needs to initialize COM, and if so, in what mode.
208 ComStatus com_status_
;
211 // Whether we successfully started the thread.
214 // If true, we're in the middle of stopping, and shouldn't access
215 // |message_loop_|. It may non-NULL and invalid.
218 // True while inside of Run().
221 // Used to pass data to ThreadMain.
223 StartupData
* startup_data_
;
225 // The thread's handle.
226 PlatformThreadHandle thread_
;
228 // The thread's message loop. Valid only while the thread is alive. Set
229 // by the created thread.
230 MessageLoop
* message_loop_
;
233 PlatformThreadId thread_id_
;
235 // The name of the thread. Used for debugging purposes.
238 friend void ThreadQuitHelper();
240 DISALLOW_COPY_AND_ASSIGN(Thread
);
245 #endif // BASE_THREADING_THREAD_H_