Port Android relocation packer to chromium build
[chromium-blink-merge.git] / base / threading / thread.cc
blobea5b1747e3836a8092517b19e8197d1cf3debb62
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 // TODO(eroman): Remove once crbug.com/465458 is solved.
99 tracked_objects::ScopedTracker tracking_profile(
100 FROM_HERE_WITH_EXPLICIT_FUNCTION(
101 "465458 base::Thread::StartWithOptions"));
103 DCHECK(!message_loop_);
104 #if defined(OS_WIN)
105 DCHECK((com_status_ != STA) ||
106 (options.message_loop_type == MessageLoop::TYPE_UI));
107 #endif
109 SetThreadWasQuitProperly(false);
111 StartupData startup_data(options);
112 startup_data_ = &startup_data;
114 if (!PlatformThread::Create(options.stack_size, this, &thread_)) {
115 DLOG(ERROR) << "failed to create thread";
116 startup_data_ = NULL;
117 return false;
120 // TODO(eroman): Remove once crbug.com/465458 is solved.
121 tracked_objects::ScopedTracker tracking_profile_wait(
122 FROM_HERE_WITH_EXPLICIT_FUNCTION(
123 "465458 base::Thread::StartWithOptions (Wait)"));
125 // Wait for the thread to start and initialize message_loop_
126 base::ThreadRestrictions::ScopedAllowWait allow_wait;
127 startup_data.event.Wait();
129 // set it to NULL so we don't keep a pointer to some object on the stack.
130 startup_data_ = NULL;
131 started_ = true;
133 DCHECK(message_loop_);
134 return true;
137 void Thread::Stop() {
138 if (!started_)
139 return;
141 StopSoon();
143 // Wait for the thread to exit.
145 // TODO(darin): Unfortunately, we need to keep message_loop_ around until
146 // the thread exits. Some consumers are abusing the API. Make them stop.
148 PlatformThread::Join(thread_);
150 // The thread should NULL message_loop_ on exit.
151 DCHECK(!message_loop_);
153 // The thread no longer needs to be joined.
154 started_ = false;
156 stopping_ = false;
159 void Thread::StopSoon() {
160 // We should only be called on the same thread that started us.
162 // Reading thread_id_ without a lock can lead to a benign data race
163 // with ThreadMain, so we annotate it to stay silent under ThreadSanitizer.
164 DCHECK_NE(ANNOTATE_UNPROTECTED_READ(thread_id_), PlatformThread::CurrentId());
166 if (stopping_ || !message_loop_)
167 return;
169 stopping_ = true;
170 message_loop_->PostTask(FROM_HERE, base::Bind(&ThreadQuitHelper));
173 bool Thread::IsRunning() const {
174 return running_;
177 void Thread::SetPriority(ThreadPriority priority) {
178 // The thread must be started (and id known) for this to be
179 // compatible with all platforms.
180 DCHECK_NE(thread_id_, kInvalidThreadId);
181 PlatformThread::SetThreadPriority(thread_, priority);
184 void Thread::Run(MessageLoop* message_loop) {
185 message_loop->Run();
188 void Thread::SetThreadWasQuitProperly(bool flag) {
189 lazy_tls_bool.Pointer()->Set(flag);
192 bool Thread::GetThreadWasQuitProperly() {
193 bool quit_properly = true;
194 #ifndef NDEBUG
195 quit_properly = lazy_tls_bool.Pointer()->Get();
196 #endif
197 return quit_properly;
200 void Thread::ThreadMain() {
202 // The message loop for this thread.
203 // Allocated on the heap to centralize any leak reports at this line.
204 scoped_ptr<MessageLoop> message_loop;
205 if (!startup_data_->options.message_pump_factory.is_null()) {
206 message_loop.reset(
207 new MessageLoop(startup_data_->options.message_pump_factory.Run()));
208 } else {
209 message_loop.reset(
210 new MessageLoop(startup_data_->options.message_loop_type));
213 // Complete the initialization of our Thread object.
214 thread_id_ = PlatformThread::CurrentId();
215 PlatformThread::SetName(name_.c_str());
216 ANNOTATE_THREAD_NAME(name_.c_str()); // Tell the name to race detector.
217 message_loop->set_thread_name(name_);
218 message_loop->SetTimerSlack(startup_data_->options.timer_slack);
219 message_loop_ = message_loop.get();
221 #if defined(OS_WIN)
222 scoped_ptr<win::ScopedCOMInitializer> com_initializer;
223 if (com_status_ != NONE) {
224 com_initializer.reset((com_status_ == STA) ?
225 new win::ScopedCOMInitializer() :
226 new win::ScopedCOMInitializer(win::ScopedCOMInitializer::kMTA));
228 #endif
230 // Let the thread do extra initialization.
231 // Let's do this before signaling we are started.
232 Init();
234 running_ = true;
235 startup_data_->event.Signal();
236 // startup_data_ can't be touched anymore since the starting thread is now
237 // unlocked.
239 Run(message_loop_);
240 running_ = false;
242 // Let the thread do extra cleanup.
243 CleanUp();
245 #if defined(OS_WIN)
246 com_initializer.reset();
247 #endif
249 // Assert that MessageLoop::Quit was called by ThreadQuitHelper.
250 DCHECK(GetThreadWasQuitProperly());
252 // We can't receive messages anymore.
253 message_loop_ = NULL;
257 } // namespace base