2 * Copyright 2015 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>
47 enum class TLPDestructionMode {
53 #include <folly/detail/ThreadLocalDetail.h>
57 template<class T, class Tag> class ThreadLocalPtr;
59 template<class T, class Tag=void>
62 constexpr ThreadLocal() : constructor_([]() {
66 explicit ThreadLocal(std::function<T*()> constructor) :
67 constructor_(constructor) {
72 if (LIKELY(ptr != nullptr)) {
76 // separated new item creation out to speed up the fast path.
80 T* operator->() const {
84 T& operator*() const {
88 void reset(T* newPtr = nullptr) {
92 typedef typename ThreadLocalPtr<T,Tag>::Accessor Accessor;
93 Accessor accessAllThreads() const {
94 return tlp_.accessAllThreads();
98 ThreadLocal(ThreadLocal&&) = default;
99 ThreadLocal& operator=(ThreadLocal&&) = default;
103 ThreadLocal(const ThreadLocal&) = delete;
104 ThreadLocal& operator=(const ThreadLocal&) = delete;
107 auto ptr = constructor_();
112 mutable ThreadLocalPtr<T,Tag> tlp_;
113 std::function<T*()> constructor_;
117 * The idea here is that __thread is faster than pthread_getspecific, so we
118 * keep a __thread array of pointers to objects (ThreadEntry::elements) where
119 * each array has an index for each unique instance of the ThreadLocalPtr
120 * object. Each ThreadLocalPtr object has a unique id that is an index into
121 * these arrays so we can fetch the correct object from thread local storage
124 * In order to prevent unbounded growth of the id space and thus huge
125 * ThreadEntry::elements, arrays, for example due to continuous creation and
126 * destruction of ThreadLocalPtr objects, we keep a set of all active
127 * instances. When an instance is destroyed we remove it from the active
128 * set and insert the id into freeIds_ for reuse. These operations require a
129 * global mutex, but only happen at construction and destruction time.
131 * We use a single global pthread_key_t per Tag to manage object destruction and
132 * memory cleanup upon thread exit because there is a finite number of
133 * pthread_key_t's available per machine.
135 * NOTE: Apple platforms don't support the same semantics for __thread that
136 * Linux does (and it's only supported at all on i386). For these, use
137 * pthread_setspecific()/pthread_getspecific() for the per-thread
138 * storage. Windows (MSVC and GCC) does support the same semantics
139 * with __declspec(thread)
142 template<class T, class Tag=void>
143 class ThreadLocalPtr {
145 typedef threadlocal_detail::StaticMeta<Tag> StaticMeta;
147 constexpr ThreadLocalPtr() : id_() {}
149 ThreadLocalPtr(ThreadLocalPtr&& other) noexcept :
150 id_(std::move(other.id_)) {
153 ThreadLocalPtr& operator=(ThreadLocalPtr&& other) {
154 assert(this != &other);
156 id_ = std::move(other.id_);
165 threadlocal_detail::ElementWrapper& w = StaticMeta::get(&id_);
166 return static_cast<T*>(w.ptr);
169 T* operator->() const {
173 T& operator*() const {
178 threadlocal_detail::ElementWrapper& w = StaticMeta::get(&id_);
180 return static_cast<T*>(w.release());
183 void reset(T* newPtr = nullptr) {
184 threadlocal_detail::ElementWrapper& w = StaticMeta::get(&id_);
186 if (w.ptr != newPtr) {
187 w.dispose(TLPDestructionMode::THIS_THREAD);
192 explicit operator bool() const {
193 return get() != nullptr;
197 * reset() with a custom deleter:
198 * deleter(T* ptr, TLPDestructionMode mode)
199 * "mode" is ALL_THREADS if we're destructing this ThreadLocalPtr (and thus
200 * deleting pointers for all threads), and THIS_THREAD if we're only deleting
201 * the member for one thread (because of thread exit or reset())
203 template <class Deleter>
204 void reset(T* newPtr, Deleter deleter) {
205 threadlocal_detail::ElementWrapper& w = StaticMeta::get(&id_);
206 if (w.ptr != newPtr) {
207 w.dispose(TLPDestructionMode::THIS_THREAD);
208 w.set(newPtr, deleter);
212 // Holds a global lock for iteration through all thread local child objects.
213 // Can be used as an iterable container.
214 // Use accessAllThreads() to obtain one.
216 friend class ThreadLocalPtr<T,Tag>;
218 threadlocal_detail::StaticMeta<Tag>& meta_;
224 friend class Iterator;
226 // The iterators obtained from Accessor are bidirectional iterators.
227 class Iterator : public boost::iterator_facade<
230 boost::bidirectional_traversal_tag> { // traversal
231 friend class Accessor;
232 friend class boost::iterator_core_access;
233 const Accessor* const accessor_;
234 threadlocal_detail::ThreadEntry* e_;
246 T& dereference() const {
247 return *static_cast<T*>(e_->elements[accessor_->id_].ptr);
250 bool equal(const Iterator& other) const {
251 return (accessor_->id_ == other.accessor_->id_ &&
255 explicit Iterator(const Accessor* accessor)
256 : accessor_(accessor),
257 e_(&accessor_->meta_.head_) {
261 return (e_->elements &&
262 accessor_->id_ < e_->elementsCapacity &&
263 e_->elements[accessor_->id_].ptr);
266 void incrementToValid() {
267 for (; e_ != &accessor_->meta_.head_ && !valid(); e_ = e_->next) { }
270 void decrementToValid() {
271 for (; e_ != &accessor_->meta_.head_ && !valid(); e_ = e_->prev) { }
279 Iterator begin() const {
280 return ++Iterator(this);
283 Iterator end() const {
284 return Iterator(this);
287 Accessor(const Accessor&) = delete;
288 Accessor& operator=(const Accessor&) = delete;
290 Accessor(Accessor&& other) noexcept
291 : meta_(other.meta_),
295 other.lock_ = nullptr;
298 Accessor& operator=(Accessor&& other) noexcept {
299 // Each Tag has its own unique meta, and accessors with different Tags
300 // have different types. So either *this is empty, or this and other
301 // have the same tag. But if they have the same tag, they have the same
302 // meta (and lock), so they'd both hold the lock at the same time,
303 // which is impossible, which leaves only one possible scenario --
304 // *this is empty. Assert it.
305 assert(&meta_ == &other.meta_);
306 assert(lock_ == nullptr);
308 swap(lock_, other.lock_);
309 swap(id_, other.id_);
313 : meta_(threadlocal_detail::StaticMeta<Tag>::instance()),
319 explicit Accessor(uint32_t id)
320 : meta_(threadlocal_detail::StaticMeta<Tag>::instance()),
321 lock_(&meta_.lock_) {
335 // accessor allows a client to iterate through all thread local child
336 // elements of this ThreadLocal instance. Holds a global lock for each <Tag>
337 Accessor accessAllThreads() const {
338 static_assert(!std::is_same<Tag, void>::value,
339 "Must use a unique Tag to use the accessAllThreads feature");
340 return Accessor(id_.getOrAllocate());
345 StaticMeta::destroy(&id_);
349 ThreadLocalPtr(const ThreadLocalPtr&) = delete;
350 ThreadLocalPtr& operator=(const ThreadLocalPtr&) = delete;
352 mutable typename StaticMeta::EntryID id_;
357 #endif /* FOLLY_THREADLOCAL_H_ */