2 * Copyright 2013 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.
17 #ifndef FOLLY_DETAIL_THREADLOCALDETAIL_H_
18 #define FOLLY_DETAIL_THREADLOCALDETAIL_H_
26 #include <boost/thread/mutex.hpp>
28 #include <glog/logging.h>
30 #include "folly/Foreach.h"
31 #include "folly/Malloc.h"
34 namespace threadlocal_detail {
37 * Base class for deleters.
41 virtual ~DeleterBase() { }
42 virtual void dispose(void* ptr, TLPDestructionMode mode) const = 0;
46 * Simple deleter class that calls delete on the passed-in pointer.
49 class SimpleDeleter : public DeleterBase {
51 virtual void dispose(void* ptr, TLPDestructionMode mode) const {
52 delete static_cast<Ptr>(ptr);
57 * Custom deleter that calls a given callable.
59 template <class Ptr, class Deleter>
60 class CustomDeleter : public DeleterBase {
62 explicit CustomDeleter(Deleter d) : deleter_(d) { }
63 virtual void dispose(void* ptr, TLPDestructionMode mode) const {
64 deleter_(static_cast<Ptr>(ptr), mode);
72 * POD wrapper around an element (a void*) and an associated deleter.
73 * This must be POD, as we memset() it to 0 and memcpy() it around.
75 struct ElementWrapper {
76 void dispose(TLPDestructionMode mode) {
78 DCHECK(deleter != NULL);
79 deleter->dispose(ptr, mode);
92 DCHECK(deleter == NULL);
95 // We leak a single object here but that is ok. If we used an
96 // object directly, there is a chance that the destructor will be
97 // called on that static object before any of the ElementWrappers
98 // are disposed and that isn't so nice.
99 static auto d = new SimpleDeleter<Ptr>();
106 template <class Ptr, class Deleter>
107 void set(Ptr p, Deleter d) {
109 DCHECK(deleter == NULL);
112 deleter = new CustomDeleter<Ptr,Deleter>(d);
118 DeleterBase* deleter;
123 * Per-thread entry. Each thread using a StaticMeta object has one.
124 * This is written from the owning thread only (under the lock), read
125 * from the owning thread (no lock necessary), and read from other threads
129 ElementWrapper* elements;
130 size_t elementsCapacity;
135 // Held in a singleton to track our global instances.
136 // We have one of these per "Tag", by default one for the whole system
139 // Creating and destroying ThreadLocalPtr objects, as well as thread exit
140 // for threads that use ThreadLocalPtr objects collide on a lock inside
141 // StaticMeta; you can specify multiple Tag types to break that lock.
144 static StaticMeta<Tag>& instance() {
145 // Leak it on exit, there's only one per process and we don't have to
146 // worry about synchronization with exiting threads.
147 static bool constructed = (inst = new StaticMeta<Tag>());
148 (void)constructed; // suppress unused warning
153 std::vector<int> freeIds_;
155 pthread_key_t pthreadKey_;
158 void push_back(ThreadEntry* t) {
160 t->prev = head_.prev;
161 head_.prev->next = t;
165 void erase(ThreadEntry* t) {
166 t->next->prev = t->prev;
167 t->prev->next = t->next;
168 t->next = t->prev = t;
171 static __thread ThreadEntry threadEntry_;
172 static StaticMeta<Tag>* inst;
174 StaticMeta() : nextId_(1) {
175 head_.next = head_.prev = &head_;
176 int ret = pthread_key_create(&pthreadKey_, &onThreadExit);
182 snprintf(buf, sizeof(buf), "PTHREAD_KEYS_MAX (%d) is exceeded",
187 msg = "Out-of-memory";
190 msg = "(unknown error)";
192 throw std::runtime_error("pthread_key_create failed: " + msg);
196 LOG(FATAL) << "StaticMeta lives forever!";
199 static void onThreadExit(void* ptr) {
200 auto & meta = instance();
201 DCHECK_EQ(ptr, &meta);
202 // We wouldn't call pthread_setspecific unless we actually called get()
203 DCHECK_NE(threadEntry_.elementsCapacity, 0);
205 boost::lock_guard<boost::mutex> g(meta.lock_);
206 meta.erase(&threadEntry_);
207 // No need to hold the lock any longer; threadEntry_ is private to this
208 // thread now that it's been removed from meta.
210 FOR_EACH_RANGE(i, 0, threadEntry_.elementsCapacity) {
211 threadEntry_.elements[i].dispose(TLPDestructionMode::THIS_THREAD);
213 free(threadEntry_.elements);
214 threadEntry_.elements = NULL;
215 pthread_setspecific(meta.pthreadKey_, NULL);
218 static int create() {
220 auto & meta = instance();
221 boost::lock_guard<boost::mutex> g(meta.lock_);
222 if (!meta.freeIds_.empty()) {
223 id = meta.freeIds_.back();
224 meta.freeIds_.pop_back();
231 static void destroy(int id) {
233 auto & meta = instance();
234 // Elements in other threads that use this id.
235 std::vector<ElementWrapper> elements;
237 boost::lock_guard<boost::mutex> g(meta.lock_);
238 for (ThreadEntry* e = meta.head_.next; e != &meta.head_; e = e->next) {
239 if (id < e->elementsCapacity && e->elements[id].ptr) {
240 elements.push_back(e->elements[id]);
242 // Writing another thread's ThreadEntry from here is fine;
243 // the only other potential reader is the owning thread --
244 // from onThreadExit (which grabs the lock, so is properly
245 // synchronized with us) or from get() -- but using get() on a
246 // ThreadLocalPtr object that's being destroyed is a bug, so
247 // undefined behavior is fair game.
248 e->elements[id].ptr = NULL;
249 e->elements[id].deleter = NULL;
252 meta.freeIds_.push_back(id);
254 // Delete elements outside the lock
255 FOR_EACH(it, elements) {
256 it->dispose(TLPDestructionMode::ALL_THREADS);
258 } catch (...) { // Just in case we get a lock error or something anyway...
259 LOG(WARNING) << "Destructor discarding an exception that was thrown.";
264 * Reserve enough space in the threadEntry_.elements for the item
267 static void reserve(int id) {
268 size_t prevSize = threadEntry_.elementsCapacity;
269 size_t newSize = static_cast<size_t>((id + 5) * 1.7);
270 auto& meta = instance();
271 ElementWrapper* ptr = nullptr;
272 // Rely on jemalloc to zero the memory if possible -- maybe it knows
273 // it's already zeroed and saves us some work.
274 if (!usingJEMalloc() ||
275 prevSize < jemallocMinInPlaceExpandable ||
277 static_cast<void**>(static_cast<void*>(&threadEntry_.elements)),
278 NULL, newSize * sizeof(ElementWrapper), 0,
279 ALLOCM_NO_MOVE | ALLOCM_ZERO) != ALLOCM_SUCCESS)) {
280 // Sigh, must realloc, but we can't call realloc here, as elements is
281 // still linked in meta, so another thread might access invalid memory
282 // after realloc succeeds. We'll copy by hand and update threadEntry_
285 // Note that we're using calloc instead of malloc in order to zero
286 // the entire region. rallocm (ALLOCM_ZERO) will only zero newly
287 // allocated memory, so if a previous allocation allocated more than
288 // we requested, it's our responsibility to guarantee that the tail
289 // is zeroed. calloc() is simpler than malloc() followed by memset(),
290 // and potentially faster when dealing with a lot of memory, as
291 // it can get already-zeroed pages from the kernel.
292 if ((ptr = static_cast<ElementWrapper*>(
293 calloc(newSize, sizeof(ElementWrapper)))) != nullptr) {
294 memcpy(ptr, threadEntry_.elements, sizeof(ElementWrapper) * prevSize);
296 throw std::bad_alloc();
300 // Success, update the entry
302 boost::lock_guard<boost::mutex> g(meta.lock_);
304 meta.push_back(&threadEntry_);
308 swap(ptr, threadEntry_.elements);
310 threadEntry_.elementsCapacity = newSize;
316 pthread_setspecific(meta.pthreadKey_, &meta);
320 static ElementWrapper& get(int id) {
321 if (UNLIKELY(threadEntry_.elementsCapacity <= id)) {
324 return threadEntry_.elements[id];
328 template <class Tag> __thread ThreadEntry StaticMeta<Tag>::threadEntry_ = {0};
329 template <class Tag> StaticMeta<Tag>* StaticMeta<Tag>::inst = nullptr;
331 } // namespace threadlocal_detail
334 #endif /* FOLLY_DETAIL_THREADLOCALDETAIL_H_ */