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/profiler/scoped_tracker.h"
11 #include "base/synchronization/waitable_event.h"
12 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
13 #include "base/threading/thread_id_name_manager.h"
14 #include "base/threading/thread_local.h"
15 #include "base/threading/thread_restrictions.h"
18 #include "base/win/scoped_com_initializer.h"
25 // We use this thread-local variable to record whether or not a thread exited
26 // because its Stop method was called. This allows us to catch cases where
27 // MessageLoop::QuitWhenIdle() is called directly, which is unexpected when
28 // using a Thread to setup and run a MessageLoop.
29 base::LazyInstance
<base::ThreadLocalBoolean
> lazy_tls_bool
=
30 LAZY_INSTANCE_INITIALIZER
;
34 // This is used to trigger the message loop to exit.
35 void ThreadQuitHelper() {
36 MessageLoop::current()->QuitWhenIdle();
37 Thread::SetThreadWasQuitProperly(true);
40 Thread::Options::Options()
41 : message_loop_type(MessageLoop::TYPE_DEFAULT
),
42 timer_slack(TIMER_SLACK_NONE
),
44 priority(ThreadPriority::NORMAL
) {
47 Thread::Options::Options(MessageLoop::Type type
,
49 : message_loop_type(type
),
50 timer_slack(TIMER_SLACK_NONE
),
52 priority(ThreadPriority::NORMAL
) {
55 Thread::Options::~Options() {
58 Thread::Thread(const std::string
& name
)
66 id_(kInvalidThreadId
),
67 id_event_(true, false),
68 message_loop_(nullptr),
69 message_loop_timer_slack_(TIMER_SLACK_NONE
),
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(new WaitableEvent(false, false));
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;
117 start_event_
.reset();
122 // The ownership of message_loop is managemed by the newly created thread
123 // within the ThreadMain.
124 ignore_result(message_loop
.release());
126 DCHECK(message_loop_
);
130 bool Thread::StartAndWaitForTesting() {
131 bool result
= Start();
134 WaitUntilThreadStarted();
138 bool Thread::WaitUntilThreadStarted() {
141 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
142 start_event_
->Wait();
146 void Thread::Stop() {
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_
);
159 // The thread should NULL message_loop_ on exit.
160 DCHECK(!message_loop_
);
162 // The thread no longer needs to be joined.
163 start_event_
.reset();
168 void Thread::StopSoon() {
169 // We should only be called on the same thread that started us.
171 DCHECK_NE(GetThreadId(), PlatformThread::CurrentId());
173 if (stopping_
|| !message_loop_
)
177 task_runner()->PostTask(FROM_HERE
, base::Bind(&ThreadQuitHelper
));
180 PlatformThreadId
Thread::GetThreadId() const {
181 // If the thread is created but not started yet, wait for |id_| being ready.
182 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
183 // TODO(toyoshim): Remove this after a few days (crbug.com/495097)
184 tracked_objects::ScopedTracker
tracking_profile(
185 FROM_HERE_WITH_EXPLICIT_FUNCTION(
186 "495097 base::Thread::GetThreadId"));
191 bool Thread::IsRunning() const {
192 // If the thread's already started (i.e. message_loop_ is non-null) and
193 // not yet requested to stop (i.e. stopping_ is false) we can just return
194 // true. (Note that stopping_ is touched only on the same thread that
195 // starts / started the new thread so we need no locking here.)
196 if (message_loop_
&& !stopping_
)
198 // Otherwise check the running_ flag, which is set to true by the new thread
199 // only while it is inside Run().
200 AutoLock
lock(running_lock_
);
204 void Thread::Run(MessageLoop
* message_loop
) {
208 void Thread::SetThreadWasQuitProperly(bool flag
) {
209 lazy_tls_bool
.Pointer()->Set(flag
);
212 bool Thread::GetThreadWasQuitProperly() {
213 bool quit_properly
= true;
215 quit_properly
= lazy_tls_bool
.Pointer()->Get();
217 return quit_properly
;
220 void Thread::ThreadMain() {
221 // First, make GetThreadId() available to avoid deadlocks. It could be called
222 // any place in the following thread initialization code.
223 id_
= PlatformThread::CurrentId();
224 DCHECK_NE(kInvalidThreadId
, id_
);
227 // Complete the initialization of our Thread object.
228 PlatformThread::SetName(name_
.c_str());
229 ANNOTATE_THREAD_NAME(name_
.c_str()); // Tell the name to race detector.
231 // Lazily initialize the message_loop so that it can run on this thread.
232 DCHECK(message_loop_
);
233 scoped_ptr
<MessageLoop
> message_loop(message_loop_
);
234 message_loop_
->BindToCurrentThread();
235 message_loop_
->set_thread_name(name_
);
236 message_loop_
->SetTimerSlack(message_loop_timer_slack_
);
239 scoped_ptr
<win::ScopedCOMInitializer
> com_initializer
;
240 if (com_status_
!= NONE
) {
241 com_initializer
.reset((com_status_
== STA
) ?
242 new win::ScopedCOMInitializer() :
243 new win::ScopedCOMInitializer(win::ScopedCOMInitializer::kMTA
));
247 // Let the thread do extra initialization.
251 AutoLock
lock(running_lock_
);
255 start_event_
->Signal();
260 AutoLock
lock(running_lock_
);
264 // Let the thread do extra cleanup.
268 com_initializer
.reset();
271 // Assert that MessageLoop::Quit was called by ThreadQuitHelper.
272 DCHECK(GetThreadWasQuitProperly());
274 // We can't receive messages anymore.
275 // (The message loop is destructed at the end of this block)
276 message_loop_
= NULL
;