| 6 |
| 7 | #include <type_traits> |
| 8 |
| 9 | #include "base/bind.h" |
| 10 | #include "base/bind_helpers.h" |
| 11 | #include "base/lazy_instance.h" |
| 12 | #include "base/location.h" |
| 13 | #include "base/logging.h" |
| 14 | #include "base/memory/ptr_util.h" |
| 15 | #include "base/memory/scoped_refptr.h" |
| 16 | #include "base/message_loop/message_loop_current.h" |
| 17 | #include "base/message_loop/message_pump.h" |
| 18 | #include "base/run_loop.h" |
| 19 | #include "base/synchronization/waitable_event.h" |
| 20 | #include "base/task/sequence_manager/sequence_manager_impl.h" |
| 21 | #include "base/task/sequence_manager/task_queue.h" |
| 22 | #include "base/task/simple_task_executor.h" |
| 23 | #include "base/third_party/dynamic_annotations/dynamic_annotations.h" |
| 24 | #include "base/threading/thread_id_name_manager.h" |
| 25 | #include "base/threading/thread_local.h" |
| 26 | #include "base/threading/thread_restrictions.h" |
| 27 | #include "base/threading/thread_task_runner_handle.h" |
| 28 | #include "build/build_config.h" |
| 29 |
| 30 | #if defined(OS_POSIX) && !defined(OS_NACL) |
| 31 | #include "base/files/file_descriptor_watcher_posix.h" |
| 32 | #endif |
| 33 |
| 34 | #if defined(OS_WIN) |
| 35 | #include "base/win/scoped_com_initializer.h" |
| 36 | #endif |
| 37 |
| 38 | namespace base { |
| 39 |
| 40 | namespace { |
| 41 |
| 42 | // We use this thread-local variable to record whether or not a thread exited |
| 43 | // because its Stop method was called. This allows us to catch cases where |
| 44 | // MessageLoop::QuitWhenIdle() is called directly, which is unexpected when |
| 45 | // using a Thread to setup and run a MessageLoop. |
| 46 | base::LazyInstance<base::ThreadLocalBoolean>::Leaky lazy_tls_bool = |
| 47 | LAZY_INSTANCE_INITIALIZER; |
| 48 |
| 49 | class SequenceManagerThreadDelegate : public Thread::Delegate { |
| 50 | public: |
| 51 | explicit SequenceManagerThreadDelegate( |
| 52 | MessagePumpType message_pump_type, |
| 53 | OnceCallback<std::unique_ptr<MessagePump>()> message_pump_factory, |
| 54 | sequence_manager::TimeDomain* time_domain) |
| 55 | : sequence_manager_( |
| 56 | sequence_manager::internal::SequenceManagerImpl::CreateUnbound( |
| 57 | sequence_manager::SequenceManager::Settings::Builder() |
| 58 | .SetMessagePumpType(message_pump_type) |
| 59 | .Build())), |
| 60 | default_task_queue_(sequence_manager_->CreateTaskQueue( |
| 61 | sequence_manager::TaskQueue::Spec("default_tq") |
| 62 | .SetTimeDomain(time_domain))), |
| 63 | message_pump_factory_(std::move(message_pump_factory)) { |
| 64 | sequence_manager_->SetDefaultTaskRunner(default_task_queue_->task_runner()); |
| 65 | } |
| 66 |
| 67 | ~SequenceManagerThreadDelegate() override = default; |
| 68 |
| 69 | scoped_refptr<SingleThreadTaskRunner> GetDefaultTaskRunner() override { |
| 70 | // Surprisingly this might not be default_task_queue_->task_runner() which |
| 71 | // we set in the constructor. The Thread::Init() method could create a |
| 72 | // SequenceManager on top of the current one and call |
| 73 | // SequenceManager::SetDefaultTaskRunner which would propagate the new |
| 74 | // TaskRunner down to our SequenceManager. Turns out, code actually relies |
| 75 | // on this and somehow relies on |
| 76 | // SequenceManagerThreadDelegate::GetDefaultTaskRunner returning this new |
| 77 | // TaskRunner. So instead of returning default_task_queue_->task_runner() we |
| 78 | // need to query the SequenceManager for it. |
| 79 | // The underlying problem here is that Subclasses of Thread can do crazy |
| 80 | // stuff in Init() but they are not really in control of what happens in the |
| 81 | // Thread::Delegate, as this is passed in on calling StartWithOptions which |
| 82 | // could happen far away from where the Thread is created. We should |
| 83 | // consider getting rid of StartWithOptions, and pass them as a constructor |
| 84 | // argument instead. |
| 85 | return sequence_manager_->GetTaskRunner(); |
| 86 | } |
| 87 |
| 88 | void BindToCurrentThread(TimerSlack timer_slack) override { |
| 89 | sequence_manager_->BindToMessagePump( |
| 90 | std::move(message_pump_factory_).Run()); |
| 91 | sequence_manager_->SetTimerSlack(timer_slack); |
| 92 | simple_task_executor_.emplace(GetDefaultTaskRunner()); |
| 93 | } |
| 94 |
| 95 | private: |
| 96 | std::unique_ptr<sequence_manager::internal::SequenceManagerImpl> |
| 97 | sequence_manager_; |
| 98 | scoped_refptr<sequence_manager::TaskQueue> default_task_queue_; |
| 99 | OnceCallback<std::unique_ptr<MessagePump>()> message_pump_factory_; |
| 100 | base::Optional<SimpleTaskExecutor> simple_task_executor_; |
| 101 | }; |
| 102 |
| 103 | } // namespace |
| 104 |
| 105 | Thread::Options::Options() = default; |
| 106 |
| 107 | Thread::Options::Options(MessagePumpType type, size_t size) |
| 108 | : message_pump_type(type), stack_size(size) {} |
| 109 |
| 110 | Thread::Options::Options(Options&& other) = default; |
| 111 |
| 112 | Thread::Options::~Options() = default; |
| 113 |
| 114 | Thread::Thread(const std::string& name) |
| 115 | : id_event_(WaitableEvent::ResetPolicy::MANUAL, |
| 116 | WaitableEvent::InitialState::NOT_SIGNALED), |
| 117 | name_(name), |
| 118 | start_event_(WaitableEvent::ResetPolicy::MANUAL, |
| 119 | WaitableEvent::InitialState::NOT_SIGNALED) { |
| 120 | // Only bind the sequence on Start(): the state is constant between |
| 121 | // construction and Start() and it's thus valid for Start() to be called on |
| 122 | // another sequence as long as every other operation is then performed on that |
| 123 | // sequence. |
| 124 | owning_sequence_checker_.DetachFromSequence(); |
| 125 | } |
| 126 |
| 127 | Thread::~Thread() { |
| 128 | Stop(); |
| 129 | } |
| 130 |
| 131 | bool Thread::Start() { |
| 132 | DCHECK(owning_sequence_checker_.CalledOnValidSequence()); |
| 133 |
| 134 | Options options; |
| 135 | #if defined(OS_WIN) |
| 136 | if (com_status_ == STA) |
| 137 | options.message_pump_type = MessagePumpType::UI; |
| 138 | #endif |
| 139 | return StartWithOptions(options); |
| 140 | } |
| 141 |
| 142 | bool Thread::StartWithOptions(const Options& options) { |
| 143 | DCHECK(owning_sequence_checker_.CalledOnValidSequence()); |
| 144 | DCHECK(!delegate_); |
| 145 | DCHECK(!IsRunning()); |
| 146 | DCHECK(!stopping_) << "Starting a non-joinable thread a second time? That's " |
| 147 | << "not allowed!"; |
| 148 | #if defined(OS_WIN) |
| 149 | DCHECK((com_status_ != STA) || |
| 150 | (options.message_pump_type == MessagePumpType::UI)); |
| 151 | #endif |
| 152 |
| 153 | // Reset |id_| here to support restarting the thread. |
| 154 | id_event_.Reset(); |
| 155 | id_ = kInvalidThreadId; |
| 156 |
| 157 | SetThreadWasQuitProperly(false); |
| 158 |
| 159 | timer_slack_ = options.timer_slack; |
| 160 |
| 161 | if (options.delegate) { |
| 162 | DCHECK(!options.message_pump_factory); |
| 163 | DCHECK(!options.task_queue_time_domain); |
| 164 | delegate_ = WrapUnique(options.delegate); |
| 165 | } else if (options.message_pump_factory) { |
| 166 | delegate_ = std::make_unique<SequenceManagerThreadDelegate>( |
| 167 | MessagePumpType::CUSTOM, options.message_pump_factory, |
| 168 | options.task_queue_time_domain); |
| 169 | } else { |
| 170 | delegate_ = std::make_unique<SequenceManagerThreadDelegate>( |
| 171 | options.message_pump_type, |
| 172 | BindOnce([](MessagePumpType type) { return MessagePump::Create(type); }, |
| 173 | options.message_pump_type), |
| 174 | options.task_queue_time_domain); |
| 175 | } |
| 176 |
| 177 | start_event_.Reset(); |
| 178 |
| 179 | // Hold |thread_lock_| while starting the new thread to synchronize with |
| 180 | // Stop() while it's not guaranteed to be sequenced (until crbug/629139 is |
| 181 | // fixed). |
| 182 | { |
| 183 | AutoLock lock(thread_lock_); |
| 184 | bool success = |
| 185 | options.joinable |
| 186 | ? PlatformThread::CreateWithPriority(options.stack_size, this, |
| 187 | &thread_, options.priority) |
| 188 | : PlatformThread::CreateNonJoinableWithPriority( |
| 189 | options.stack_size, this, options.priority); |
| 190 | if (!success) { |
| 191 | DLOG(ERROR) << "failed to create thread"; |
| 192 | return false; |
| 193 | } |
| 194 | } |
| 195 |
| 196 | joinable_ = options.joinable; |
| 197 |
| 198 | return true; |
| 199 | } |
| 200 |
| 201 | bool Thread::StartAndWaitForTesting() { |
| 202 | DCHECK(owning_sequence_checker_.CalledOnValidSequence()); |
| 203 | bool result = Start(); |
| 204 | if (!result) |
| 205 | return false; |
| 206 | WaitUntilThreadStarted(); |
| 207 | return true; |
| 208 | } |
| 209 |
| 210 | bool Thread::WaitUntilThreadStarted() const { |
| 211 | DCHECK(owning_sequence_checker_.CalledOnValidSequence()); |
| 212 | if (!delegate_) |
| 213 | return false; |
| 214 | // https://crbug.com/918039 |
| 215 | base::ScopedAllowBaseSyncPrimitivesOutsideBlockingScope allow_wait; |
| 216 | start_event_.Wait(); |
| 217 | return true; |
| 218 | } |
| 219 |
| 220 | void Thread::FlushForTesting() { |
| 221 | DCHECK(owning_sequence_checker_.CalledOnValidSequence()); |
| 222 | if (!delegate_) |
| 223 | return; |
| 224 |
| 225 | WaitableEvent done(WaitableEvent::ResetPolicy::AUTOMATIC, |
| 226 | WaitableEvent::InitialState::NOT_SIGNALED); |
| 227 | task_runner()->PostTask(FROM_HERE, |
| 228 | BindOnce(&WaitableEvent::Signal, Unretained(&done))); |
| 229 | done.Wait(); |
| 230 | } |
| 231 |
| 232 | void Thread::Stop() { |
| 233 | DCHECK(joinable_); |
| 234 |
| 235 | // TODO(gab): Fix improper usage of this API (http://crbug.com/629139) and |
| 236 | // enable this check, until then synchronization with Start() via |
| 237 | // |thread_lock_| is required... |
| 238 | // DCHECK(owning_sequence_checker_.CalledOnValidSequence()); |
| 239 | AutoLock lock(thread_lock_); |
| 240 |
| 241 | StopSoon(); |
| 242 |
| 243 | // Can't join if the |thread_| is either already gone or is non-joinable. |
| 244 | if (thread_.is_null()) |
| 245 | return; |
| 246 |
| 247 | // Wait for the thread to exit. |
| 248 | // |
| 249 | // TODO(darin): Unfortunately, we need to keep |delegate_| around |
| 250 | // until the thread exits. Some consumers are abusing the API. Make them stop. |
| 251 | PlatformThread::Join(thread_); |
| 252 | thread_ = base::PlatformThreadHandle(); |
| 253 |
| 254 | // The thread should release |delegate_| on exit (note: Join() adds |
| 255 | // an implicit memory barrier and no lock is thus required for this check). |
| 256 | DCHECK(!delegate_); |
| 257 |
| 258 | stopping_ = false; |
| 259 | } |
| 260 |
| 261 | void Thread::StopSoon() { |
| 262 | // TODO(gab): Fix improper usage of this API (http://crbug.com/629139) and |
| 263 | // enable this check. |
| 264 | // DCHECK(owning_sequence_checker_.CalledOnValidSequence()); |
| 265 |
| 266 | if (stopping_ || !delegate_) |
| 267 | return; |
| 268 |
| 269 | stopping_ = true; |
| 270 |
| 271 | task_runner()->PostTask( |
| 272 | FROM_HERE, base::BindOnce(&Thread::ThreadQuitHelper, Unretained(this))); |
| 273 | } |
| 274 |
| 275 | void Thread::DetachFromSequence() { |
| 276 | DCHECK(owning_sequence_checker_.CalledOnValidSequence()); |
| 277 | owning_sequence_checker_.DetachFromSequence(); |
| 278 | } |
| 279 |
| 280 | PlatformThreadId Thread::GetThreadId() const { |
| 281 | // If the thread is created but not started yet, wait for |id_| being ready. |
| 282 | base::ScopedAllowBaseSyncPrimitivesOutsideBlockingScope allow_wait; |
| 283 | id_event_.Wait(); |
| 284 | return id_; |
| 285 | } |
| 286 |
| 287 | bool Thread::IsRunning() const { |
| 288 | // TODO(gab): Fix improper usage of this API (http://crbug.com/629139) and |
| 289 | // enable this check. |
| 290 | // DCHECK(owning_sequence_checker_.CalledOnValidSequence()); |
| 291 |
| 292 | // If the thread's already started (i.e. |delegate_| is non-null) and |
| 293 | // not yet requested to stop (i.e. |stopping_| is false) we can just return |
| 294 | // true. (Note that |stopping_| is touched only on the same sequence that |
| 295 | // starts / started the new thread so we need no locking here.) |
| 296 | if (delegate_ && !stopping_) |
| 297 | return true; |
| 298 | // Otherwise check the |running_| flag, which is set to true by the new thread |
| 299 | // only while it is inside Run(). |
| 300 | AutoLock lock(running_lock_); |
| 301 | return running_; |
| 302 | } |
| 303 |
| 304 | void Thread::Run(RunLoop* run_loop) { |
| 305 | // Overridable protected method to be called from our |thread_| only. |
| 306 | DCHECK(id_event_.IsSignaled()); |
| 307 | DCHECK_EQ(id_, PlatformThread::CurrentId()); |
| 308 |
| 309 | run_loop->Run(); |
| 310 | } |
| 311 |
| 312 | // static |
| 313 | void Thread::SetThreadWasQuitProperly(bool flag) { |
| 314 | lazy_tls_bool.Pointer()->Set(flag); |
| 315 | } |
| 316 |
| 317 | // static |
| 318 | bool Thread::GetThreadWasQuitProperly() { |
| 319 | bool quit_properly = true; |
| 320 | #if DCHECK_IS_ON() |
| 321 | quit_properly = lazy_tls_bool.Pointer()->Get(); |
| 322 | #endif |
| 323 | return quit_properly; |
| 324 | } |
| 325 |
| 326 | void Thread::ThreadMain() { |
| 327 | // First, make GetThreadId() available to avoid deadlocks. It could be called |
| 328 | // any place in the following thread initialization code. |
| 329 | DCHECK(!id_event_.IsSignaled()); |
| 330 | // Note: this read of |id_| while |id_event_| isn't signaled is exceptionally |
| 331 | // okay because ThreadMain has a happens-after relationship with the other |
| 332 | // write in StartWithOptions(). |
| 333 | DCHECK_EQ(kInvalidThreadId, id_); |
| 334 | id_ = PlatformThread::CurrentId(); |
| 335 | DCHECK_NE(kInvalidThreadId, id_); |
| 336 | id_event_.Signal(); |
| 337 |
| 338 | // Complete the initialization of our Thread object. |
| 339 | PlatformThread::SetName(name_.c_str()); |
| 340 | ANNOTATE_THREAD_NAME(name_.c_str()); // Tell the name to race detector. |
| 341 |
| 342 | // Lazily initialize the |message_loop| so that it can run on this thread. |
| 343 | DCHECK(delegate_); |
| 344 | // This binds MessageLoopCurrent and ThreadTaskRunnerHandle. |
| 345 | delegate_->BindToCurrentThread(timer_slack_); |
| 346 | DCHECK(MessageLoopCurrent::Get()); |
| 347 | DCHECK(ThreadTaskRunnerHandle::IsSet()); |
| 348 |
| 349 | #if defined(OS_POSIX) && !defined(OS_NACL) |
| 350 | // Allow threads running a MessageLoopForIO to use FileDescriptorWatcher API. |
| 351 | std::unique_ptr<FileDescriptorWatcher> file_descriptor_watcher; |
| 352 | if (MessageLoopCurrentForIO::IsSet()) { |
| 353 | file_descriptor_watcher.reset( |
| 354 | new FileDescriptorWatcher(delegate_->GetDefaultTaskRunner())); |
| 355 | } |
| 356 | #endif |
| 357 |
| 358 | #if defined(OS_WIN) |
| 359 | std::unique_ptr<win::ScopedCOMInitializer> com_initializer; |
| 360 | if (com_status_ != NONE) { |
| 361 | com_initializer.reset( |
| 362 | (com_status_ == STA) |
| 363 | ? new win::ScopedCOMInitializer() |
| 364 | : new win::ScopedCOMInitializer(win::ScopedCOMInitializer::kMTA)); |
| 365 | } |
| 366 | #endif |
| 367 |
| 368 | // Let the thread do extra initialization. |
| 369 | Init(); |
| 370 |
| 371 | { |
| 372 | AutoLock lock(running_lock_); |
| 373 | running_ = true; |
| 374 | } |
| 375 |
| 376 | start_event_.Signal(); |
| 377 |
| 378 | RunLoop run_loop; |
| 379 | run_loop_ = &run_loop; |
| 380 | Run(run_loop_); |
| 381 |
| 382 | { |
| 383 | AutoLock lock(running_lock_); |
| 384 | running_ = false; |
| 385 | } |
| 386 |
| 387 | // Let the thread do extra cleanup. |
| 388 | CleanUp(); |
| 389 |
| 390 | #if defined(OS_WIN) |
| 391 | com_initializer.reset(); |
| 392 | #endif |
| 393 |
| 394 | DCHECK(GetThreadWasQuitProperly()); |
| 395 |
| 396 | // We can't receive messages anymore. |
| 397 | // (The message loop is destructed at the end of this block) |
| 398 | delegate_.reset(); |
| 399 | run_loop_ = nullptr; |
| 400 | } |
| 401 |
| 402 | void Thread::ThreadQuitHelper() { |
| 403 | DCHECK(run_loop_); |
| 404 | run_loop_->QuitWhenIdle(); |
| 405 | SetThreadWasQuitProperly(true); |
| 406 | } |
| 407 |
| 408 | } // namespace base |
| 409 |