Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / base / threading / thread.cc
blobf7d938c8483ffcb540b652e7a4d230c14708c452
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/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"
17 #if defined(OS_WIN)
18 #include "base/win/scoped_com_initializer.h"
19 #endif
21 namespace base {
23 namespace {
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;
32 } // namespace
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),
43 stack_size(0),
44 priority(ThreadPriority::NORMAL) {
47 Thread::Options::Options(MessageLoop::Type type,
48 size_t size)
49 : message_loop_type(type),
50 timer_slack(TIMER_SLACK_NONE),
51 stack_size(size),
52 priority(ThreadPriority::NORMAL) {
55 Thread::Options::~Options() {
58 Thread::Thread(const std::string& name)
60 #if defined(OS_WIN)
61 com_status_(NONE),
62 #endif
63 stopping_(false),
64 running_(false),
65 thread_(0),
66 id_(kInvalidThreadId),
67 id_event_(true, false),
68 message_loop_(nullptr),
69 message_loop_timer_slack_(TIMER_SLACK_NONE),
70 name_(name) {
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(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_,
114 options.priority)) {
115 DLOG(ERROR) << "failed to create thread";
116 message_loop_ = nullptr;
117 start_event_.reset();
118 return false;
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_);
127 return true;
130 bool Thread::StartAndWaitForTesting() {
131 bool result = Start();
132 if (!result)
133 return false;
134 WaitUntilThreadStarted();
135 return true;
138 bool Thread::WaitUntilThreadStarted() {
139 if (!start_event_)
140 return false;
141 base::ThreadRestrictions::ScopedAllowWait allow_wait;
142 start_event_->Wait();
143 return true;
146 void Thread::Stop() {
147 if (!start_event_)
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_);
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();
165 stopping_ = false;
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_)
174 return;
176 stopping_ = true;
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"));
187 id_event_.Wait();
188 return id_;
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_)
197 return true;
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_);
201 return running_;
204 void Thread::Run(MessageLoop* message_loop) {
205 message_loop->Run();
208 void Thread::SetThreadWasQuitProperly(bool flag) {
209 lazy_tls_bool.Pointer()->Set(flag);
212 bool Thread::GetThreadWasQuitProperly() {
213 bool quit_properly = true;
214 #ifndef NDEBUG
215 quit_properly = lazy_tls_bool.Pointer()->Get();
216 #endif
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_);
225 id_event_.Signal();
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_);
238 #if defined(OS_WIN)
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));
245 #endif
247 // Let the thread do extra initialization.
248 Init();
251 AutoLock lock(running_lock_);
252 running_ = true;
255 start_event_->Signal();
257 Run(message_loop_);
260 AutoLock lock(running_lock_);
261 running_ = false;
264 // Let the thread do extra cleanup.
265 CleanUp();
267 #if defined(OS_WIN)
268 com_initializer.reset();
269 #endif
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;
279 } // namespace base