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 #include "base/threading/thread.h"
8 #include "base/lazy_instance.h"
9 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
10 #include "base/threading/thread_id_name_manager.h"
11 #include "base/threading/thread_local.h"
12 #include "base/threading/thread_restrictions.h"
13 #include "base/synchronization/waitable_event.h"
16 #include "base/win/scoped_com_initializer.h"
23 // We use this thread-local variable to record whether or not a thread exited
24 // because its Stop method was called. This allows us to catch cases where
25 // MessageLoop::QuitWhenIdle() is called directly, which is unexpected when
26 // using a Thread to setup and run a MessageLoop.
27 base::LazyInstance
<base::ThreadLocalBoolean
> lazy_tls_bool
=
28 LAZY_INSTANCE_INITIALIZER
;
32 // This is used to trigger the message loop to exit.
33 void ThreadQuitHelper() {
34 MessageLoop::current()->QuitWhenIdle();
35 Thread::SetThreadWasQuitProperly(true);
38 // Used to pass data to ThreadMain. This structure is allocated on the stack
39 // from within StartWithOptions.
40 struct Thread::StartupData
{
41 // We get away with a const reference here because of how we are allocated.
42 const Thread::Options
& options
;
44 // Used to synchronize thread startup.
47 explicit StartupData(const Options
& opt
)
49 event(false, false) {}
52 Thread::Options::Options()
53 : message_loop_type(MessageLoop::TYPE_DEFAULT
),
54 timer_slack(TIMER_SLACK_NONE
),
58 Thread::Options::Options(MessageLoop::Type type
,
60 : message_loop_type(type
),
61 timer_slack(TIMER_SLACK_NONE
),
65 Thread::Options::~Options() {
68 Thread::Thread(const std::string
& name
)
79 thread_id_(kInvalidThreadId
),
87 bool Thread::Start() {
90 if (com_status_
== STA
)
91 options
.message_loop_type
= MessageLoop::TYPE_UI
;
93 return StartWithOptions(options
);
96 bool Thread::StartWithOptions(const Options
& options
) {
97 DCHECK(!message_loop_
);
99 DCHECK((com_status_
!= STA
) ||
100 (options
.message_loop_type
== MessageLoop::TYPE_UI
));
103 SetThreadWasQuitProperly(false);
105 StartupData
startup_data(options
);
106 startup_data_
= &startup_data
;
108 if (!PlatformThread::Create(options
.stack_size
, this, &thread_
)) {
109 DLOG(ERROR
) << "failed to create thread";
110 startup_data_
= NULL
;
114 // Wait for the thread to start and initialize message_loop_
115 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
116 startup_data
.event
.Wait();
118 // set it to NULL so we don't keep a pointer to some object on the stack.
119 startup_data_
= NULL
;
122 DCHECK(message_loop_
);
126 void Thread::Stop() {
132 // Wait for the thread to exit.
134 // TODO(darin): Unfortunately, we need to keep message_loop_ around until
135 // the thread exits. Some consumers are abusing the API. Make them stop.
137 PlatformThread::Join(thread_
);
139 // The thread should NULL message_loop_ on exit.
140 DCHECK(!message_loop_
);
142 // The thread no longer needs to be joined.
148 void Thread::StopSoon() {
149 // We should only be called on the same thread that started us.
151 // Reading thread_id_ without a lock can lead to a benign data race
152 // with ThreadMain, so we annotate it to stay silent under ThreadSanitizer.
153 DCHECK_NE(ANNOTATE_UNPROTECTED_READ(thread_id_
), PlatformThread::CurrentId());
155 if (stopping_
|| !message_loop_
)
159 message_loop_
->PostTask(FROM_HERE
, base::Bind(&ThreadQuitHelper
));
162 bool Thread::IsRunning() const {
166 void Thread::SetPriority(ThreadPriority priority
) {
167 // The thread must be started (and id known) for this to be
168 // compatible with all platforms.
169 DCHECK_NE(thread_id_
, kInvalidThreadId
);
170 PlatformThread::SetThreadPriority(thread_
, priority
);
173 void Thread::Run(MessageLoop
* message_loop
) {
177 void Thread::SetThreadWasQuitProperly(bool flag
) {
178 lazy_tls_bool
.Pointer()->Set(flag
);
181 bool Thread::GetThreadWasQuitProperly() {
182 bool quit_properly
= true;
184 quit_properly
= lazy_tls_bool
.Pointer()->Get();
186 return quit_properly
;
189 void Thread::ThreadMain() {
191 // The message loop for this thread.
192 // Allocated on the heap to centralize any leak reports at this line.
193 scoped_ptr
<MessageLoop
> message_loop
;
194 if (!startup_data_
->options
.message_pump_factory
.is_null()) {
196 new MessageLoop(startup_data_
->options
.message_pump_factory
.Run()));
199 new MessageLoop(startup_data_
->options
.message_loop_type
));
202 // Complete the initialization of our Thread object.
203 thread_id_
= PlatformThread::CurrentId();
204 PlatformThread::SetName(name_
.c_str());
205 ANNOTATE_THREAD_NAME(name_
.c_str()); // Tell the name to race detector.
206 message_loop
->set_thread_name(name_
);
207 message_loop
->SetTimerSlack(startup_data_
->options
.timer_slack
);
208 message_loop_
= message_loop
.get();
211 scoped_ptr
<win::ScopedCOMInitializer
> com_initializer
;
212 if (com_status_
!= NONE
) {
213 com_initializer
.reset((com_status_
== STA
) ?
214 new win::ScopedCOMInitializer() :
215 new win::ScopedCOMInitializer(win::ScopedCOMInitializer::kMTA
));
219 // Let the thread do extra initialization.
220 // Let's do this before signaling we are started.
224 startup_data_
->event
.Signal();
225 // startup_data_ can't be touched anymore since the starting thread is now
231 // Let the thread do extra cleanup.
235 com_initializer
.reset();
238 // Assert that MessageLoop::Quit was called by ThreadQuitHelper.
239 DCHECK(GetThreadWasQuitProperly());
241 // We can't receive messages anymore.
242 message_loop_
= NULL
;