folly: speed up fastpath of ThreadLocal::get()
[folly.git] / folly / ThreadLocal.h
1 /*
2  * Copyright 2013 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /**
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).
21  *
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  *
27  * Intended use is for frequent write, infrequent read data access patterns such
28  * as counters.
29  *
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.
33  *
34  * @author Spencer Ahrens (sahrens)
35  */
36
37 #ifndef FOLLY_THREADLOCAL_H_
38 #define FOLLY_THREADLOCAL_H_
39
40 #include "folly/Portability.h"
41 #include <boost/iterator/iterator_facade.hpp>
42 #include "folly/Likely.h"
43 #include <type_traits>
44
45 // Use noexcept on gcc 4.6 or higher
46 #undef FOLLY_NOEXCEPT
47 #ifdef __GNUC__
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
53 #  endif
54 # endif
55 #endif
56
57 #ifndef FOLLY_NOEXCEPT
58 #  define FOLLY_NOEXCEPT
59 #  define FOLLY_ASSERT(x) /**/
60 #endif
61
62 namespace folly {
63 enum class TLPDestructionMode {
64   THIS_THREAD,
65   ALL_THREADS
66 };
67 }  // namespace
68
69 #include "folly/detail/ThreadLocalDetail.h"
70
71 namespace folly {
72
73 template<class T, class Tag> class ThreadLocalPtr;
74
75 template<class T, class Tag=void>
76 class ThreadLocal {
77  public:
78   ThreadLocal() { }
79
80   T* get() const {
81     T* ptr = tlp_.get();
82     if (LIKELY(ptr != nullptr)) {
83       return ptr;
84     }
85
86     // separated new item creation out to speed up the fast path.
87     return makeTlp();
88   }
89
90   T* operator->() const {
91     return get();
92   }
93
94   T& operator*() const {
95     return *get();
96   }
97
98   void reset(T* newPtr = nullptr) {
99     tlp_.reset(newPtr);
100   }
101
102   typedef typename ThreadLocalPtr<T,Tag>::Accessor Accessor;
103   Accessor accessAllThreads() const {
104     return tlp_.accessAllThreads();
105   }
106
107   // movable
108   ThreadLocal(ThreadLocal&&) = default;
109   ThreadLocal& operator=(ThreadLocal&&) = default;
110
111  private:
112   // non-copyable
113   ThreadLocal(const ThreadLocal&) = delete;
114   ThreadLocal& operator=(const ThreadLocal&) = delete;
115
116   T* makeTlp() const {
117     T* ptr = new T();
118     tlp_.reset(ptr);
119     return ptr;
120   }
121
122   mutable ThreadLocalPtr<T,Tag> tlp_;
123 };
124
125 /*
126  * The idea here is that __thread is faster than pthread_getspecific, so we
127  * keep a __thread array of pointers to objects (ThreadEntry::elements) where
128  * each array has an index for each unique instance of the ThreadLocalPtr
129  * object.  Each ThreadLocalPtr object has a unique id that is an index into
130  * these arrays so we can fetch the correct object from thread local storage
131  * very efficiently.
132  *
133  * In order to prevent unbounded growth of the id space and thus huge
134  * ThreadEntry::elements, arrays, for example due to continuous creation and
135  * destruction of ThreadLocalPtr objects, we keep a set of all active
136  * instances.  When an instance is destroyed we remove it from the active
137  * set and insert the id into freeIds_ for reuse.  These operations require a
138  * global mutex, but only happen at construction and destruction time.
139  *
140  * We use a single global pthread_key_t per Tag to manage object destruction and
141  * memory cleanup upon thread exit because there is a finite number of
142  * pthread_key_t's available per machine.
143  */
144
145 template<class T, class Tag=void>
146 class ThreadLocalPtr {
147  public:
148   ThreadLocalPtr() : id_(threadlocal_detail::StaticMeta<Tag>::create()) { }
149
150   ThreadLocalPtr(ThreadLocalPtr&& other) : id_(other.id_) {
151     other.id_ = 0;
152   }
153
154   ThreadLocalPtr& operator=(ThreadLocalPtr&& other) {
155     assert(this != &other);
156     destroy();
157     id_ = other.id_;
158     other.id_ = 0;
159     return *this;
160   }
161
162   ~ThreadLocalPtr() {
163     destroy();
164   }
165
166   T* get() const {
167     return static_cast<T*>(threadlocal_detail::StaticMeta<Tag>::get(id_).ptr);
168   }
169
170   T* operator->() const {
171     return get();
172   }
173
174   T& operator*() const {
175     return *get();
176   }
177
178   void reset(T* newPtr = nullptr) {
179     threadlocal_detail::ElementWrapper& w =
180       threadlocal_detail::StaticMeta<Tag>::get(id_);
181     if (w.ptr != newPtr) {
182       w.dispose(TLPDestructionMode::THIS_THREAD);
183       w.set(newPtr);
184     }
185   }
186
187   explicit operator bool() const {
188     return get() != nullptr;
189   }
190
191   /**
192    * reset() with a custom deleter:
193    * deleter(T* ptr, TLPDestructionMode mode)
194    * "mode" is ALL_THREADS if we're destructing this ThreadLocalPtr (and thus
195    * deleting pointers for all threads), and THIS_THREAD if we're only deleting
196    * the member for one thread (because of thread exit or reset())
197    */
198   template <class Deleter>
199   void reset(T* newPtr, Deleter deleter) {
200     threadlocal_detail::ElementWrapper& w =
201       threadlocal_detail::StaticMeta<Tag>::get(id_);
202     if (w.ptr != newPtr) {
203       w.dispose(TLPDestructionMode::THIS_THREAD);
204       w.set(newPtr, deleter);
205     }
206   }
207
208   // Holds a global lock for iteration through all thread local child objects.
209   // Can be used as an iterable container.
210   // Use accessAllThreads() to obtain one.
211   class Accessor {
212     friend class ThreadLocalPtr<T,Tag>;
213
214     threadlocal_detail::StaticMeta<Tag>& meta_;
215     boost::mutex* lock_;
216     int id_;
217
218    public:
219     class Iterator;
220     friend class Iterator;
221
222     // The iterators obtained from Accessor are bidirectional iterators.
223     class Iterator : public boost::iterator_facade<
224           Iterator,                               // Derived
225           T,                                      // value_type
226           boost::bidirectional_traversal_tag> {   // traversal
227       friend class Accessor;
228       friend class boost::iterator_core_access;
229       const Accessor* const accessor_;
230       threadlocal_detail::ThreadEntry* e_;
231
232       void increment() {
233         e_ = e_->next;
234         incrementToValid();
235       }
236
237       void decrement() {
238         e_ = e_->prev;
239         decrementToValid();
240       }
241
242       T& dereference() const {
243         return *static_cast<T*>(e_->elements[accessor_->id_].ptr);
244       }
245
246       bool equal(const Iterator& other) const {
247         return (accessor_->id_ == other.accessor_->id_ &&
248                 e_ == other.e_);
249       }
250
251       explicit Iterator(const Accessor* accessor)
252         : accessor_(accessor),
253           e_(&accessor_->meta_.head_) {
254       }
255
256       bool valid() const {
257         return (e_->elements &&
258                 accessor_->id_ < e_->elementsCapacity &&
259                 e_->elements[accessor_->id_].ptr);
260       }
261
262       void incrementToValid() {
263         for (; e_ != &accessor_->meta_.head_ && !valid(); e_ = e_->next) { }
264       }
265
266       void decrementToValid() {
267         for (; e_ != &accessor_->meta_.head_ && !valid(); e_ = e_->prev) { }
268       }
269     };
270
271     ~Accessor() {
272       release();
273     }
274
275     Iterator begin() const {
276       return ++Iterator(this);
277     }
278
279     Iterator end() const {
280       return Iterator(this);
281     }
282
283     Accessor(const Accessor&) = delete;
284     Accessor& operator=(const Accessor&) = delete;
285
286     Accessor(Accessor&& other) FOLLY_NOEXCEPT
287       : meta_(other.meta_),
288         lock_(other.lock_),
289         id_(other.id_) {
290       other.id_ = 0;
291       other.lock_ = nullptr;
292     }
293
294     Accessor& operator=(Accessor&& other) FOLLY_NOEXCEPT {
295       // Each Tag has its own unique meta, and accessors with different Tags
296       // have different types.  So either *this is empty, or this and other
297       // have the same tag.  But if they have the same tag, they have the same
298       // meta (and lock), so they'd both hold the lock at the same time,
299       // which is impossible, which leaves only one possible scenario --
300       // *this is empty.  Assert it.
301       assert(&meta_ == &other.meta_);
302       assert(lock_ == nullptr);
303       using std::swap;
304       swap(lock_, other.lock_);
305       swap(id_, other.id_);
306     }
307
308     Accessor()
309       : meta_(threadlocal_detail::StaticMeta<Tag>::instance()),
310         lock_(nullptr),
311         id_(0) {
312     }
313
314    private:
315     explicit Accessor(int id)
316       : meta_(threadlocal_detail::StaticMeta<Tag>::instance()),
317         lock_(&meta_.lock_) {
318       lock_->lock();
319       id_ = id;
320     }
321
322     void release() {
323       if (lock_) {
324         lock_->unlock();
325         id_ = 0;
326         lock_ = nullptr;
327       }
328     }
329   };
330
331   // accessor allows a client to iterate through all thread local child
332   // elements of this ThreadLocal instance.  Holds a global lock for each <Tag>
333   Accessor accessAllThreads() const {
334     FOLLY_ASSERT(static_assert(!std::is_same<Tag, void>::value,
335                  "Must use a unique Tag to use the accessAllThreads feature"));
336     return Accessor(id_);
337   }
338
339  private:
340   void destroy() {
341     if (id_) {
342       threadlocal_detail::StaticMeta<Tag>::destroy(id_);
343     }
344   }
345
346   // non-copyable
347   ThreadLocalPtr(const ThreadLocalPtr&) = delete;
348   ThreadLocalPtr& operator=(const ThreadLocalPtr&) = delete;
349
350   int id_;  // every instantiation has a unique id
351 };
352
353 #undef FOLLY_NOEXCEPT
354
355 }  // namespace folly
356
357 #endif /* FOLLY_THREADLOCAL_H_ */