2 * Copyright 2012 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.
27 * Intended use is for frequent write, infrequent read data access patterns such
30 * There are two classes here - ThreadLocal and ThreadLocalPtr. ThreadLocalPtr
31 * has semantics similar to boost::thread_specific_ptr. ThreadLocal is a thin
32 * wrapper around ThreadLocalPtr that manages allocation automatically.
34 * @author Spencer Ahrens (sahrens)
37 #ifndef FOLLY_THREADLOCAL_H_
38 #define FOLLY_THREADLOCAL_H_
40 #include "folly/Portability.h"
41 #include <boost/iterator/iterator_facade.hpp>
42 #include "folly/Likely.h"
43 #include <type_traits>
45 // Use noexcept on gcc 4.6 or higher
48 # ifdef HAVE_FEATURES_H
49 # include <features.h>
50 # if __GNUC_PREREQ(4,6)
51 # define FOLLY_NOEXCEPT noexcept
52 # define FOLLY_ASSERT(x) x
57 #ifndef FOLLY_NOEXCEPT
58 # define FOLLY_NOEXCEPT
59 # define FOLLY_ASSERT(x) /**/
63 enum class TLPDestructionMode {
69 #include "folly/detail/ThreadLocalDetail.h"
73 template<class T, class Tag> class ThreadLocalPtr;
75 template<class T, class Tag=void>
82 if (UNLIKELY(ptr == nullptr)) {
89 T* operator->() const {
93 T& operator*() const {
97 void reset(T* newPtr = nullptr) {
101 typedef typename ThreadLocalPtr<T,Tag>::Accessor Accessor;
102 Accessor accessAllThreads() const {
103 return tlp_.accessAllThreads();
107 ThreadLocal(ThreadLocal&&) = default;
108 ThreadLocal& operator=(ThreadLocal&&) = default;
112 ThreadLocal(const ThreadLocal&) = delete;
113 ThreadLocal& operator=(const ThreadLocal&) = delete;
115 mutable ThreadLocalPtr<T,Tag> tlp_;
119 * The idea here is that __thread is faster than pthread_getspecific, so we
120 * keep a __thread array of pointers to objects (ThreadEntry::elements) where
121 * each array has an index for each unique instance of the ThreadLocalPtr
122 * object. Each ThreadLocalPtr object has a unique id that is an index into
123 * these arrays so we can fetch the correct object from thread local storage
126 * In order to prevent unbounded growth of the id space and thus huge
127 * ThreadEntry::elements, arrays, for example due to continuous creation and
128 * destruction of ThreadLocalPtr objects, we keep a set of all active
129 * instances. When an instance is destroyed we remove it from the active
130 * set and insert the id into freeIds_ for reuse. These operations require a
131 * global mutex, but only happen at construction and destruction time.
133 * We use a single global pthread_key_t per Tag to manage object destruction and
134 * memory cleanup upon thread exit because there is a finite number of
135 * pthread_key_t's available per machine.
138 template<class T, class Tag=void>
139 class ThreadLocalPtr {
141 ThreadLocalPtr() : id_(threadlocal_detail::StaticMeta<Tag>::create()) { }
143 ThreadLocalPtr(ThreadLocalPtr&& other) : id_(other.id_) {
147 ThreadLocalPtr& operator=(ThreadLocalPtr&& other) {
148 assert(this != &other);
160 return static_cast<T*>(threadlocal_detail::StaticMeta<Tag>::get(id_).ptr);
163 T* operator->() const {
167 T& operator*() const {
171 void reset(T* newPtr = nullptr) {
172 threadlocal_detail::ElementWrapper& w =
173 threadlocal_detail::StaticMeta<Tag>::get(id_);
174 if (w.ptr != newPtr) {
175 w.dispose(TLPDestructionMode::THIS_THREAD);
180 explicit operator bool() const {
181 return get() != nullptr;
185 * reset() with a custom deleter:
186 * deleter(T* ptr, TLPDestructionMode mode)
187 * "mode" is ALL_THREADS if we're destructing this ThreadLocalPtr (and thus
188 * deleting pointers for all threads), and THIS_THREAD if we're only deleting
189 * the member for one thread (because of thread exit or reset())
191 template <class Deleter>
192 void reset(T* newPtr, Deleter deleter) {
193 threadlocal_detail::ElementWrapper& w =
194 threadlocal_detail::StaticMeta<Tag>::get(id_);
195 if (w.ptr != newPtr) {
196 w.dispose(TLPDestructionMode::THIS_THREAD);
197 w.set(newPtr, deleter);
201 // Holds a global lock for iteration through all thread local child objects.
202 // Can be used as an iterable container.
203 // Use accessAllThreads() to obtain one.
205 friend class ThreadLocalPtr<T,Tag>;
207 threadlocal_detail::StaticMeta<Tag>& meta_;
213 friend class Iterator;
215 // The iterators obtained from Accessor are bidirectional iterators.
216 class Iterator : public boost::iterator_facade<
219 boost::bidirectional_traversal_tag> { // traversal
220 friend class Accessor;
221 friend class boost::iterator_core_access;
222 const Accessor* const accessor_;
223 threadlocal_detail::ThreadEntry* e_;
235 T& dereference() const {
236 return *static_cast<T*>(e_->elements[accessor_->id_].ptr);
239 bool equal(const Iterator& other) const {
240 return (accessor_->id_ == other.accessor_->id_ &&
244 explicit Iterator(const Accessor* accessor)
245 : accessor_(accessor),
246 e_(&accessor_->meta_.head_) {
250 return (e_->elements &&
251 accessor_->id_ < e_->elementsCapacity &&
252 e_->elements[accessor_->id_].ptr);
255 void incrementToValid() {
256 for (; e_ != &accessor_->meta_.head_ && !valid(); e_ = e_->next) { }
259 void decrementToValid() {
260 for (; e_ != &accessor_->meta_.head_ && !valid(); e_ = e_->prev) { }
268 Iterator begin() const {
269 return ++Iterator(this);
272 Iterator end() const {
273 return Iterator(this);
276 Accessor(const Accessor&) = delete;
277 Accessor& operator=(const Accessor&) = delete;
279 Accessor(Accessor&& other) FOLLY_NOEXCEPT
280 : meta_(other.meta_),
284 other.lock_ = nullptr;
287 Accessor& operator=(Accessor&& other) FOLLY_NOEXCEPT {
288 // Each Tag has its own unique meta, and accessors with different Tags
289 // have different types. So either *this is empty, or this and other
290 // have the same tag. But if they have the same tag, they have the same
291 // meta (and lock), so they'd both hold the lock at the same time,
292 // which is impossible, which leaves only one possible scenario --
293 // *this is empty. Assert it.
294 assert(&meta_ == &other.meta_);
295 assert(lock_ == nullptr);
297 swap(lock_, other.lock_);
298 swap(id_, other.id_);
302 : meta_(threadlocal_detail::StaticMeta<Tag>::instance()),
308 explicit Accessor(int id)
309 : meta_(threadlocal_detail::StaticMeta<Tag>::instance()),
310 lock_(&meta_.lock_) {
324 // accessor allows a client to iterate through all thread local child
325 // elements of this ThreadLocal instance. Holds a global lock for each <Tag>
326 Accessor accessAllThreads() const {
327 FOLLY_ASSERT(static_assert(!std::is_same<Tag, void>::value,
328 "Must use a unique Tag to use the accessAllThreads feature"));
329 return Accessor(id_);
335 threadlocal_detail::StaticMeta<Tag>::destroy(id_);
340 ThreadLocalPtr(const ThreadLocalPtr&) = delete;
341 ThreadLocalPtr& operator=(const ThreadLocalPtr&) = delete;
343 int id_; // every instantiation has a unique id
346 #undef FOLLY_NOEXCEPT
350 #endif /* FOLLY_THREADLOCAL_H_ */