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/profiler/scoped_tracker.h"
10 #include "base/synchronization/waitable_event.h"
11 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
12 #include "base/threading/thread_id_name_manager.h"
13 #include "base/threading/thread_local.h"
14 #include "base/threading/thread_restrictions.h"
17 #include "base/win/scoped_com_initializer.h"
24 // We use this thread-local variable to record whether or not a thread exited
25 // because its Stop method was called. This allows us to catch cases where
26 // MessageLoop::QuitWhenIdle() is called directly, which is unexpected when
27 // using a Thread to setup and run a MessageLoop.
28 base::LazyInstance
<base::ThreadLocalBoolean
> lazy_tls_bool
=
29 LAZY_INSTANCE_INITIALIZER
;
33 // This is used to trigger the message loop to exit.
34 void ThreadQuitHelper() {
35 MessageLoop::current()->QuitWhenIdle();
36 Thread::SetThreadWasQuitProperly(true);
39 // Used to pass data to ThreadMain. This structure is allocated on the stack
40 // from within StartWithOptions.
41 struct Thread::StartupData
{
42 // We get away with a const reference here because of how we are allocated.
43 const Thread::Options
& options
;
45 // Used to synchronize thread startup.
48 explicit StartupData(const Options
& opt
)
50 event(false, false) {}
53 Thread::Options::Options()
54 : message_loop_type(MessageLoop::TYPE_DEFAULT
),
55 timer_slack(TIMER_SLACK_NONE
),
59 Thread::Options::Options(MessageLoop::Type type
,
61 : message_loop_type(type
),
62 timer_slack(TIMER_SLACK_NONE
),
66 Thread::Options::~Options() {
69 Thread::Thread(const std::string
& name
)
80 thread_id_(kInvalidThreadId
),
88 bool Thread::Start() {
91 if (com_status_
== STA
)
92 options
.message_loop_type
= MessageLoop::TYPE_UI
;
94 return StartWithOptions(options
);
97 bool Thread::StartWithOptions(const Options
& options
) {
98 DCHECK(!message_loop_
);
100 DCHECK((com_status_
!= STA
) ||
101 (options
.message_loop_type
== MessageLoop::TYPE_UI
));
104 SetThreadWasQuitProperly(false);
106 StartupData
startup_data(options
);
107 startup_data_
= &startup_data
;
109 if (!PlatformThread::Create(options
.stack_size
, this, &thread_
)) {
110 DLOG(ERROR
) << "failed to create thread";
111 startup_data_
= NULL
;
115 // TODO(kinuko): Remove once crbug.com/465458 is solved.
116 tracked_objects::ScopedTracker
tracking_profile_wait(
117 FROM_HERE_WITH_EXPLICIT_FUNCTION(
118 "465458 base::Thread::StartWithOptions (Wait)"));
120 // Wait for the thread to start and initialize message_loop_
121 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
122 startup_data
.event
.Wait();
124 // set it to NULL so we don't keep a pointer to some object on the stack.
125 startup_data_
= NULL
;
128 DCHECK(message_loop_
);
132 void Thread::Stop() {
138 // Wait for the thread to exit.
140 // TODO(darin): Unfortunately, we need to keep message_loop_ around until
141 // the thread exits. Some consumers are abusing the API. Make them stop.
143 PlatformThread::Join(thread_
);
145 // The thread should NULL message_loop_ on exit.
146 DCHECK(!message_loop_
);
148 // The thread no longer needs to be joined.
154 void Thread::StopSoon() {
155 // We should only be called on the same thread that started us.
157 // Reading thread_id_ without a lock can lead to a benign data race
158 // with ThreadMain, so we annotate it to stay silent under ThreadSanitizer.
159 DCHECK_NE(ANNOTATE_UNPROTECTED_READ(thread_id_
), PlatformThread::CurrentId());
161 if (stopping_
|| !message_loop_
)
165 message_loop_
->PostTask(FROM_HERE
, base::Bind(&ThreadQuitHelper
));
168 bool Thread::IsRunning() const {
172 void Thread::SetPriority(ThreadPriority priority
) {
173 // The thread must be started (and id known) for this to be
174 // compatible with all platforms.
175 DCHECK_NE(thread_id_
, kInvalidThreadId
);
176 PlatformThread::SetThreadPriority(thread_
, priority
);
179 void Thread::Run(MessageLoop
* message_loop
) {
183 void Thread::SetThreadWasQuitProperly(bool flag
) {
184 lazy_tls_bool
.Pointer()->Set(flag
);
187 bool Thread::GetThreadWasQuitProperly() {
188 bool quit_properly
= true;
190 quit_properly
= lazy_tls_bool
.Pointer()->Get();
192 return quit_properly
;
195 void Thread::ThreadMain() {
197 // The message loop for this thread.
198 // Allocated on the heap to centralize any leak reports at this line.
199 scoped_ptr
<MessageLoop
> message_loop
;
200 if (!startup_data_
->options
.message_pump_factory
.is_null()) {
202 new MessageLoop(startup_data_
->options
.message_pump_factory
.Run()));
205 new MessageLoop(startup_data_
->options
.message_loop_type
));
208 // Complete the initialization of our Thread object.
209 thread_id_
= PlatformThread::CurrentId();
210 PlatformThread::SetName(name_
.c_str());
211 ANNOTATE_THREAD_NAME(name_
.c_str()); // Tell the name to race detector.
212 message_loop
->set_thread_name(name_
);
213 message_loop
->SetTimerSlack(startup_data_
->options
.timer_slack
);
214 message_loop_
= message_loop
.get();
217 scoped_ptr
<win::ScopedCOMInitializer
> com_initializer
;
218 if (com_status_
!= NONE
) {
219 com_initializer
.reset((com_status_
== STA
) ?
220 new win::ScopedCOMInitializer() :
221 new win::ScopedCOMInitializer(win::ScopedCOMInitializer::kMTA
));
225 // Let the thread do extra initialization.
226 // Let's do this before signaling we are started.
230 startup_data_
->event
.Signal();
231 // startup_data_ can't be touched anymore since the starting thread is now
237 // Let the thread do extra cleanup.
241 com_initializer
.reset();
244 // Assert that MessageLoop::Quit was called by ThreadQuitHelper.
245 DCHECK(GetThreadWasQuitProperly());
247 // We can't receive messages anymore.
248 message_loop_
= NULL
;