1 // Copyright 2016 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. 4 5 #include "base/threading/thread_task_runner_handle.h" 6 7 #include <utility> 8 9 #include "base/lazy_instance.h" 10 #include "base/logging.h" 11 #include "base/threading/sequenced_task_runner_handle.h" 12 #include "base/threading/thread_local.h" 13 14 namespace base { 15 16 namespace { 17 18 base::LazyInstance<base::ThreadLocalPointer<ThreadTaskRunnerHandle>>::Leaky 19 lazy_tls_ptr = LAZY_INSTANCE_INITIALIZER; 20 21 } // namespace 22 23 // static 24 scoped_refptr<SingleThreadTaskRunner> ThreadTaskRunnerHandle::Get() { 25 ThreadTaskRunnerHandle* current = lazy_tls_ptr.Pointer()->Get(); 26 DCHECK(current); 27 return current->task_runner_; 28 } 29 30 // static 31 bool ThreadTaskRunnerHandle::IsSet() { 32 return !!lazy_tls_ptr.Pointer()->Get(); 33 } 34 35 ThreadTaskRunnerHandle::ThreadTaskRunnerHandle( 36 scoped_refptr<SingleThreadTaskRunner> task_runner) 37 : task_runner_(std::move(task_runner)) { 38 DCHECK(task_runner_->BelongsToCurrentThread()); 39 // No SequencedTaskRunnerHandle (which includes ThreadTaskRunnerHandles) 40 // should already be set for this thread. 41 DCHECK(!SequencedTaskRunnerHandle::IsSet()); 42 lazy_tls_ptr.Pointer()->Set(this); 43 } 44 45 ThreadTaskRunnerHandle::~ThreadTaskRunnerHandle() { 46 DCHECK(task_runner_->BelongsToCurrentThread()); 47 DCHECK_EQ(lazy_tls_ptr.Pointer()->Get(), this); 48 lazy_tls_ptr.Pointer()->Set(nullptr); 49 } 50 51 } // namespace base 52