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/location.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 Thread::Options::Options()
40 : message_loop_type(MessageLoop::TYPE_DEFAULT
),
41 timer_slack(TIMER_SLACK_NONE
),
43 priority(ThreadPriority::NORMAL
) {
46 Thread::Options::Options(MessageLoop::Type type
,
48 : message_loop_type(type
),
49 timer_slack(TIMER_SLACK_NONE
),
51 priority(ThreadPriority::NORMAL
) {
54 Thread::Options::~Options() {
57 Thread::Thread(const std::string
& name
)
65 id_(kInvalidThreadId
),
66 id_event_(true, false),
67 message_loop_(nullptr),
68 message_loop_timer_slack_(TIMER_SLACK_NONE
),
70 start_event_(false, false) {
77 bool Thread::Start() {
80 if (com_status_
== STA
)
81 options
.message_loop_type
= MessageLoop::TYPE_UI
;
83 return StartWithOptions(options
);
86 bool Thread::StartWithOptions(const Options
& options
) {
87 DCHECK(!message_loop_
);
89 DCHECK((com_status_
!= STA
) ||
90 (options
.message_loop_type
== MessageLoop::TYPE_UI
));
93 // Reset |id_| here to support restarting the thread.
95 id_
= kInvalidThreadId
;
97 SetThreadWasQuitProperly(false);
99 MessageLoop::Type type
= options
.message_loop_type
;
100 if (!options
.message_pump_factory
.is_null())
101 type
= MessageLoop::TYPE_CUSTOM
;
103 message_loop_timer_slack_
= options
.timer_slack
;
104 scoped_ptr
<MessageLoop
> message_loop
= MessageLoop::CreateUnbound(
105 type
, options
.message_pump_factory
);
106 message_loop_
= message_loop
.get();
107 start_event_
.Reset();
109 // Hold the thread_lock_ while starting a new thread, so that we can make sure
110 // that thread_ is populated before the newly created thread accesses it.
112 AutoLock
lock(thread_lock_
);
113 if (!PlatformThread::CreateWithPriority(options
.stack_size
, this, &thread_
,
115 DLOG(ERROR
) << "failed to create thread";
116 message_loop_
= nullptr;
121 // The ownership of message_loop is managemed by the newly created thread
122 // within the ThreadMain.
123 ignore_result(message_loop
.release());
125 DCHECK(message_loop_
);
129 bool Thread::StartAndWaitForTesting() {
130 bool result
= Start();
133 WaitUntilThreadStarted();
137 bool Thread::WaitUntilThreadStarted() const {
140 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
145 void Thread::Stop() {
146 AutoLock
lock(thread_lock_
);
147 if (thread_
.is_null())
152 // Wait for the thread to exit.
154 // TODO(darin): Unfortunately, we need to keep message_loop_ around until
155 // the thread exits. Some consumers are abusing the API. Make them stop.
157 PlatformThread::Join(thread_
);
158 thread_
= base::PlatformThreadHandle();
160 // The thread should nullify message_loop_ on exit.
161 DCHECK(!message_loop_
);
166 void Thread::StopSoon() {
167 // We should only be called on the same thread that started us.
169 DCHECK_NE(GetThreadId(), PlatformThread::CurrentId());
171 if (stopping_
|| !message_loop_
)
175 task_runner()->PostTask(FROM_HERE
, base::Bind(&ThreadQuitHelper
));
178 PlatformThreadId
Thread::GetThreadId() const {
179 // If the thread is created but not started yet, wait for |id_| being ready.
180 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
185 bool Thread::IsRunning() const {
186 // If the thread's already started (i.e. message_loop_ is non-null) and
187 // not yet requested to stop (i.e. stopping_ is false) we can just return
188 // true. (Note that stopping_ is touched only on the same thread that
189 // starts / started the new thread so we need no locking here.)
190 if (message_loop_
&& !stopping_
)
192 // Otherwise check the running_ flag, which is set to true by the new thread
193 // only while it is inside Run().
194 AutoLock
lock(running_lock_
);
198 void Thread::Run(MessageLoop
* message_loop
) {
202 void Thread::SetThreadWasQuitProperly(bool flag
) {
203 lazy_tls_bool
.Pointer()->Set(flag
);
206 bool Thread::GetThreadWasQuitProperly() {
207 bool quit_properly
= true;
209 quit_properly
= lazy_tls_bool
.Pointer()->Get();
211 return quit_properly
;
214 void Thread::ThreadMain() {
215 // First, make GetThreadId() available to avoid deadlocks. It could be called
216 // any place in the following thread initialization code.
217 id_
= PlatformThread::CurrentId();
218 DCHECK_NE(kInvalidThreadId
, id_
);
221 // Complete the initialization of our Thread object.
222 PlatformThread::SetName(name_
.c_str());
223 ANNOTATE_THREAD_NAME(name_
.c_str()); // Tell the name to race detector.
225 // Lazily initialize the message_loop so that it can run on this thread.
226 DCHECK(message_loop_
);
227 scoped_ptr
<MessageLoop
> message_loop(message_loop_
);
228 message_loop_
->BindToCurrentThread();
229 message_loop_
->set_thread_name(name_
);
230 message_loop_
->SetTimerSlack(message_loop_timer_slack_
);
233 scoped_ptr
<win::ScopedCOMInitializer
> com_initializer
;
234 if (com_status_
!= NONE
) {
235 com_initializer
.reset((com_status_
== STA
) ?
236 new win::ScopedCOMInitializer() :
237 new win::ScopedCOMInitializer(win::ScopedCOMInitializer::kMTA
));
241 // Let the thread do extra initialization.
245 AutoLock
lock(running_lock_
);
249 start_event_
.Signal();
254 AutoLock
lock(running_lock_
);
258 // Let the thread do extra cleanup.
262 com_initializer
.reset();
265 // Assert that MessageLoop::Quit was called by ThreadQuitHelper.
266 DCHECK(GetThreadWasQuitProperly());
268 // We can't receive messages anymore.
269 // (The message loop is destructed at the end of this block)
270 message_loop_
= nullptr;