abstract thread_local support
[folly.git] / folly / ThreadLocal.h
1 /*
2  * Copyright 2014 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
46 namespace folly {
47 enum class TLPDestructionMode {
48   THIS_THREAD,
49   ALL_THREADS
50 };
51 }  // namespace
52
53 #include "folly/detail/ThreadLocalDetail.h"
54
55 namespace folly {
56
57 template<class T, class Tag> class ThreadLocalPtr;
58
59 template<class T, class Tag=void>
60 class ThreadLocal {
61  public:
62   ThreadLocal() { }
63
64   T* get() const {
65     T* ptr = tlp_.get();
66     if (LIKELY(ptr != nullptr)) {
67       return ptr;
68     }
69
70     // separated new item creation out to speed up the fast path.
71     return makeTlp();
72   }
73
74   T* operator->() const {
75     return get();
76   }
77
78   T& operator*() const {
79     return *get();
80   }
81
82   void reset(T* newPtr = nullptr) {
83     tlp_.reset(newPtr);
84   }
85
86   typedef typename ThreadLocalPtr<T,Tag>::Accessor Accessor;
87   Accessor accessAllThreads() const {
88     return tlp_.accessAllThreads();
89   }
90
91   // movable
92   ThreadLocal(ThreadLocal&&) = default;
93   ThreadLocal& operator=(ThreadLocal&&) = default;
94
95  private:
96   // non-copyable
97   ThreadLocal(const ThreadLocal&) = delete;
98   ThreadLocal& operator=(const ThreadLocal&) = delete;
99
100   T* makeTlp() const {
101     T* ptr = new T();
102     tlp_.reset(ptr);
103     return ptr;
104   }
105
106   mutable ThreadLocalPtr<T,Tag> tlp_;
107 };
108
109 /*
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
115  * very efficiently.
116  *
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.
123  *
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.
127  *
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)
133  */
134
135 template<class T, class Tag=void>
136 class ThreadLocalPtr {
137  public:
138   ThreadLocalPtr() : id_(threadlocal_detail::StaticMeta<Tag>::create()) { }
139
140   ThreadLocalPtr(ThreadLocalPtr&& other) : id_(other.id_) {
141     other.id_ = 0;
142   }
143
144   ThreadLocalPtr& operator=(ThreadLocalPtr&& other) {
145     assert(this != &other);
146     destroy();
147     id_ = other.id_;
148     other.id_ = 0;
149     return *this;
150   }
151
152   ~ThreadLocalPtr() {
153     destroy();
154   }
155
156   T* get() const {
157     return static_cast<T*>(threadlocal_detail::StaticMeta<Tag>::get(id_).ptr);
158   }
159
160   T* operator->() const {
161     return get();
162   }
163
164   T& operator*() const {
165     return *get();
166   }
167
168   void reset(T* newPtr = nullptr) {
169     threadlocal_detail::ElementWrapper& w =
170       threadlocal_detail::StaticMeta<Tag>::get(id_);
171     if (w.ptr != newPtr) {
172       w.dispose(TLPDestructionMode::THIS_THREAD);
173       w.set(newPtr);
174     }
175   }
176
177   explicit operator bool() const {
178     return get() != nullptr;
179   }
180
181   /**
182    * reset() with a custom deleter:
183    * deleter(T* ptr, TLPDestructionMode mode)
184    * "mode" is ALL_THREADS if we're destructing this ThreadLocalPtr (and thus
185    * deleting pointers for all threads), and THIS_THREAD if we're only deleting
186    * the member for one thread (because of thread exit or reset())
187    */
188   template <class Deleter>
189   void reset(T* newPtr, Deleter deleter) {
190     threadlocal_detail::ElementWrapper& w =
191       threadlocal_detail::StaticMeta<Tag>::get(id_);
192     if (w.ptr != newPtr) {
193       w.dispose(TLPDestructionMode::THIS_THREAD);
194       w.set(newPtr, deleter);
195     }
196   }
197
198   // Holds a global lock for iteration through all thread local child objects.
199   // Can be used as an iterable container.
200   // Use accessAllThreads() to obtain one.
201   class Accessor {
202     friend class ThreadLocalPtr<T,Tag>;
203
204     threadlocal_detail::StaticMeta<Tag>& meta_;
205     std::mutex* lock_;
206     int id_;
207
208    public:
209     class Iterator;
210     friend class Iterator;
211
212     // The iterators obtained from Accessor are bidirectional iterators.
213     class Iterator : public boost::iterator_facade<
214           Iterator,                               // Derived
215           T,                                      // value_type
216           boost::bidirectional_traversal_tag> {   // traversal
217       friend class Accessor;
218       friend class boost::iterator_core_access;
219       const Accessor* const accessor_;
220       threadlocal_detail::ThreadEntry* e_;
221
222       void increment() {
223         e_ = e_->next;
224         incrementToValid();
225       }
226
227       void decrement() {
228         e_ = e_->prev;
229         decrementToValid();
230       }
231
232       T& dereference() const {
233         return *static_cast<T*>(e_->elements[accessor_->id_].ptr);
234       }
235
236       bool equal(const Iterator& other) const {
237         return (accessor_->id_ == other.accessor_->id_ &&
238                 e_ == other.e_);
239       }
240
241       explicit Iterator(const Accessor* accessor)
242         : accessor_(accessor),
243           e_(&accessor_->meta_.head_) {
244       }
245
246       bool valid() const {
247         return (e_->elements &&
248                 accessor_->id_ < e_->elementsCapacity &&
249                 e_->elements[accessor_->id_].ptr);
250       }
251
252       void incrementToValid() {
253         for (; e_ != &accessor_->meta_.head_ && !valid(); e_ = e_->next) { }
254       }
255
256       void decrementToValid() {
257         for (; e_ != &accessor_->meta_.head_ && !valid(); e_ = e_->prev) { }
258       }
259     };
260
261     ~Accessor() {
262       release();
263     }
264
265     Iterator begin() const {
266       return ++Iterator(this);
267     }
268
269     Iterator end() const {
270       return Iterator(this);
271     }
272
273     Accessor(const Accessor&) = delete;
274     Accessor& operator=(const Accessor&) = delete;
275
276     Accessor(Accessor&& other) noexcept
277       : meta_(other.meta_),
278         lock_(other.lock_),
279         id_(other.id_) {
280       other.id_ = 0;
281       other.lock_ = nullptr;
282     }
283
284     Accessor& operator=(Accessor&& other) noexcept {
285       // Each Tag has its own unique meta, and accessors with different Tags
286       // have different types.  So either *this is empty, or this and other
287       // have the same tag.  But if they have the same tag, they have the same
288       // meta (and lock), so they'd both hold the lock at the same time,
289       // which is impossible, which leaves only one possible scenario --
290       // *this is empty.  Assert it.
291       assert(&meta_ == &other.meta_);
292       assert(lock_ == nullptr);
293       using std::swap;
294       swap(lock_, other.lock_);
295       swap(id_, other.id_);
296     }
297
298     Accessor()
299       : meta_(threadlocal_detail::StaticMeta<Tag>::instance()),
300         lock_(nullptr),
301         id_(0) {
302     }
303
304    private:
305     explicit Accessor(int id)
306       : meta_(threadlocal_detail::StaticMeta<Tag>::instance()),
307         lock_(&meta_.lock_) {
308       lock_->lock();
309       id_ = id;
310     }
311
312     void release() {
313       if (lock_) {
314         lock_->unlock();
315         id_ = 0;
316         lock_ = nullptr;
317       }
318     }
319   };
320
321   // accessor allows a client to iterate through all thread local child
322   // elements of this ThreadLocal instance.  Holds a global lock for each <Tag>
323   Accessor accessAllThreads() const {
324     static_assert(!std::is_same<Tag, void>::value,
325                   "Must use a unique Tag to use the accessAllThreads feature");
326     return Accessor(id_);
327   }
328
329  private:
330   void destroy() {
331     if (id_) {
332       threadlocal_detail::StaticMeta<Tag>::destroy(id_);
333     }
334   }
335
336   // non-copyable
337   ThreadLocalPtr(const ThreadLocalPtr&) = delete;
338   ThreadLocalPtr& operator=(const ThreadLocalPtr&) = delete;
339
340   int id_;  // every instantiation has a unique id
341 };
342
343 }  // namespace folly
344
345 #endif /* FOLLY_THREADLOCAL_H_ */