2 * Copyright 2017 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * Improved thread local storage for non-trivial types (similar speed as
19 * pthread_getspecific but only consumes a single pthread_key_t, and 4x faster
20 * than boost::thread_specific_ptr).
22 * Also includes an accessor interface to walk all the thread local child
23 * objects of a parent. accessAllThreads() initializes an accessor which holds
24 * a global lock *that blocks all creation and destruction of ThreadLocal
25 * objects with the same Tag* and can be used as an iterable container.
26 * accessAllThreads() can race with destruction of thread-local elements. We
27 * provide a strict mode which is dangerous because it requires the access lock
28 * to be held while destroying thread-local elements which could cause
29 * deadlocks. We gate this mode behind the AccessModeStrict template parameter.
31 * Intended use is for frequent write, infrequent read data access patterns such
34 * There are two classes here - ThreadLocal and ThreadLocalPtr. ThreadLocalPtr
35 * has semantics similar to boost::thread_specific_ptr. ThreadLocal is a thin
36 * wrapper around ThreadLocalPtr that manages allocation automatically.
38 * @author Spencer Ahrens (sahrens)
43 #include <boost/iterator/iterator_facade.hpp>
44 #include <folly/Likely.h>
45 #include <folly/Portability.h>
46 #include <folly/ScopeGuard.h>
47 #include <folly/SharedMutex.h>
48 #include <folly/detail/ThreadLocalDetail.h>
49 #include <type_traits>
54 template <class T, class Tag, class AccessMode>
57 template <class T, class Tag = void, class AccessMode = void>
60 constexpr ThreadLocal() : constructor_([]() {
64 explicit ThreadLocal(std::function<T*()> constructor) :
65 constructor_(constructor) {
70 if (LIKELY(ptr != nullptr)) {
74 // separated new item creation out to speed up the fast path.
78 T* operator->() const {
82 T& operator*() const {
86 void reset(T* newPtr = nullptr) {
90 typedef typename ThreadLocalPtr<T, Tag, AccessMode>::Accessor Accessor;
91 Accessor accessAllThreads() const {
92 return tlp_.accessAllThreads();
96 ThreadLocal(ThreadLocal&&) = default;
97 ThreadLocal& operator=(ThreadLocal&&) = default;
101 ThreadLocal(const ThreadLocal&) = delete;
102 ThreadLocal& operator=(const ThreadLocal&) = delete;
105 auto ptr = constructor_();
110 mutable ThreadLocalPtr<T, Tag, AccessMode> tlp_;
111 std::function<T*()> constructor_;
115 * The idea here is that __thread is faster than pthread_getspecific, so we
116 * keep a __thread array of pointers to objects (ThreadEntry::elements) where
117 * each array has an index for each unique instance of the ThreadLocalPtr
118 * object. Each ThreadLocalPtr object has a unique id that is an index into
119 * these arrays so we can fetch the correct object from thread local storage
122 * In order to prevent unbounded growth of the id space and thus huge
123 * ThreadEntry::elements, arrays, for example due to continuous creation and
124 * destruction of ThreadLocalPtr objects, we keep a set of all active
125 * instances. When an instance is destroyed we remove it from the active
126 * set and insert the id into freeIds_ for reuse. These operations require a
127 * global mutex, but only happen at construction and destruction time.
129 * We use a single global pthread_key_t per Tag to manage object destruction and
130 * memory cleanup upon thread exit because there is a finite number of
131 * pthread_key_t's available per machine.
133 * NOTE: Apple platforms don't support the same semantics for __thread that
134 * Linux does (and it's only supported at all on i386). For these, use
135 * pthread_setspecific()/pthread_getspecific() for the per-thread
136 * storage. Windows (MSVC and GCC) does support the same semantics
137 * with __declspec(thread)
140 template <class T, class Tag = void, class AccessMode = void>
141 class ThreadLocalPtr {
143 typedef threadlocal_detail::StaticMeta<Tag, AccessMode> StaticMeta;
146 constexpr ThreadLocalPtr() : id_() {}
148 ThreadLocalPtr(ThreadLocalPtr&& other) noexcept :
149 id_(std::move(other.id_)) {
152 ThreadLocalPtr& operator=(ThreadLocalPtr&& other) {
153 assert(this != &other);
155 id_ = std::move(other.id_);
164 threadlocal_detail::ElementWrapper& w = StaticMeta::instance().get(&id_);
165 return static_cast<T*>(w.ptr);
168 T* operator->() const {
172 T& operator*() const {
177 threadlocal_detail::ElementWrapper& w = StaticMeta::instance().get(&id_);
179 return static_cast<T*>(w.release());
182 void reset(T* newPtr = nullptr) {
183 auto guard = makeGuard([&] { delete newPtr; });
184 threadlocal_detail::ElementWrapper& w = StaticMeta::instance().get(&id_);
186 w.dispose(TLPDestructionMode::THIS_THREAD);
191 explicit operator bool() const {
192 return get() != nullptr;
196 * reset() that transfers ownership from a smart pointer
201 typename = typename std::enable_if<
202 std::is_convertible<SourceT*, T*>::value>::type>
203 void reset(std::unique_ptr<SourceT, Deleter> source) {
204 auto deleter = [delegate = source.get_deleter()](
205 T * ptr, TLPDestructionMode) {
208 reset(source.release(), deleter);
212 * reset() that transfers ownership from a smart pointer with the default
217 typename = typename std::enable_if<
218 std::is_convertible<SourceT*, T*>::value>::type>
219 void reset(std::unique_ptr<SourceT> source) {
220 reset(source.release());
224 * reset() with a custom deleter:
225 * deleter(T* ptr, TLPDestructionMode mode)
226 * "mode" is ALL_THREADS if we're destructing this ThreadLocalPtr (and thus
227 * deleting pointers for all threads), and THIS_THREAD if we're only deleting
228 * the member for one thread (because of thread exit or reset()).
229 * Invoking the deleter must not throw.
231 template <class Deleter>
232 void reset(T* newPtr, const Deleter& deleter) {
233 auto guard = makeGuard([&] {
235 deleter(newPtr, TLPDestructionMode::THIS_THREAD);
238 threadlocal_detail::ElementWrapper& w = StaticMeta::instance().get(&id_);
239 w.dispose(TLPDestructionMode::THIS_THREAD);
241 w.set(newPtr, deleter);
244 // Holds a global lock for iteration through all thread local child objects.
245 // Can be used as an iterable container.
246 // Use accessAllThreads() to obtain one.
248 friend class ThreadLocalPtr<T, Tag, AccessMode>;
250 threadlocal_detail::StaticMetaBase& meta_;
251 SharedMutex* accessAllThreadsLock_;
257 friend class Iterator;
259 // The iterators obtained from Accessor are bidirectional iterators.
260 class Iterator : public boost::iterator_facade<
263 boost::bidirectional_traversal_tag> { // traversal
264 friend class Accessor;
265 friend class boost::iterator_core_access;
266 const Accessor* accessor_;
267 threadlocal_detail::ThreadEntry* e_;
279 T& dereference() const {
280 return *static_cast<T*>(e_->elements[accessor_->id_].ptr);
283 bool equal(const Iterator& other) const {
284 return (accessor_->id_ == other.accessor_->id_ &&
288 explicit Iterator(const Accessor* accessor)
289 : accessor_(accessor),
290 e_(&accessor_->meta_.head_) {
294 return (e_->elements &&
295 accessor_->id_ < e_->elementsCapacity &&
296 e_->elements[accessor_->id_].ptr);
299 void incrementToValid() {
300 for (; e_ != &accessor_->meta_.head_ && !valid(); e_ = e_->next) { }
303 void decrementToValid() {
304 for (; e_ != &accessor_->meta_.head_ && !valid(); e_ = e_->prev) { }
312 Iterator begin() const {
313 return ++Iterator(this);
316 Iterator end() const {
317 return Iterator(this);
320 Accessor(const Accessor&) = delete;
321 Accessor& operator=(const Accessor&) = delete;
323 Accessor(Accessor&& other) noexcept
324 : meta_(other.meta_),
325 accessAllThreadsLock_(other.accessAllThreadsLock_),
329 other.accessAllThreadsLock_ = nullptr;
330 other.lock_ = nullptr;
333 Accessor& operator=(Accessor&& other) noexcept {
334 // Each Tag has its own unique meta, and accessors with different Tags
335 // have different types. So either *this is empty, or this and other
336 // have the same tag. But if they have the same tag, they have the same
337 // meta (and lock), so they'd both hold the lock at the same time,
338 // which is impossible, which leaves only one possible scenario --
339 // *this is empty. Assert it.
340 assert(&meta_ == &other.meta_);
341 assert(lock_ == nullptr);
343 swap(accessAllThreadsLock_, other.accessAllThreadsLock_);
344 swap(lock_, other.lock_);
345 swap(id_, other.id_);
349 : meta_(threadlocal_detail::StaticMeta<Tag, AccessMode>::instance()),
350 accessAllThreadsLock_(nullptr),
355 explicit Accessor(uint32_t id)
356 : meta_(threadlocal_detail::StaticMeta<Tag, AccessMode>::instance()),
357 accessAllThreadsLock_(&meta_.accessAllThreadsLock_),
358 lock_(&meta_.lock_) {
359 accessAllThreadsLock_->lock();
367 DCHECK(accessAllThreadsLock_ != nullptr);
368 accessAllThreadsLock_->unlock();
371 accessAllThreadsLock_ = nullptr;
376 // accessor allows a client to iterate through all thread local child
377 // elements of this ThreadLocal instance. Holds a global lock for each <Tag>
378 Accessor accessAllThreads() const {
379 static_assert(!std::is_same<Tag, void>::value,
380 "Must use a unique Tag to use the accessAllThreads feature");
381 return Accessor(id_.getOrAllocate(StaticMeta::instance()));
386 StaticMeta::instance().destroy(&id_);
390 ThreadLocalPtr(const ThreadLocalPtr&) = delete;
391 ThreadLocalPtr& operator=(const ThreadLocalPtr&) = delete;
393 mutable typename StaticMeta::EntryID id_;