2 * Copyright 2014 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>
66 if (LIKELY(ptr != nullptr)) {
70 // separated new item creation out to speed up the fast path.
74 T* operator->() const {
78 T& operator*() const {
82 void reset(T* newPtr = nullptr) {
86 typedef typename ThreadLocalPtr<T,Tag>::Accessor Accessor;
87 Accessor accessAllThreads() const {
88 return tlp_.accessAllThreads();
92 ThreadLocal(ThreadLocal&&) = default;
93 ThreadLocal& operator=(ThreadLocal&&) = default;
97 ThreadLocal(const ThreadLocal&) = delete;
98 ThreadLocal& operator=(const ThreadLocal&) = delete;
106 mutable ThreadLocalPtr<T,Tag> tlp_;
110 * The idea here is that __thread is faster than pthread_getspecific, so we
111 * keep a __thread array of pointers to objects (ThreadEntry::elements) where
112 * each array has an index for each unique instance of the ThreadLocalPtr
113 * object. Each ThreadLocalPtr object has a unique id that is an index into
114 * these arrays so we can fetch the correct object from thread local storage
117 * In order to prevent unbounded growth of the id space and thus huge
118 * ThreadEntry::elements, arrays, for example due to continuous creation and
119 * destruction of ThreadLocalPtr objects, we keep a set of all active
120 * instances. When an instance is destroyed we remove it from the active
121 * set and insert the id into freeIds_ for reuse. These operations require a
122 * global mutex, but only happen at construction and destruction time.
124 * We use a single global pthread_key_t per Tag to manage object destruction and
125 * memory cleanup upon thread exit because there is a finite number of
126 * pthread_key_t's available per machine.
128 * NOTE: Apple platforms don't support the same semantics for __thread that
129 * Linux does (and it's only supported at all on i386). For these, use
130 * pthread_setspecific()/pthread_getspecific() for the per-thread
131 * storage. Windows (MSVC and GCC) does support the same semantics
132 * with __declspec(thread)
135 template<class T, class Tag=void>
136 class ThreadLocalPtr {
138 ThreadLocalPtr() : id_(threadlocal_detail::StaticMeta<Tag>::create()) { }
140 ThreadLocalPtr(ThreadLocalPtr&& other) : id_(other.id_) {
144 ThreadLocalPtr& operator=(ThreadLocalPtr&& other) {
145 assert(this != &other);
157 return static_cast<T*>(threadlocal_detail::StaticMeta<Tag>::get(id_).ptr);
160 T* operator->() const {
164 T& operator*() const {
169 threadlocal_detail::ElementWrapper& w =
170 threadlocal_detail::StaticMeta<Tag>::get(id_);
172 return static_cast<T*>(w.release());
175 void reset(T* newPtr = nullptr) {
176 threadlocal_detail::ElementWrapper& w =
177 threadlocal_detail::StaticMeta<Tag>::get(id_);
178 if (w.ptr != newPtr) {
179 w.dispose(TLPDestructionMode::THIS_THREAD);
184 explicit operator bool() const {
185 return get() != nullptr;
189 * reset() with a custom deleter:
190 * deleter(T* ptr, TLPDestructionMode mode)
191 * "mode" is ALL_THREADS if we're destructing this ThreadLocalPtr (and thus
192 * deleting pointers for all threads), and THIS_THREAD if we're only deleting
193 * the member for one thread (because of thread exit or reset())
195 template <class Deleter>
196 void reset(T* newPtr, Deleter deleter) {
197 threadlocal_detail::ElementWrapper& w =
198 threadlocal_detail::StaticMeta<Tag>::get(id_);
199 if (w.ptr != newPtr) {
200 w.dispose(TLPDestructionMode::THIS_THREAD);
201 w.set(newPtr, deleter);
205 // Holds a global lock for iteration through all thread local child objects.
206 // Can be used as an iterable container.
207 // Use accessAllThreads() to obtain one.
209 friend class ThreadLocalPtr<T,Tag>;
211 threadlocal_detail::StaticMeta<Tag>& meta_;
217 friend class Iterator;
219 // The iterators obtained from Accessor are bidirectional iterators.
220 class Iterator : public boost::iterator_facade<
223 boost::bidirectional_traversal_tag> { // traversal
224 friend class Accessor;
225 friend class boost::iterator_core_access;
226 const Accessor* const accessor_;
227 threadlocal_detail::ThreadEntry* e_;
239 T& dereference() const {
240 return *static_cast<T*>(e_->elements[accessor_->id_].ptr);
243 bool equal(const Iterator& other) const {
244 return (accessor_->id_ == other.accessor_->id_ &&
248 explicit Iterator(const Accessor* accessor)
249 : accessor_(accessor),
250 e_(&accessor_->meta_.head_) {
254 return (e_->elements &&
255 accessor_->id_ < e_->elementsCapacity &&
256 e_->elements[accessor_->id_].ptr);
259 void incrementToValid() {
260 for (; e_ != &accessor_->meta_.head_ && !valid(); e_ = e_->next) { }
263 void decrementToValid() {
264 for (; e_ != &accessor_->meta_.head_ && !valid(); e_ = e_->prev) { }
272 Iterator begin() const {
273 return ++Iterator(this);
276 Iterator end() const {
277 return Iterator(this);
280 Accessor(const Accessor&) = delete;
281 Accessor& operator=(const Accessor&) = delete;
283 Accessor(Accessor&& other) noexcept
284 : meta_(other.meta_),
288 other.lock_ = nullptr;
291 Accessor& operator=(Accessor&& other) noexcept {
292 // Each Tag has its own unique meta, and accessors with different Tags
293 // have different types. So either *this is empty, or this and other
294 // have the same tag. But if they have the same tag, they have the same
295 // meta (and lock), so they'd both hold the lock at the same time,
296 // which is impossible, which leaves only one possible scenario --
297 // *this is empty. Assert it.
298 assert(&meta_ == &other.meta_);
299 assert(lock_ == nullptr);
301 swap(lock_, other.lock_);
302 swap(id_, other.id_);
306 : meta_(threadlocal_detail::StaticMeta<Tag>::instance()),
312 explicit Accessor(int id)
313 : meta_(threadlocal_detail::StaticMeta<Tag>::instance()),
314 lock_(&meta_.lock_) {
328 // accessor allows a client to iterate through all thread local child
329 // elements of this ThreadLocal instance. Holds a global lock for each <Tag>
330 Accessor accessAllThreads() const {
331 static_assert(!std::is_same<Tag, void>::value,
332 "Must use a unique Tag to use the accessAllThreads feature");
333 return Accessor(id_);
339 threadlocal_detail::StaticMeta<Tag>::destroy(id_);
344 ThreadLocalPtr(const ThreadLocalPtr&) = delete;
345 ThreadLocalPtr& operator=(const ThreadLocalPtr&) = delete;
347 int id_; // every instantiation has a unique id
352 #endif /* FOLLY_THREADLOCAL_H_ */