Revert of Re-enabled contenteditable and text-changed tests after content editable...
[chromium-blink-merge.git] / base / threading / thread.cc
blob4b517a1ef264d46d3b76b92357045ae877a6c427
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 id_(kInvalidThreadId),
66 id_event_(true, false),
67 message_loop_(nullptr),
68 message_loop_timer_slack_(TIMER_SLACK_NONE),
69 name_(name),
70 start_event_(false, false) {
73 Thread::~Thread() {
74 Stop();
77 bool Thread::Start() {
78 Options options;
79 #if defined(OS_WIN)
80 if (com_status_ == STA)
81 options.message_loop_type = MessageLoop::TYPE_UI;
82 #endif
83 return StartWithOptions(options);
86 bool Thread::StartWithOptions(const Options& options) {
87 DCHECK(!message_loop_);
88 #if defined(OS_WIN)
89 DCHECK((com_status_ != STA) ||
90 (options.message_loop_type == MessageLoop::TYPE_UI));
91 #endif
93 // Reset |id_| here to support restarting the thread.
94 id_event_.Reset();
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_,
114 options.priority)) {
115 DLOG(ERROR) << "failed to create thread";
116 message_loop_ = nullptr;
117 return false;
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_);
126 return true;
129 bool Thread::StartAndWaitForTesting() {
130 bool result = Start();
131 if (!result)
132 return false;
133 WaitUntilThreadStarted();
134 return true;
137 bool Thread::WaitUntilThreadStarted() const {
138 if (!message_loop_)
139 return false;
140 base::ThreadRestrictions::ScopedAllowWait allow_wait;
141 start_event_.Wait();
142 return true;
145 void Thread::Stop() {
146 AutoLock lock(thread_lock_);
147 if (thread_.is_null())
148 return;
150 StopSoon();
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_);
163 stopping_ = false;
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_)
172 return;
174 stopping_ = true;
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;
181 id_event_.Wait();
182 return id_;
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_)
191 return true;
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_);
195 return running_;
198 void Thread::Run(MessageLoop* message_loop) {
199 message_loop->Run();
202 void Thread::SetThreadWasQuitProperly(bool flag) {
203 lazy_tls_bool.Pointer()->Set(flag);
206 bool Thread::GetThreadWasQuitProperly() {
207 bool quit_properly = true;
208 #ifndef NDEBUG
209 quit_properly = lazy_tls_bool.Pointer()->Get();
210 #endif
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_);
219 id_event_.Signal();
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_);
232 #if defined(OS_WIN)
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));
239 #endif
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_ = nullptr;
273 } // namespace base