Unbreak folly on x86-32
[folly.git] / folly / ThreadLocal.h
1 /*
2  * Copyright 2017 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  * accessAllThreads() can race with destruction of thread-local elements. We
27  * provide a strict mode which is dangerous because it requires the access lock
28  * to be held while destroying thread-local elements which could cause
29  * deadlocks. We gate this mode behind the AccessModeStrict template parameter.
30  *
31  * Intended use is for frequent write, infrequent read data access patterns such
32  * as counters.
33  *
34  * There are two classes here - ThreadLocal and ThreadLocalPtr.  ThreadLocalPtr
35  * has semantics similar to boost::thread_specific_ptr. ThreadLocal is a thin
36  * wrapper around ThreadLocalPtr that manages allocation automatically.
37  *
38  * @author Spencer Ahrens (sahrens)
39  */
40
41 #pragma once
42
43 #include <boost/iterator/iterator_facade.hpp>
44 #include <folly/Likely.h>
45 #include <folly/Portability.h>
46 #include <folly/ScopeGuard.h>
47 #include <folly/SharedMutex.h>
48 #include <folly/detail/ThreadLocalDetail.h>
49 #include <type_traits>
50 #include <utility>
51
52 namespace folly {
53
54 template <class T, class Tag, class AccessMode>
55 class ThreadLocalPtr;
56
57 template <class T, class Tag = void, class AccessMode = void>
58 class ThreadLocal {
59  public:
60   constexpr ThreadLocal() : constructor_([]() {
61       return new T();
62     }) {}
63
64   explicit ThreadLocal(std::function<T*()> constructor) :
65       constructor_(constructor) {
66   }
67
68   T* get() const {
69     T* ptr = tlp_.get();
70     if (LIKELY(ptr != nullptr)) {
71       return ptr;
72     }
73
74     // separated new item creation out to speed up the fast path.
75     return makeTlp();
76   }
77
78   T* operator->() const {
79     return get();
80   }
81
82   T& operator*() const {
83     return *get();
84   }
85
86   void reset(T* newPtr = nullptr) {
87     tlp_.reset(newPtr);
88   }
89
90   typedef typename ThreadLocalPtr<T, Tag, AccessMode>::Accessor Accessor;
91   Accessor accessAllThreads() const {
92     return tlp_.accessAllThreads();
93   }
94
95   // movable
96   ThreadLocal(ThreadLocal&&) = default;
97   ThreadLocal& operator=(ThreadLocal&&) = default;
98
99  private:
100   // non-copyable
101   ThreadLocal(const ThreadLocal&) = delete;
102   ThreadLocal& operator=(const ThreadLocal&) = delete;
103
104   T* makeTlp() const {
105     auto ptr = constructor_();
106     tlp_.reset(ptr);
107     return ptr;
108   }
109
110   mutable ThreadLocalPtr<T, Tag, AccessMode> tlp_;
111   std::function<T*()> constructor_;
112 };
113
114 /*
115  * The idea here is that __thread is faster than pthread_getspecific, so we
116  * keep a __thread array of pointers to objects (ThreadEntry::elements) where
117  * each array has an index for each unique instance of the ThreadLocalPtr
118  * object.  Each ThreadLocalPtr object has a unique id that is an index into
119  * these arrays so we can fetch the correct object from thread local storage
120  * very efficiently.
121  *
122  * In order to prevent unbounded growth of the id space and thus huge
123  * ThreadEntry::elements, arrays, for example due to continuous creation and
124  * destruction of ThreadLocalPtr objects, we keep a set of all active
125  * instances.  When an instance is destroyed we remove it from the active
126  * set and insert the id into freeIds_ for reuse.  These operations require a
127  * global mutex, but only happen at construction and destruction time.
128  *
129  * We use a single global pthread_key_t per Tag to manage object destruction and
130  * memory cleanup upon thread exit because there is a finite number of
131  * pthread_key_t's available per machine.
132  *
133  * NOTE: Apple platforms don't support the same semantics for __thread that
134  *       Linux does (and it's only supported at all on i386). For these, use
135  *       pthread_setspecific()/pthread_getspecific() for the per-thread
136  *       storage.  Windows (MSVC and GCC) does support the same semantics
137  *       with __declspec(thread)
138  */
139
140 template <class T, class Tag = void, class AccessMode = void>
141 class ThreadLocalPtr {
142  private:
143   typedef threadlocal_detail::StaticMeta<Tag, AccessMode> StaticMeta;
144
145  public:
146   constexpr ThreadLocalPtr() : id_() {}
147
148   ThreadLocalPtr(ThreadLocalPtr&& other) noexcept :
149     id_(std::move(other.id_)) {
150   }
151
152   ThreadLocalPtr& operator=(ThreadLocalPtr&& other) {
153     assert(this != &other);
154     destroy();
155     id_ = std::move(other.id_);
156     return *this;
157   }
158
159   ~ThreadLocalPtr() {
160     destroy();
161   }
162
163   T* get() const {
164     threadlocal_detail::ElementWrapper& w = StaticMeta::get(&id_);
165     return static_cast<T*>(w.ptr);
166   }
167
168   T* operator->() const {
169     return get();
170   }
171
172   T& operator*() const {
173     return *get();
174   }
175
176   T* release() {
177     threadlocal_detail::ElementWrapper& w = StaticMeta::get(&id_);
178
179     return static_cast<T*>(w.release());
180   }
181
182   void reset(T* newPtr = nullptr) {
183     auto guard = makeGuard([&] { delete newPtr; });
184     threadlocal_detail::ElementWrapper& w = StaticMeta::get(&id_);
185
186     w.dispose(TLPDestructionMode::THIS_THREAD);
187     guard.dismiss();
188     w.set(newPtr);
189   }
190
191   explicit operator bool() const {
192     return get() != nullptr;
193   }
194
195   /**
196    * reset() that transfers ownership from a smart pointer
197    */
198   template <
199       typename SourceT,
200       typename Deleter,
201       typename = typename std::enable_if<
202           std::is_convertible<SourceT*, T*>::value>::type>
203   void reset(std::unique_ptr<SourceT, Deleter> source) {
204     auto deleter = [delegate = source.get_deleter()](
205         T * ptr, TLPDestructionMode) {
206       delegate(ptr);
207     };
208     reset(source.release(), deleter);
209   }
210
211   /**
212    * reset() that transfers ownership from a smart pointer with the default
213    * deleter
214    */
215   template <
216       typename SourceT,
217       typename = typename std::enable_if<
218           std::is_convertible<SourceT*, T*>::value>::type>
219   void reset(std::unique_ptr<SourceT> source) {
220     reset(source.release());
221   }
222
223   /**
224    * reset() with a custom deleter:
225    * deleter(T* ptr, TLPDestructionMode mode)
226    * "mode" is ALL_THREADS if we're destructing this ThreadLocalPtr (and thus
227    * deleting pointers for all threads), and THIS_THREAD if we're only deleting
228    * the member for one thread (because of thread exit or reset()).
229    * Invoking the deleter must not throw.
230    */
231   template <class Deleter>
232   void reset(T* newPtr, const Deleter& deleter) {
233     auto guard = makeGuard([&] {
234       if (newPtr) {
235         deleter(newPtr, TLPDestructionMode::THIS_THREAD);
236       }
237     });
238     threadlocal_detail::ElementWrapper& w = StaticMeta::get(&id_);
239     w.dispose(TLPDestructionMode::THIS_THREAD);
240     guard.dismiss();
241     w.set(newPtr, deleter);
242   }
243
244   // Holds a global lock for iteration through all thread local child objects.
245   // Can be used as an iterable container.
246   // Use accessAllThreads() to obtain one.
247   class Accessor {
248     friend class ThreadLocalPtr<T, Tag, AccessMode>;
249
250     threadlocal_detail::StaticMetaBase& meta_;
251     SharedMutex* accessAllThreadsLock_;
252     std::mutex* lock_;
253     uint32_t id_;
254
255    public:
256     class Iterator;
257     friend class Iterator;
258
259     // The iterators obtained from Accessor are bidirectional iterators.
260     class Iterator : public boost::iterator_facade<
261           Iterator,                               // Derived
262           T,                                      // value_type
263           boost::bidirectional_traversal_tag> {   // traversal
264       friend class Accessor;
265       friend class boost::iterator_core_access;
266       const Accessor* accessor_;
267       threadlocal_detail::ThreadEntry* e_;
268
269       void increment() {
270         e_ = e_->next;
271         incrementToValid();
272       }
273
274       void decrement() {
275         e_ = e_->prev;
276         decrementToValid();
277       }
278
279       T& dereference() const {
280         return *static_cast<T*>(e_->elements[accessor_->id_].ptr);
281       }
282
283       bool equal(const Iterator& other) const {
284         return (accessor_->id_ == other.accessor_->id_ &&
285                 e_ == other.e_);
286       }
287
288       explicit Iterator(const Accessor* accessor)
289         : accessor_(accessor),
290           e_(&accessor_->meta_.head_) {
291       }
292
293       bool valid() const {
294         return (e_->elements &&
295                 accessor_->id_ < e_->elementsCapacity &&
296                 e_->elements[accessor_->id_].ptr);
297       }
298
299       void incrementToValid() {
300         for (; e_ != &accessor_->meta_.head_ && !valid(); e_ = e_->next) { }
301       }
302
303       void decrementToValid() {
304         for (; e_ != &accessor_->meta_.head_ && !valid(); e_ = e_->prev) { }
305       }
306     };
307
308     ~Accessor() {
309       release();
310     }
311
312     Iterator begin() const {
313       return ++Iterator(this);
314     }
315
316     Iterator end() const {
317       return Iterator(this);
318     }
319
320     Accessor(const Accessor&) = delete;
321     Accessor& operator=(const Accessor&) = delete;
322
323     Accessor(Accessor&& other) noexcept
324         : meta_(other.meta_),
325           accessAllThreadsLock_(other.accessAllThreadsLock_),
326           lock_(other.lock_),
327           id_(other.id_) {
328       other.id_ = 0;
329       other.accessAllThreadsLock_ = nullptr;
330       other.lock_ = nullptr;
331     }
332
333     Accessor& operator=(Accessor&& other) noexcept {
334       // Each Tag has its own unique meta, and accessors with different Tags
335       // have different types.  So either *this is empty, or this and other
336       // have the same tag.  But if they have the same tag, they have the same
337       // meta (and lock), so they'd both hold the lock at the same time,
338       // which is impossible, which leaves only one possible scenario --
339       // *this is empty.  Assert it.
340       assert(&meta_ == &other.meta_);
341       assert(lock_ == nullptr);
342       using std::swap;
343       swap(accessAllThreadsLock_, other.accessAllThreadsLock_);
344       swap(lock_, other.lock_);
345       swap(id_, other.id_);
346     }
347
348     Accessor()
349         : meta_(threadlocal_detail::StaticMeta<Tag, AccessMode>::instance()),
350           accessAllThreadsLock_(nullptr),
351           lock_(nullptr),
352           id_(0) {}
353
354    private:
355     explicit Accessor(uint32_t id)
356         : meta_(threadlocal_detail::StaticMeta<Tag, AccessMode>::instance()),
357           accessAllThreadsLock_(&meta_.accessAllThreadsLock_),
358           lock_(&meta_.lock_) {
359       accessAllThreadsLock_->lock();
360       lock_->lock();
361       id_ = id;
362     }
363
364     void release() {
365       if (lock_) {
366         lock_->unlock();
367         DCHECK(accessAllThreadsLock_ != nullptr);
368         accessAllThreadsLock_->unlock();
369         id_ = 0;
370         lock_ = nullptr;
371         accessAllThreadsLock_ = nullptr;
372       }
373     }
374   };
375
376   // accessor allows a client to iterate through all thread local child
377   // elements of this ThreadLocal instance.  Holds a global lock for each <Tag>
378   Accessor accessAllThreads() const {
379     static_assert(!std::is_same<Tag, void>::value,
380                   "Must use a unique Tag to use the accessAllThreads feature");
381     return Accessor(id_.getOrAllocate(StaticMeta::instance()));
382   }
383
384  private:
385   void destroy() {
386     StaticMeta::instance().destroy(&id_);
387   }
388
389   // non-copyable
390   ThreadLocalPtr(const ThreadLocalPtr&) = delete;
391   ThreadLocalPtr& operator=(const ThreadLocalPtr&) = delete;
392
393   mutable typename StaticMeta::EntryID id_;
394 };
395
396 } // namespace folly