Supervised user import: Listen for profile creation/deletion
[chromium-blink-merge.git] / base / threading / thread.cc
blobd42ba4d1577ae4abcd9ad8a8bb5576036a01b5b0
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/profiler/scoped_tracker.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 // Used to pass data to ThreadMain. This structure is allocated on the stack
40 // from within StartWithOptions.
41 struct Thread::StartupData {
42 // We get away with a const reference here because of how we are allocated.
43 const Thread::Options& options;
45 // Used to synchronize thread startup.
46 WaitableEvent event;
48 explicit StartupData(const Options& opt)
49 : options(opt),
50 event(false, false) {}
53 Thread::Options::Options()
54 : message_loop_type(MessageLoop::TYPE_DEFAULT),
55 timer_slack(TIMER_SLACK_NONE),
56 stack_size(0) {
59 Thread::Options::Options(MessageLoop::Type type,
60 size_t size)
61 : message_loop_type(type),
62 timer_slack(TIMER_SLACK_NONE),
63 stack_size(size) {
66 Thread::Options::~Options() {
69 Thread::Thread(const std::string& name)
71 #if defined(OS_WIN)
72 com_status_(NONE),
73 #endif
74 started_(false),
75 stopping_(false),
76 running_(false),
77 startup_data_(NULL),
78 thread_(0),
79 message_loop_(NULL),
80 thread_id_(kInvalidThreadId),
81 name_(name) {
84 Thread::~Thread() {
85 Stop();
88 bool Thread::Start() {
89 Options options;
90 #if defined(OS_WIN)
91 if (com_status_ == STA)
92 options.message_loop_type = MessageLoop::TYPE_UI;
93 #endif
94 return StartWithOptions(options);
97 bool Thread::StartWithOptions(const Options& options) {
98 DCHECK(!message_loop_);
99 #if defined(OS_WIN)
100 DCHECK((com_status_ != STA) ||
101 (options.message_loop_type == MessageLoop::TYPE_UI));
102 #endif
104 SetThreadWasQuitProperly(false);
106 StartupData startup_data(options);
107 startup_data_ = &startup_data;
109 if (!PlatformThread::Create(options.stack_size, this, &thread_)) {
110 DLOG(ERROR) << "failed to create thread";
111 startup_data_ = NULL;
112 return false;
115 // TODO(kinuko): Remove once crbug.com/465458 is solved.
116 tracked_objects::ScopedTracker tracking_profile_wait(
117 FROM_HERE_WITH_EXPLICIT_FUNCTION(
118 "465458 base::Thread::StartWithOptions (Wait)"));
120 // Wait for the thread to start and initialize message_loop_
121 base::ThreadRestrictions::ScopedAllowWait allow_wait;
122 startup_data.event.Wait();
124 // set it to NULL so we don't keep a pointer to some object on the stack.
125 startup_data_ = NULL;
126 started_ = true;
128 DCHECK(message_loop_);
129 return true;
132 void Thread::Stop() {
133 if (!started_)
134 return;
136 StopSoon();
138 // Wait for the thread to exit.
140 // TODO(darin): Unfortunately, we need to keep message_loop_ around until
141 // the thread exits. Some consumers are abusing the API. Make them stop.
143 PlatformThread::Join(thread_);
145 // The thread should NULL message_loop_ on exit.
146 DCHECK(!message_loop_);
148 // The thread no longer needs to be joined.
149 started_ = false;
151 stopping_ = false;
154 void Thread::StopSoon() {
155 // We should only be called on the same thread that started us.
157 // Reading thread_id_ without a lock can lead to a benign data race
158 // with ThreadMain, so we annotate it to stay silent under ThreadSanitizer.
159 DCHECK_NE(ANNOTATE_UNPROTECTED_READ(thread_id_), PlatformThread::CurrentId());
161 if (stopping_ || !message_loop_)
162 return;
164 stopping_ = true;
165 message_loop_->PostTask(FROM_HERE, base::Bind(&ThreadQuitHelper));
168 bool Thread::IsRunning() const {
169 return running_;
172 void Thread::SetPriority(ThreadPriority priority) {
173 // The thread must be started (and id known) for this to be
174 // compatible with all platforms.
175 DCHECK_NE(thread_id_, kInvalidThreadId);
176 PlatformThread::SetThreadPriority(thread_, priority);
179 void Thread::Run(MessageLoop* message_loop) {
180 message_loop->Run();
183 void Thread::SetThreadWasQuitProperly(bool flag) {
184 lazy_tls_bool.Pointer()->Set(flag);
187 bool Thread::GetThreadWasQuitProperly() {
188 bool quit_properly = true;
189 #ifndef NDEBUG
190 quit_properly = lazy_tls_bool.Pointer()->Get();
191 #endif
192 return quit_properly;
195 void Thread::ThreadMain() {
197 // The message loop for this thread.
198 // Allocated on the heap to centralize any leak reports at this line.
199 scoped_ptr<MessageLoop> message_loop;
200 if (!startup_data_->options.message_pump_factory.is_null()) {
201 message_loop.reset(
202 new MessageLoop(startup_data_->options.message_pump_factory.Run()));
203 } else {
204 message_loop.reset(
205 new MessageLoop(startup_data_->options.message_loop_type));
208 // Complete the initialization of our Thread object.
209 thread_id_ = PlatformThread::CurrentId();
210 PlatformThread::SetName(name_.c_str());
211 ANNOTATE_THREAD_NAME(name_.c_str()); // Tell the name to race detector.
212 message_loop->set_thread_name(name_);
213 message_loop->SetTimerSlack(startup_data_->options.timer_slack);
214 message_loop_ = message_loop.get();
216 #if defined(OS_WIN)
217 scoped_ptr<win::ScopedCOMInitializer> com_initializer;
218 if (com_status_ != NONE) {
219 com_initializer.reset((com_status_ == STA) ?
220 new win::ScopedCOMInitializer() :
221 new win::ScopedCOMInitializer(win::ScopedCOMInitializer::kMTA));
223 #endif
225 // Let the thread do extra initialization.
226 // Let's do this before signaling we are started.
227 Init();
229 running_ = true;
230 startup_data_->event.Signal();
231 // startup_data_ can't be touched anymore since the starting thread is now
232 // unlocked.
234 Run(message_loop_);
235 running_ = false;
237 // Let the thread do extra cleanup.
238 CleanUp();
240 #if defined(OS_WIN)
241 com_initializer.reset();
242 #endif
244 // Assert that MessageLoop::Quit was called by ThreadQuitHelper.
245 DCHECK(GetThreadWasQuitProperly());
247 // We can't receive messages anymore.
248 message_loop_ = NULL;
252 } // namespace base