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