[Android WebView] Fix webview perf bot switchover to use org.chromium.webview_shell...
[chromium-blink-merge.git] / base / threading / thread.cc
blob63b07cbce6935bce5dcc203e289b4b8d58dc2af7
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"
7 #include "base/bind.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"
16 #if defined(OS_WIN)
17 #include "base/win/scoped_com_initializer.h"
18 #endif
20 namespace base {
22 namespace {
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;
31 } // namespace
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),
42 stack_size(0),
43 priority(ThreadPriority::NORMAL) {
46 Thread::Options::Options(MessageLoop::Type type,
47 size_t size)
48 : message_loop_type(type),
49 timer_slack(TIMER_SLACK_NONE),
50 stack_size(size),
51 priority(ThreadPriority::NORMAL) {
54 Thread::Options::~Options() {
57 Thread::Thread(const std::string& name)
59 #if defined(OS_WIN)
60 com_status_(NONE),
61 #endif
62 stopping_(false),
63 running_(false),
64 thread_(0),
65 message_loop_(nullptr),
66 message_loop_timer_slack_(TIMER_SLACK_NONE),
67 name_(name) {
70 Thread::~Thread() {
71 Stop();
74 bool Thread::Start() {
75 Options options;
76 #if defined(OS_WIN)
77 if (com_status_ == STA)
78 options.message_loop_type = MessageLoop::TYPE_UI;
79 #endif
80 return StartWithOptions(options);
83 bool Thread::StartWithOptions(const Options& options) {
84 DCHECK(!message_loop_);
85 #if defined(OS_WIN)
86 DCHECK((com_status_ != STA) ||
87 (options.message_loop_type == MessageLoop::TYPE_UI));
88 #endif
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 message_loop_ = new MessageLoop(type, options.message_pump_factory);
99 start_event_.reset(new WaitableEvent(false, false));
101 // Hold the thread_lock_ while starting a new thread, so that we can make sure
102 // that thread_ is populated before the newly created thread accesses it.
104 AutoLock lock(thread_lock_);
105 bool created;
106 if (options.priority == ThreadPriority::NORMAL) {
107 created = PlatformThread::Create(options.stack_size, this, &thread_);
108 } else {
109 created = PlatformThread::CreateWithPriority(options.stack_size, this,
110 &thread_, options.priority);
112 if (!created) {
113 DLOG(ERROR) << "failed to create thread";
114 delete message_loop_;
115 message_loop_ = nullptr;
116 start_event_.reset();
117 return false;
121 DCHECK(message_loop_);
122 return true;
125 bool Thread::StartAndWaitForTesting() {
126 bool result = Start();
127 if (!result)
128 return false;
129 WaitUntilThreadStarted();
130 return true;
133 bool Thread::WaitUntilThreadStarted() {
134 if (!start_event_)
135 return false;
136 base::ThreadRestrictions::ScopedAllowWait allow_wait;
137 start_event_->Wait();
138 return true;
141 void Thread::Stop() {
142 if (!start_event_)
143 return;
145 StopSoon();
147 // Wait for the thread to exit.
149 // TODO(darin): Unfortunately, we need to keep message_loop_ around until
150 // the thread exits. Some consumers are abusing the API. Make them stop.
152 PlatformThread::Join(thread_);
154 // The thread should NULL message_loop_ on exit.
155 DCHECK(!message_loop_);
157 // The thread no longer needs to be joined.
158 start_event_.reset();
160 stopping_ = false;
163 void Thread::StopSoon() {
164 // We should only be called on the same thread that started us.
166 DCHECK_NE(thread_id(), PlatformThread::CurrentId());
168 if (stopping_ || !message_loop_)
169 return;
171 stopping_ = true;
172 task_runner()->PostTask(FROM_HERE, base::Bind(&ThreadQuitHelper));
175 PlatformThreadId Thread::thread_id() const {
176 AutoLock lock(thread_lock_);
177 return thread_.id();
180 bool Thread::IsRunning() const {
181 // If the thread's already started (i.e. message_loop_ is non-null) and
182 // not yet requested to stop (i.e. stopping_ is false) we can just return
183 // true. (Note that stopping_ is touched only on the same thread that
184 // starts / started the new thread so we need no locking here.)
185 if (message_loop_ && !stopping_)
186 return true;
187 // Otherwise check the running_ flag, which is set to true by the new thread
188 // only while it is inside Run().
189 AutoLock lock(running_lock_);
190 return running_;
193 void Thread::SetPriority(ThreadPriority priority) {
194 // The thread must be started (and id known) for this to be
195 // compatible with all platforms.
196 DCHECK(message_loop_ != nullptr);
197 PlatformThread::SetThreadPriority(thread_, priority);
200 void Thread::Run(MessageLoop* message_loop) {
201 message_loop->Run();
204 void Thread::SetThreadWasQuitProperly(bool flag) {
205 lazy_tls_bool.Pointer()->Set(flag);
208 bool Thread::GetThreadWasQuitProperly() {
209 bool quit_properly = true;
210 #ifndef NDEBUG
211 quit_properly = lazy_tls_bool.Pointer()->Get();
212 #endif
213 return quit_properly;
216 void Thread::ThreadMain() {
217 // Complete the initialization of our Thread object.
218 PlatformThread::SetName(name_.c_str());
219 ANNOTATE_THREAD_NAME(name_.c_str()); // Tell the name to race detector.
221 // Lazily initialize the message_loop so that it can run on this thread.
222 DCHECK(message_loop_);
223 scoped_ptr<MessageLoop> message_loop(message_loop_);
224 message_loop_->BindToCurrentThread();
225 message_loop_->set_thread_name(name_);
226 message_loop_->SetTimerSlack(message_loop_timer_slack_);
228 #if defined(OS_WIN)
229 scoped_ptr<win::ScopedCOMInitializer> com_initializer;
230 if (com_status_ != NONE) {
231 com_initializer.reset((com_status_ == STA) ?
232 new win::ScopedCOMInitializer() :
233 new win::ScopedCOMInitializer(win::ScopedCOMInitializer::kMTA));
235 #endif
237 // Make sure the thread_id() returns current thread.
238 // (This internally acquires lock against PlatformThread::Create)
239 DCHECK_EQ(thread_id(), PlatformThread::CurrentId());
241 // Let the thread do extra initialization.
242 Init();
245 AutoLock lock(running_lock_);
246 running_ = true;
249 start_event_->Signal();
251 Run(message_loop_);
254 AutoLock lock(running_lock_);
255 running_ = false;
258 // Let the thread do extra cleanup.
259 CleanUp();
261 #if defined(OS_WIN)
262 com_initializer.reset();
263 #endif
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_ = NULL;
273 } // namespace base