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

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: addressed comments Created 5 years, 8 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"
(...skipping 18 matching lines...) Expand all
29 LAZY_INSTANCE_INITIALIZER; 29 LAZY_INSTANCE_INITIALIZER;
30 30
31 } // namespace 31 } // namespace
32 32
33 // This is used to trigger the message loop to exit. 33 // This is used to trigger the message loop to exit.
34 void ThreadQuitHelper() { 34 void ThreadQuitHelper() {
35 MessageLoop::current()->QuitWhenIdle(); 35 MessageLoop::current()->QuitWhenIdle();
36 Thread::SetThreadWasQuitProperly(true); 36 Thread::SetThreadWasQuitProperly(true);
37 } 37 }
38 38
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() 39 Thread::Options::Options()
54 : message_loop_type(MessageLoop::TYPE_DEFAULT), 40 : message_loop_type(MessageLoop::TYPE_DEFAULT),
55 timer_slack(TIMER_SLACK_NONE), 41 timer_slack(TIMER_SLACK_NONE),
56 stack_size(0) { 42 stack_size(0) {
57 } 43 }
58 44
59 Thread::Options::Options(MessageLoop::Type type, 45 Thread::Options::Options(MessageLoop::Type type,
60 size_t size) 46 size_t size)
61 : message_loop_type(type), 47 : message_loop_type(type),
62 timer_slack(TIMER_SLACK_NONE), 48 timer_slack(TIMER_SLACK_NONE),
63 stack_size(size) { 49 stack_size(size) {
64 } 50 }
65 51
66 Thread::Options::~Options() { 52 Thread::Options::~Options() {
67 } 53 }
68 54
69 Thread::Thread(const std::string& name) 55 Thread::Thread(const std::string& name)
70 : 56 :
71 #if defined(OS_WIN) 57 #if defined(OS_WIN)
72 com_status_(NONE), 58 com_status_(NONE),
73 #endif 59 #endif
74 started_(false),
75 stopping_(false), 60 stopping_(false),
76 running_(false), 61 running_(false),
77 startup_data_(NULL),
78 thread_(0), 62 thread_(0),
79 message_loop_(NULL), 63 message_loop_(nullptr),
80 thread_id_(kInvalidThreadId), 64 message_loop_timer_slack_(TIMER_SLACK_NONE),
81 name_(name) { 65 name_(name) {
82 } 66 }
83 67
84 Thread::~Thread() { 68 Thread::~Thread() {
85 Stop(); 69 Stop();
86 } 70 }
87 71
88 bool Thread::Start() { 72 bool Thread::Start() {
89 Options options; 73 Options options;
90 #if defined(OS_WIN) 74 #if defined(OS_WIN)
91 if (com_status_ == STA) 75 if (com_status_ == STA)
92 options.message_loop_type = MessageLoop::TYPE_UI; 76 options.message_loop_type = MessageLoop::TYPE_UI;
93 #endif 77 #endif
94 return StartWithOptions(options); 78 return StartWithOptions(options);
95 } 79 }
96 80
97 bool Thread::StartWithOptions(const Options& options) { 81 bool Thread::StartWithOptions(const Options& options) {
98 DCHECK(!message_loop_); 82 DCHECK(!message_loop_);
99 #if defined(OS_WIN) 83 #if defined(OS_WIN)
100 DCHECK((com_status_ != STA) || 84 DCHECK((com_status_ != STA) ||
101 (options.message_loop_type == MessageLoop::TYPE_UI)); 85 (options.message_loop_type == MessageLoop::TYPE_UI));
102 #endif 86 #endif
103 87
104 SetThreadWasQuitProperly(false); 88 SetThreadWasQuitProperly(false);
105 89
106 StartupData startup_data(options); 90 MessageLoop::Type type = options.message_loop_type;
107 startup_data_ = &startup_data; 91 if (!options.message_pump_factory.is_null())
92 type = MessageLoop::TYPE_CUSTOM;
93
94 message_loop_timer_slack_ = options.timer_slack;
95 message_loop_ = new MessageLoop(type, options.message_pump_factory);
96
97 start_event_.reset(new WaitableEvent(false, false));
108 98
109 if (!PlatformThread::Create(options.stack_size, this, &thread_)) { 99 if (!PlatformThread::Create(options.stack_size, this, &thread_)) {
110 DLOG(ERROR) << "failed to create thread"; 100 DLOG(ERROR) << "failed to create thread";
111 startup_data_ = NULL; 101 delete message_loop_;
102 message_loop_ = nullptr;
103 start_event_.reset();
112 return false; 104 return false;
113 } 105 }
114 106
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)"));
119
120 // Wait for the thread to start and initialize message_loop_
121 base::ThreadRestrictions::ScopedAllowWait allow_wait;
122 startup_data.event.Wait();
123
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;
127
128 DCHECK(message_loop_); 107 DCHECK(message_loop_);
129 return true; 108 return true;
130 } 109 }
131 110
111 bool Thread::StartAndWaitForTesting() {
112 bool result = Start();
113 if (!result)
114 return false;
115 WaitUntilThreadStartedForTesting();
116 return result;
117 }
118
119 bool Thread::WaitUntilThreadStartedForTesting() {
120 if (!start_event_)
121 return false;
122 base::ThreadRestrictions::ScopedAllowWait allow_wait;
123 start_event_->Wait();
124 return true;
125 }
126
132 void Thread::Stop() { 127 void Thread::Stop() {
133 if (!started_) 128 if (!start_event_)
134 return; 129 return;
135 130
136 StopSoon(); 131 StopSoon();
137 132
138 // Wait for the thread to exit. 133 // Wait for the thread to exit.
139 // 134 //
140 // TODO(darin): Unfortunately, we need to keep message_loop_ around until 135 // TODO(darin): Unfortunately, we need to keep message_loop_ around until
141 // the thread exits. Some consumers are abusing the API. Make them stop. 136 // the thread exits. Some consumers are abusing the API. Make them stop.
142 // 137 //
143 PlatformThread::Join(thread_); 138 PlatformThread::Join(thread_);
144 139
145 // The thread should NULL message_loop_ on exit. 140 // The thread should NULL message_loop_ on exit.
146 DCHECK(!message_loop_); 141 DCHECK(!message_loop_);
147 142
148 // The thread no longer needs to be joined. 143 // The thread no longer needs to be joined.
149 started_ = false; 144 start_event_.reset();
150 145
151 stopping_ = false; 146 stopping_ = false;
152 } 147 }
153 148
154 void Thread::StopSoon() { 149 void Thread::StopSoon() {
155 // We should only be called on the same thread that started us. 150 // We should only be called on the same thread that started us.
156 151
157 // Reading thread_id_ without a lock can lead to a benign data race 152 DCHECK_NE(thread_id(), PlatformThread::CurrentId());
158 // with ThreadMain, so we annotate it to stay silent under ThreadSanitizer.
159 DCHECK_NE(ANNOTATE_UNPROTECTED_READ(thread_id_), PlatformThread::CurrentId());
160 153
161 if (stopping_ || !message_loop_) 154 if (stopping_ || !message_loop_)
162 return; 155 return;
163 156
164 stopping_ = true; 157 stopping_ = true;
165 message_loop_->PostTask(FROM_HERE, base::Bind(&ThreadQuitHelper)); 158 message_loop_->PostTask(FROM_HERE, base::Bind(&ThreadQuitHelper));
166 } 159 }
167 160
168 bool Thread::IsRunning() const { 161 bool Thread::IsRunning() const {
162 if (message_loop_ && !stopping_)
163 return true;
164 AutoLock lock(lock_);
169 return running_; 165 return running_;
170 } 166 }
171 167
172 void Thread::SetPriority(ThreadPriority priority) { 168 void Thread::SetPriority(ThreadPriority priority) {
173 // The thread must be started (and id known) for this to be 169 // The thread must be started (and id known) for this to be
174 // compatible with all platforms. 170 // compatible with all platforms.
175 DCHECK_NE(thread_id_, kInvalidThreadId); 171 DCHECK(message_loop_ != nullptr);
176 PlatformThread::SetThreadPriority(thread_, priority); 172 PlatformThread::SetThreadPriority(thread_, priority);
177 } 173 }
178 174
179 void Thread::Run(MessageLoop* message_loop) { 175 void Thread::Run(MessageLoop* message_loop) {
180 message_loop->Run(); 176 message_loop->Run();
181 } 177 }
182 178
183 void Thread::SetThreadWasQuitProperly(bool flag) { 179 void Thread::SetThreadWasQuitProperly(bool flag) {
184 lazy_tls_bool.Pointer()->Set(flag); 180 lazy_tls_bool.Pointer()->Set(flag);
185 } 181 }
186 182
187 bool Thread::GetThreadWasQuitProperly() { 183 bool Thread::GetThreadWasQuitProperly() {
188 bool quit_properly = true; 184 bool quit_properly = true;
189 #ifndef NDEBUG 185 #ifndef NDEBUG
190 quit_properly = lazy_tls_bool.Pointer()->Get(); 186 quit_properly = lazy_tls_bool.Pointer()->Get();
191 #endif 187 #endif
192 return quit_properly; 188 return quit_properly;
193 } 189 }
194 190
195 void Thread::ThreadMain() { 191 void Thread::ThreadMain() {
196 { 192 // Complete the initialization of our Thread object.
197 // The message loop for this thread. 193 DCHECK_EQ(thread_id(), PlatformThread::CurrentId());
198 // Allocated on the heap to centralize any leak reports at this line. 194 PlatformThread::SetName(name_.c_str());
199 scoped_ptr<MessageLoop> message_loop; 195 ANNOTATE_THREAD_NAME(name_.c_str()); // Tell the name to race detector.
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));
206 }
207 196
208 // Complete the initialization of our Thread object. 197 // Lazily initialize the message_loop so that it can run on this thread.
209 thread_id_ = PlatformThread::CurrentId(); 198 DCHECK(message_loop_);
210 PlatformThread::SetName(name_.c_str()); 199 scoped_ptr<MessageLoop> message_loop(message_loop_);
211 ANNOTATE_THREAD_NAME(name_.c_str()); // Tell the name to race detector. 200 message_loop_->BindToCurrentThread();
212 message_loop->set_thread_name(name_); 201 message_loop_->set_thread_name(name_);
213 message_loop->SetTimerSlack(startup_data_->options.timer_slack); 202 message_loop_->SetTimerSlack(message_loop_timer_slack_);
214 message_loop_ = message_loop.get();
215 203
216 #if defined(OS_WIN) 204 #if defined(OS_WIN)
217 scoped_ptr<win::ScopedCOMInitializer> com_initializer; 205 scoped_ptr<win::ScopedCOMInitializer> com_initializer;
218 if (com_status_ != NONE) { 206 if (com_status_ != NONE) {
219 com_initializer.reset((com_status_ == STA) ? 207 com_initializer.reset((com_status_ == STA) ?
220 new win::ScopedCOMInitializer() : 208 new win::ScopedCOMInitializer() :
221 new win::ScopedCOMInitializer(win::ScopedCOMInitializer::kMTA)); 209 new win::ScopedCOMInitializer(win::ScopedCOMInitializer::kMTA));
222 } 210 }
223 #endif 211 #endif
224 212
225 // Let the thread do extra initialization. 213 // Let the thread do extra initialization.
226 // Let's do this before signaling we are started. 214 Init();
227 Init();
228 215
216 {
217 AutoLock lock(lock_);
229 running_ = true; 218 running_ = true;
230 startup_data_->event.Signal(); 219 }
231 // startup_data_ can't be touched anymore since the starting thread is now
232 // unlocked.
233 220
234 Run(message_loop_); 221 start_event_->Signal();
222
223 Run(message_loop_);
224
225 {
226 AutoLock lock(lock_);
235 running_ = false; 227 running_ = false;
228 }
236 229
237 // Let the thread do extra cleanup. 230 // Let the thread do extra cleanup.
238 CleanUp(); 231 CleanUp();
239 232
240 #if defined(OS_WIN) 233 #if defined(OS_WIN)
241 com_initializer.reset(); 234 com_initializer.reset();
242 #endif 235 #endif
243 236
244 // Assert that MessageLoop::Quit was called by ThreadQuitHelper. 237 // Assert that MessageLoop::Quit was called by ThreadQuitHelper.
245 DCHECK(GetThreadWasQuitProperly()); 238 DCHECK(GetThreadWasQuitProperly());
246 239
247 // We can't receive messages anymore. 240 // We can't receive messages anymore.
248 message_loop_ = NULL; 241 // (The message loop is destructed at the end of this block)
249 } 242 message_loop_ = NULL;
250 } 243 }
251 244
252 } // namespace base 245 } // namespace base
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698