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/message_loop/message_loop.h"
12 #include "base/message_loop/message_loop_proxy.h"
13 #include "base/threading/platform_thread.h"
17 // A simple thread abstraction that establishes a MessageLoop on a new thread.
18 // The consumer uses the MessageLoop of the thread to cause code to execute on
19 // the thread. When this object is destroyed the thread is terminated. All
20 // pending tasks queued on the thread's message loop will run to completion
21 // before the thread is terminated.
23 // WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
25 // After the thread is stopped, the destruction sequence is:
27 // (1) Thread::CleanUp()
28 // (2) MessageLoop::~MessageLoop
29 // (3.b) MessageLoop::DestructionObserver::WillDestroyCurrentMessageLoop
30 class BASE_EXPORT Thread
: PlatformThread::Delegate
{
33 Options() : message_loop_type(MessageLoop::TYPE_DEFAULT
), stack_size(0) {}
34 Options(MessageLoop::Type type
, size_t size
)
35 : message_loop_type(type
), stack_size(size
) {}
37 // Specifies the type of message loop that will be allocated on the thread.
38 MessageLoop::Type message_loop_type
;
40 // Specifies the maximum stack size that the thread is allowed to use.
41 // This does not necessarily correspond to the thread's initial stack size.
42 // A value of 0 indicates that the default maximum should be used.
47 // name is a display string to identify the thread.
48 explicit Thread(const char* name
);
50 // Destroys the thread, stopping it if necessary.
52 // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
53 // guarantee Stop() is explicitly called before the subclass is destroyed).
54 // This is required to avoid a data race between the destructor modifying the
55 // vtable, and the thread's ThreadMain calling the virtual method Run(). It
56 // also ensures that the CleanUp() virtual method is called on the subclass
57 // before it is destructed.
61 // Causes the thread to initialize COM. This must be called before calling
62 // Start() or StartWithOptions(). If |use_mta| is false, the thread is also
63 // started with a TYPE_UI message loop. It is an error to call
64 // init_com_with_mta(false) and then StartWithOptions() with any message loop
65 // type other than TYPE_UI.
66 void init_com_with_mta(bool use_mta
) {
68 com_status_
= use_mta
? MTA
: STA
;
72 // Starts the thread. Returns true if the thread was successfully started;
73 // otherwise, returns false. Upon successful return, the message_loop()
74 // getter will return non-null.
76 // Note: This function can't be called on Windows with the loader lock held;
77 // i.e. during a DllMain, global object construction or destruction, atexit()
81 // Starts the thread. Behaves exactly like Start in addition to allow to
82 // override the default options.
84 // Note: This function can't be called on Windows with the loader lock held;
85 // i.e. during a DllMain, global object construction or destruction, atexit()
87 bool StartWithOptions(const Options
& options
);
89 // Signals the thread to exit and returns once the thread has exited. After
90 // this method returns, the Thread object is completely reset and may be used
91 // as if it were newly constructed (i.e., Start may be called again).
93 // Stop may be called multiple times and is simply ignored if the thread is
96 // NOTE: If you are a consumer of Thread, it is not necessary to call this
97 // before deleting your Thread objects, as the destructor will do it.
98 // IF YOU ARE A SUBCLASS OF Thread, YOU MUST CALL THIS IN YOUR DESTRUCTOR.
101 // Signals the thread to exit in the near future.
103 // WARNING: This function is not meant to be commonly used. Use at your own
104 // risk. Calling this function will cause message_loop() to become invalid in
105 // the near future. This function was created to workaround a specific
106 // deadlock on Windows with printer worker thread. In any other case, Stop()
109 // StopSoon should not be called multiple times as it is risky to do so. It
110 // could cause a timing issue in message_loop() access. Call Stop() to reset
111 // the thread object once it is known that the thread has quit.
114 // Returns the message loop for this thread. Use the MessageLoop's
115 // PostTask methods to execute code on the thread. This only returns
116 // non-null after a successful call to Start. After Stop has been called,
117 // this will return NULL.
119 // NOTE: You must not call this MessageLoop's Quit method directly. Use
120 // the Thread's Stop method instead.
122 MessageLoop
* message_loop() const { return message_loop_
; }
124 // Returns a MessageLoopProxy for this thread. Use the MessageLoopProxy's
125 // PostTask methods to execute code on the thread. This only returns
126 // non-NULL after a successful call to Start. After Stop has been called,
127 // this will return NULL. Callers can hold on to this even after the thread
129 scoped_refptr
<MessageLoopProxy
> message_loop_proxy() const {
130 return message_loop_
? message_loop_
->message_loop_proxy() : NULL
;
133 // Returns the name of this thread (for display in debugger too).
134 const std::string
& thread_name() const { return name_
; }
136 // The native thread handle.
137 PlatformThreadHandle
thread_handle() { return thread_
; }
140 PlatformThreadId
thread_id() const { return thread_id_
; }
142 // Returns true if the thread has been started, and not yet stopped.
143 bool IsRunning() const;
145 // Sets the thread priority. The thread must already be started.
146 void SetPriority(ThreadPriority priority
);
149 // Called just prior to starting the message loop
150 virtual void Init() {}
152 // Called to start the message loop
153 virtual void Run(MessageLoop
* message_loop
);
155 // Called just after the message loop ends
156 virtual void CleanUp() {}
158 static void SetThreadWasQuitProperly(bool flag
);
159 static bool GetThreadWasQuitProperly();
161 void set_message_loop(MessageLoop
* message_loop
) {
162 message_loop_
= message_loop
;
174 // PlatformThread::Delegate methods:
175 virtual void ThreadMain() OVERRIDE
;
178 // Whether this thread needs to initialize COM, and if so, in what mode.
179 ComStatus com_status_
;
182 // Whether we successfully started the thread.
185 // If true, we're in the middle of stopping, and shouldn't access
186 // |message_loop_|. It may non-NULL and invalid.
189 // True while inside of Run().
192 // Used to pass data to ThreadMain.
194 StartupData
* startup_data_
;
196 // The thread's handle.
197 PlatformThreadHandle thread_
;
199 // The thread's message loop. Valid only while the thread is alive. Set
200 // by the created thread.
201 MessageLoop
* message_loop_
;
204 PlatformThreadId thread_id_
;
206 // The name of the thread. Used for debugging purposes.
209 friend void ThreadQuitHelper();
211 DISALLOW_COPY_AND_ASSIGN(Thread
);
216 #endif // BASE_THREADING_THREAD_H_