Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(690)

Side by Side Diff: base/threading/thread.cc

Issue 1011683002: Lazily initialize MessageLoop for faster thread startup (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Created 5 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "base/threading/thread.h" 5 #include "base/threading/thread.h"
6 6
7 #include "base/bind.h" 7 #include "base/bind.h"
8 #include "base/lazy_instance.h" 8 #include "base/lazy_instance.h"
9 #include "base/profiler/scoped_tracker.h" 9 #include "base/profiler/scoped_tracker.h"
10 #include "base/synchronization/waitable_event.h" 10 #include "base/synchronization/waitable_event.h"
11 #include "base/synchronization/waitable_event_watcher.h"
11 #include "base/third_party/dynamic_annotations/dynamic_annotations.h" 12 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
12 #include "base/threading/thread_id_name_manager.h" 13 #include "base/threading/thread_id_name_manager.h"
13 #include "base/threading/thread_local.h" 14 #include "base/threading/thread_local.h"
14 #include "base/threading/thread_restrictions.h" 15 #include "base/threading/thread_restrictions.h"
15 16
16 #if defined(OS_WIN) 17 #if defined(OS_WIN)
17 #include "base/win/scoped_com_initializer.h" 18 #include "base/win/scoped_com_initializer.h"
18 #endif 19 #endif
19 20
20 namespace base { 21 namespace base {
21 22
22 namespace { 23 namespace {
23 24
24 // We use this thread-local variable to record whether or not a thread exited 25 // 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 // because its Stop method was called. This allows us to catch cases where
26 // MessageLoop::QuitWhenIdle() is called directly, which is unexpected when 27 // MessageLoop::QuitWhenIdle() is called directly, which is unexpected when
27 // using a Thread to setup and run a MessageLoop. 28 // using a Thread to setup and run a MessageLoop.
28 base::LazyInstance<base::ThreadLocalBoolean> lazy_tls_bool = 29 base::LazyInstance<base::ThreadLocalBoolean> lazy_tls_bool =
29 LAZY_INSTANCE_INITIALIZER; 30 LAZY_INSTANCE_INITIALIZER;
30 31
31 } // namespace 32 } // namespace
32 33
33 // This is used to trigger the message loop to exit. 34 // This is used to trigger the message loop to exit.
34 void ThreadQuitHelper() { 35 void ThreadQuitHelper() {
35 MessageLoop::current()->QuitWhenIdle(); 36 MessageLoop::current()->QuitWhenIdle();
36 Thread::SetThreadWasQuitProperly(true); 37 Thread::SetThreadWasQuitProperly(true);
37 } 38 }
38 39
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;
44
45 // Used to synchronize thread startup.
46 WaitableEvent event;
47
48 explicit StartupData(const Options& opt)
49 : options(opt),
50 event(false, false) {}
51 };
52
53 Thread::Options::Options() 40 Thread::Options::Options()
54 : message_loop_type(MessageLoop::TYPE_DEFAULT), 41 : message_loop_type(MessageLoop::TYPE_DEFAULT),
55 timer_slack(TIMER_SLACK_NONE), 42 timer_slack(TIMER_SLACK_NONE),
56 stack_size(0) { 43 stack_size(0) {
57 } 44 }
58 45
59 Thread::Options::Options(MessageLoop::Type type, 46 Thread::Options::Options(MessageLoop::Type type,
60 size_t size) 47 size_t size)
61 : message_loop_type(type), 48 : message_loop_type(type),
62 timer_slack(TIMER_SLACK_NONE), 49 timer_slack(TIMER_SLACK_NONE),
63 stack_size(size) { 50 stack_size(size) {
64 } 51 }
65 52
66 Thread::Options::~Options() { 53 Thread::Options::~Options() {
67 } 54 }
68 55
69 Thread::Thread(const std::string& name) 56 Thread::Thread(const std::string& name)
70 : 57 :
71 #if defined(OS_WIN) 58 #if defined(OS_WIN)
72 com_status_(NONE), 59 com_status_(NONE),
73 #endif 60 #endif
74 started_(false), 61 started_(false),
75 stopping_(false), 62 stopping_(false),
76 running_(false), 63 running_(false),
77 startup_data_(NULL),
78 thread_(0), 64 thread_(0),
79 message_loop_(NULL), 65 message_loop_(nullptr),
80 thread_id_(kInvalidThreadId), 66 thread_id_(kInvalidThreadId),
81 name_(name) { 67 name_(name) {
82 } 68 }
83 69
84 Thread::~Thread() { 70 Thread::~Thread() {
85 Stop(); 71 Stop();
86 } 72 }
87 73
88 bool Thread::Start() { 74 bool Thread::Start() {
89 Options options; 75 Options options;
(...skipping 11 matching lines...) Expand all
101 "465458 base::Thread::StartWithOptions")); 87 "465458 base::Thread::StartWithOptions"));
102 88
103 DCHECK(!message_loop_); 89 DCHECK(!message_loop_);
104 #if defined(OS_WIN) 90 #if defined(OS_WIN)
105 DCHECK((com_status_ != STA) || 91 DCHECK((com_status_ != STA) ||
106 (options.message_loop_type == MessageLoop::TYPE_UI)); 92 (options.message_loop_type == MessageLoop::TYPE_UI));
107 #endif 93 #endif
108 94
109 SetThreadWasQuitProperly(false); 95 SetThreadWasQuitProperly(false);
110 96
111 StartupData startup_data(options); 97 scoped_ptr<MessageLoop::LazyInitOptions> message_loop_options(
DaleCurtis 2015/03/18 22:04:28 No need for a scoped_ptr allocation? Seems simple
kinuko 2015/03/19 03:08:16 Not really, but I want to keep around this object
112 startup_data_ = &startup_data; 98 new MessageLoop::LazyInitOptions);
99 message_loop_options->message_loop_type = options.message_loop_type;
100 message_loop_options->message_pump_factory = options.message_pump_factory;
101 message_loop_options->timer_slack = options.timer_slack;
102 message_loop_ = MessageLoop::CreateForLazyInit(message_loop_options.Pass());
103
104 start_event_.reset(new WaitableEvent(false, false));
113 105
114 if (!PlatformThread::Create(options.stack_size, this, &thread_)) { 106 if (!PlatformThread::Create(options.stack_size, this, &thread_)) {
115 DLOG(ERROR) << "failed to create thread"; 107 DLOG(ERROR) << "failed to create thread";
116 startup_data_ = NULL; 108 delete message_loop_;
109 message_loop_ = NULL;
117 return false; 110 return false;
118 } 111 }
119 112
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)"));
124
125 // Wait for the thread to start and initialize message_loop_
126 base::ThreadRestrictions::ScopedAllowWait allow_wait;
127 startup_data.event.Wait();
128
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; 113 started_ = true;
132 114
133 DCHECK(message_loop_); 115 DCHECK(message_loop_);
134 return true; 116 return true;
135 } 117 }
136 118
119 bool Thread::StartAndWait() {
120 bool result = Start();
121 if (!result)
122 return result;
123 WaitUntilThreadStarted();
124 return result;
125 }
126
127 bool Thread::WaitUntilThreadStarted() {
128 if (!started_)
129 return false;
130 base::ThreadRestrictions::ScopedAllowWait allow_wait;
131 start_event_->Wait();
132 return true;
133 }
134
137 void Thread::Stop() { 135 void Thread::Stop() {
138 if (!started_) 136 if (!started_)
139 return; 137 return;
140 138
141 StopSoon(); 139 StopSoon();
142 140
143 // Wait for the thread to exit. 141 // Wait for the thread to exit.
144 // 142 //
145 // TODO(darin): Unfortunately, we need to keep message_loop_ around until 143 // TODO(darin): Unfortunately, we need to keep message_loop_ around until
146 // the thread exits. Some consumers are abusing the API. Make them stop. 144 // the thread exits. Some consumers are abusing the API. Make them stop.
(...skipping 17 matching lines...) Expand all
164 DCHECK_NE(ANNOTATE_UNPROTECTED_READ(thread_id_), PlatformThread::CurrentId()); 162 DCHECK_NE(ANNOTATE_UNPROTECTED_READ(thread_id_), PlatformThread::CurrentId());
165 163
166 if (stopping_ || !message_loop_) 164 if (stopping_ || !message_loop_)
167 return; 165 return;
168 166
169 stopping_ = true; 167 stopping_ = true;
170 message_loop_->PostTask(FROM_HERE, base::Bind(&ThreadQuitHelper)); 168 message_loop_->PostTask(FROM_HERE, base::Bind(&ThreadQuitHelper));
171 } 169 }
172 170
173 bool Thread::IsRunning() const { 171 bool Thread::IsRunning() const {
174 return running_; 172 if (stopping_)
173 return IsInRunLoop();
174 return started_;
175 } 175 }
176 176
177 void Thread::SetPriority(ThreadPriority priority) { 177 void Thread::SetPriority(ThreadPriority priority) {
178 // The thread must be started (and id known) for this to be 178 // The thread must be started (and id known) for this to be
179 // compatible with all platforms. 179 // compatible with all platforms.
180 DCHECK_NE(thread_id_, kInvalidThreadId); 180 DCHECK_NE(thread_id_, kInvalidThreadId);
181 PlatformThread::SetThreadPriority(thread_, priority); 181 PlatformThread::SetThreadPriority(thread_, priority);
182 } 182 }
183 183
184 void Thread::Run(MessageLoop* message_loop) { 184 void Thread::Run(MessageLoop* message_loop) {
185 message_loop->Run(); 185 message_loop->Run();
186 } 186 }
187 187
188 void Thread::SetThreadWasQuitProperly(bool flag) { 188 void Thread::SetThreadWasQuitProperly(bool flag) {
189 lazy_tls_bool.Pointer()->Set(flag); 189 lazy_tls_bool.Pointer()->Set(flag);
190 } 190 }
191 191
192 bool Thread::GetThreadWasQuitProperly() { 192 bool Thread::GetThreadWasQuitProperly() {
193 bool quit_properly = true; 193 bool quit_properly = true;
194 #ifndef NDEBUG 194 #ifndef NDEBUG
195 quit_properly = lazy_tls_bool.Pointer()->Get(); 195 quit_properly = lazy_tls_bool.Pointer()->Get();
196 #endif 196 #endif
197 return quit_properly; 197 return quit_properly;
198 } 198 }
199 199
200 void Thread::ThreadMain() { 200 void Thread::ThreadMain() {
201 { 201 {
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));
211 }
212
213 // Complete the initialization of our Thread object. 202 // Complete the initialization of our Thread object.
214 thread_id_ = PlatformThread::CurrentId(); 203 thread_id_ = PlatformThread::CurrentId();
215 PlatformThread::SetName(name_.c_str()); 204 PlatformThread::SetName(name_.c_str());
216 ANNOTATE_THREAD_NAME(name_.c_str()); // Tell the name to race detector. 205 ANNOTATE_THREAD_NAME(name_.c_str()); // Tell the name to race detector.
217 message_loop->set_thread_name(name_); 206
218 message_loop->SetTimerSlack(startup_data_->options.timer_slack); 207 // Lazily initialize the message_loop so that it can run on this thread.
219 message_loop_ = message_loop.get(); 208 DCHECK(message_loop_);
209 scoped_ptr<MessageLoop> message_loop(message_loop_);
210 message_loop_->set_thread_name(name_);
211 message_loop_->LazyInit();
220 212
221 #if defined(OS_WIN) 213 #if defined(OS_WIN)
222 scoped_ptr<win::ScopedCOMInitializer> com_initializer; 214 scoped_ptr<win::ScopedCOMInitializer> com_initializer;
223 if (com_status_ != NONE) { 215 if (com_status_ != NONE) {
224 com_initializer.reset((com_status_ == STA) ? 216 com_initializer.reset((com_status_ == STA) ?
225 new win::ScopedCOMInitializer() : 217 new win::ScopedCOMInitializer() :
226 new win::ScopedCOMInitializer(win::ScopedCOMInitializer::kMTA)); 218 new win::ScopedCOMInitializer(win::ScopedCOMInitializer::kMTA));
227 } 219 }
228 #endif 220 #endif
229 221
230 // Let the thread do extra initialization. 222 // Let the thread do extra initialization.
231 // Let's do this before signaling we are started.
232 Init(); 223 Init();
233 224
234 running_ = true; 225 {
DaleCurtis 2015/03/18 22:04:28 You can combine running_ and start_event_ into a r
kinuko 2015/03/19 03:08:16 Sounds like a good idea, done.
kinuko 2015/03/20 08:44:22 Hmm, replacing running_ with event_->IsSignaled()
235 startup_data_->event.Signal(); 226 base::AutoLock lock(running_lock_);
236 // startup_data_ can't be touched anymore since the starting thread is now 227 running_ = true;
237 // unlocked. 228 }
229
230 start_event_->Signal();
238 231
239 Run(message_loop_); 232 Run(message_loop_);
240 running_ = false; 233
234 {
235 base::AutoLock lock(running_lock_);
236 running_ = false;
237 }
241 238
242 // Let the thread do extra cleanup. 239 // Let the thread do extra cleanup.
243 CleanUp(); 240 CleanUp();
244 241
245 #if defined(OS_WIN) 242 #if defined(OS_WIN)
246 com_initializer.reset(); 243 com_initializer.reset();
247 #endif 244 #endif
248 245
249 // Assert that MessageLoop::Quit was called by ThreadQuitHelper. 246 // Assert that MessageLoop::Quit was called by ThreadQuitHelper.
250 DCHECK(GetThreadWasQuitProperly()); 247 DCHECK(GetThreadWasQuitProperly());
251 248
252 // We can't receive messages anymore. 249 // We can't receive messages anymore.
253 message_loop_ = NULL; 250 message_loop_ = NULL;
254 } 251 }
255 } 252 }
256 253
254 bool Thread::IsInRunLoop() const {
255 base::AutoLock lock(running_lock_);
256 return running_;
257 }
258
257 } // namespace base 259 } // namespace base
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698