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 // TODO(eroman): Remove once crbug.com/465458 is solved.
99 tracked_objects::ScopedTracker
tracking_profile(
100 FROM_HERE_WITH_EXPLICIT_FUNCTION(
101 "465458 base::Thread::StartWithOptions"));
103 DCHECK(!message_loop_
);
105 DCHECK((com_status_
!= STA
) ||
106 (options
.message_loop_type
== MessageLoop::TYPE_UI
));
109 SetThreadWasQuitProperly(false);
111 StartupData
startup_data(options
);
112 startup_data_
= &startup_data
;
114 if (!PlatformThread::Create(options
.stack_size
, this, &thread_
)) {
115 DLOG(ERROR
) << "failed to create thread";
116 startup_data_
= NULL
;
120 // TODO(eroman): Remove once crbug.com/465458 is solved.
121 tracked_objects::ScopedTracker
tracking_profile_wait(
122 FROM_HERE_WITH_EXPLICIT_FUNCTION(
123 "465458 base::Thread::StartWithOptions (Wait)"));
125 // Wait for the thread to start and initialize message_loop_
126 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
127 startup_data
.event
.Wait();
129 // set it to NULL so we don't keep a pointer to some object on the stack.
130 startup_data_
= NULL
;
133 DCHECK(message_loop_
);
137 void Thread::Stop() {
143 // Wait for the thread to exit.
145 // TODO(darin): Unfortunately, we need to keep message_loop_ around until
146 // the thread exits. Some consumers are abusing the API. Make them stop.
148 PlatformThread::Join(thread_
);
150 // The thread should NULL message_loop_ on exit.
151 DCHECK(!message_loop_
);
153 // The thread no longer needs to be joined.
159 void Thread::StopSoon() {
160 // We should only be called on the same thread that started us.
162 // Reading thread_id_ without a lock can lead to a benign data race
163 // with ThreadMain, so we annotate it to stay silent under ThreadSanitizer.
164 DCHECK_NE(ANNOTATE_UNPROTECTED_READ(thread_id_
), PlatformThread::CurrentId());
166 if (stopping_
|| !message_loop_
)
170 message_loop_
->PostTask(FROM_HERE
, base::Bind(&ThreadQuitHelper
));
173 bool Thread::IsRunning() const {
177 void Thread::SetPriority(ThreadPriority priority
) {
178 // The thread must be started (and id known) for this to be
179 // compatible with all platforms.
180 DCHECK_NE(thread_id_
, kInvalidThreadId
);
181 PlatformThread::SetThreadPriority(thread_
, priority
);
184 void Thread::Run(MessageLoop
* message_loop
) {
188 void Thread::SetThreadWasQuitProperly(bool flag
) {
189 lazy_tls_bool
.Pointer()->Set(flag
);
192 bool Thread::GetThreadWasQuitProperly() {
193 bool quit_properly
= true;
195 quit_properly
= lazy_tls_bool
.Pointer()->Get();
197 return quit_properly
;
200 void Thread::ThreadMain() {
202 // The message loop for this thread.
203 // Allocated on the heap to centralize any leak reports at this line.
204 scoped_ptr
<MessageLoop
> message_loop
;
205 if (!startup_data_
->options
.message_pump_factory
.is_null()) {
207 new MessageLoop(startup_data_
->options
.message_pump_factory
.Run()));
210 new MessageLoop(startup_data_
->options
.message_loop_type
));
213 // Complete the initialization of our Thread object.
214 thread_id_
= PlatformThread::CurrentId();
215 PlatformThread::SetName(name_
.c_str());
216 ANNOTATE_THREAD_NAME(name_
.c_str()); // Tell the name to race detector.
217 message_loop
->set_thread_name(name_
);
218 message_loop
->SetTimerSlack(startup_data_
->options
.timer_slack
);
219 message_loop_
= message_loop
.get();
222 scoped_ptr
<win::ScopedCOMInitializer
> com_initializer
;
223 if (com_status_
!= NONE
) {
224 com_initializer
.reset((com_status_
== STA
) ?
225 new win::ScopedCOMInitializer() :
226 new win::ScopedCOMInitializer(win::ScopedCOMInitializer::kMTA
));
230 // Let the thread do extra initialization.
231 // Let's do this before signaling we are started.
235 startup_data_
->event
.Signal();
236 // startup_data_ can't be touched anymore since the starting thread is now
242 // Let the thread do extra cleanup.
246 com_initializer
.reset();
249 // Assert that MessageLoop::Quit was called by ThreadQuitHelper.
250 DCHECK(GetThreadWasQuitProperly());
252 // We can't receive messages anymore.
253 message_loop_
= NULL
;