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 message_loop_(nullptr),
66 message_loop_timer_slack_(TIMER_SLACK_NONE
),
74 bool Thread::Start() {
77 if (com_status_
== STA
)
78 options
.message_loop_type
= MessageLoop::TYPE_UI
;
80 return StartWithOptions(options
);
83 bool Thread::StartWithOptions(const Options
& options
) {
84 DCHECK(!message_loop_
);
86 DCHECK((com_status_
!= STA
) ||
87 (options
.message_loop_type
== MessageLoop::TYPE_UI
));
90 SetThreadWasQuitProperly(false);
92 MessageLoop::Type type
= options
.message_loop_type
;
93 if (!options
.message_pump_factory
.is_null())
94 type
= MessageLoop::TYPE_CUSTOM
;
96 message_loop_timer_slack_
= options
.timer_slack
;
97 scoped_ptr
<MessageLoop
> message_loop
= MessageLoop::CreateUnbound(
98 type
, options
.message_pump_factory
);
99 message_loop_
= message_loop
.get();
100 start_event_
.reset(new WaitableEvent(false, false));
102 // Hold the thread_lock_ while starting a new thread, so that we can make sure
103 // that thread_ is populated before the newly created thread accesses it.
105 AutoLock
lock(thread_lock_
);
106 if (!PlatformThread::CreateWithPriority(options
.stack_size
, this, &thread_
,
108 DLOG(ERROR
) << "failed to create thread";
109 message_loop_
= nullptr;
110 start_event_
.reset();
115 // The ownership of message_loop is managemed by the newly created thread
116 // within the ThreadMain.
117 ignore_result(message_loop
.release());
119 DCHECK(message_loop_
);
123 bool Thread::StartAndWaitForTesting() {
124 bool result
= Start();
127 WaitUntilThreadStarted();
131 bool Thread::WaitUntilThreadStarted() {
134 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
135 start_event_
->Wait();
139 void Thread::Stop() {
145 // Wait for the thread to exit.
147 // TODO(darin): Unfortunately, we need to keep message_loop_ around until
148 // the thread exits. Some consumers are abusing the API. Make them stop.
150 PlatformThread::Join(thread_
);
152 // The thread should NULL message_loop_ on exit.
153 DCHECK(!message_loop_
);
155 // The thread no longer needs to be joined.
156 start_event_
.reset();
161 void Thread::StopSoon() {
162 // We should only be called on the same thread that started us.
164 DCHECK_NE(thread_id(), PlatformThread::CurrentId());
166 if (stopping_
|| !message_loop_
)
170 task_runner()->PostTask(FROM_HERE
, base::Bind(&ThreadQuitHelper
));
173 PlatformThreadId
Thread::thread_id() const {
174 AutoLock
lock(thread_lock_
);
178 bool Thread::IsRunning() const {
179 // If the thread's already started (i.e. message_loop_ is non-null) and
180 // not yet requested to stop (i.e. stopping_ is false) we can just return
181 // true. (Note that stopping_ is touched only on the same thread that
182 // starts / started the new thread so we need no locking here.)
183 if (message_loop_
&& !stopping_
)
185 // Otherwise check the running_ flag, which is set to true by the new thread
186 // only while it is inside Run().
187 AutoLock
lock(running_lock_
);
191 void Thread::Run(MessageLoop
* message_loop
) {
195 void Thread::SetThreadWasQuitProperly(bool flag
) {
196 lazy_tls_bool
.Pointer()->Set(flag
);
199 bool Thread::GetThreadWasQuitProperly() {
200 bool quit_properly
= true;
202 quit_properly
= lazy_tls_bool
.Pointer()->Get();
204 return quit_properly
;
207 void Thread::ThreadMain() {
208 // Complete the initialization of our Thread object.
209 PlatformThread::SetName(name_
.c_str());
210 ANNOTATE_THREAD_NAME(name_
.c_str()); // Tell the name to race detector.
212 // Lazily initialize the message_loop so that it can run on this thread.
213 DCHECK(message_loop_
);
214 scoped_ptr
<MessageLoop
> message_loop(message_loop_
);
215 message_loop_
->BindToCurrentThread();
216 message_loop_
->set_thread_name(name_
);
217 message_loop_
->SetTimerSlack(message_loop_timer_slack_
);
220 scoped_ptr
<win::ScopedCOMInitializer
> com_initializer
;
221 if (com_status_
!= NONE
) {
222 com_initializer
.reset((com_status_
== STA
) ?
223 new win::ScopedCOMInitializer() :
224 new win::ScopedCOMInitializer(win::ScopedCOMInitializer::kMTA
));
228 // Make sure the thread_id() returns current thread.
229 // (This internally acquires lock against PlatformThread::Create)
230 DCHECK_EQ(thread_id(), PlatformThread::CurrentId());
232 // Let the thread do extra initialization.
236 AutoLock
lock(running_lock_
);
240 start_event_
->Signal();
245 AutoLock
lock(running_lock_
);
249 // Let the thread do extra cleanup.
253 com_initializer
.reset();
256 // Assert that MessageLoop::Quit was called by ThreadQuitHelper.
257 DCHECK(GetThreadWasQuitProperly());
259 // We can't receive messages anymore.
260 // (The message loop is destructed at the end of this block)
261 message_loop_
= NULL
;