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/locks.hpp>
27 #include <boost/thread/mutex.hpp>
28 #include <boost/thread/locks.hpp>
30 #include <glog/logging.h>
32 #include "folly/Exception.h"
33 #include "folly/Foreach.h"
34 #include "folly/Malloc.h"
37 namespace threadlocal_detail {
40 * Base class for deleters.
44 virtual ~DeleterBase() { }
45 virtual void dispose(void* ptr, TLPDestructionMode mode) const = 0;
49 * Simple deleter class that calls delete on the passed-in pointer.
52 class SimpleDeleter : public DeleterBase {
54 virtual void dispose(void* ptr, TLPDestructionMode mode) const {
55 delete static_cast<Ptr>(ptr);
60 * Custom deleter that calls a given callable.
62 template <class Ptr, class Deleter>
63 class CustomDeleter : public DeleterBase {
65 explicit CustomDeleter(Deleter d) : deleter_(d) { }
66 virtual void dispose(void* ptr, TLPDestructionMode mode) const {
67 deleter_(static_cast<Ptr>(ptr), mode);
75 * POD wrapper around an element (a void*) and an associated deleter.
76 * This must be POD, as we memset() it to 0 and memcpy() it around.
78 struct ElementWrapper {
79 void dispose(TLPDestructionMode mode) {
81 DCHECK(deleter != NULL);
82 deleter->dispose(ptr, mode);
95 DCHECK(deleter == NULL);
98 // We leak a single object here but that is ok. If we used an
99 // object directly, there is a chance that the destructor will be
100 // called on that static object before any of the ElementWrappers
101 // are disposed and that isn't so nice.
102 static auto d = new SimpleDeleter<Ptr>();
109 template <class Ptr, class Deleter>
110 void set(Ptr p, Deleter d) {
112 DCHECK(deleter == NULL);
115 deleter = new CustomDeleter<Ptr,Deleter>(d);
121 DeleterBase* deleter;
126 * Per-thread entry. Each thread using a StaticMeta object has one.
127 * This is written from the owning thread only (under the lock), read
128 * from the owning thread (no lock necessary), and read from other threads
132 ElementWrapper* elements;
133 size_t elementsCapacity;
138 // Held in a singleton to track our global instances.
139 // We have one of these per "Tag", by default one for the whole system
142 // Creating and destroying ThreadLocalPtr objects, as well as thread exit
143 // for threads that use ThreadLocalPtr objects collide on a lock inside
144 // StaticMeta; you can specify multiple Tag types to break that lock.
147 static StaticMeta<Tag>& instance() {
148 // Leak it on exit, there's only one per process and we don't have to
149 // worry about synchronization with exiting threads.
150 static bool constructed = (inst_ = new StaticMeta<Tag>());
151 (void)constructed; // suppress unused warning
156 std::vector<int> freeIds_;
158 pthread_key_t pthreadKey_;
161 void push_back(ThreadEntry* t) {
163 t->prev = head_.prev;
164 head_.prev->next = t;
168 void erase(ThreadEntry* t) {
169 t->next->prev = t->prev;
170 t->prev->next = t->next;
171 t->next = t->prev = t;
174 static __thread ThreadEntry threadEntry_;
175 static StaticMeta<Tag>* inst_;
177 StaticMeta() : nextId_(1) {
178 head_.next = head_.prev = &head_;
179 int ret = pthread_key_create(&pthreadKey_, &onThreadExit);
180 checkPosixError(ret, "pthread_key_create failed");
182 ret = pthread_atfork(/*prepare*/ &StaticMeta::preFork,
183 /*parent*/ &StaticMeta::onForkParent,
184 /*child*/ &StaticMeta::onForkChild);
185 checkPosixError(ret, "pthread_atfork failed");
188 LOG(FATAL) << "StaticMeta lives forever!";
191 static void preFork(void) {
192 instance().lock_.lock(); // Make sure it's created
195 static void onForkParent(void) {
196 inst_->lock_.unlock();
199 static void onForkChild(void) {
200 inst_->head_.next = inst_->head_.prev = &inst_->head_;
201 inst_->push_back(&threadEntry_); // only the current thread survives
202 inst_->lock_.unlock();
205 static void onThreadExit(void* ptr) {
206 auto & meta = instance();
207 DCHECK_EQ(ptr, &meta);
208 // We wouldn't call pthread_setspecific unless we actually called get()
209 DCHECK_NE(threadEntry_.elementsCapacity, 0);
211 boost::lock_guard<boost::mutex> g(meta.lock_);
212 meta.erase(&threadEntry_);
213 // No need to hold the lock any longer; threadEntry_ is private to this
214 // thread now that it's been removed from meta.
216 FOR_EACH_RANGE(i, 0, threadEntry_.elementsCapacity) {
217 threadEntry_.elements[i].dispose(TLPDestructionMode::THIS_THREAD);
219 free(threadEntry_.elements);
220 threadEntry_.elements = NULL;
221 pthread_setspecific(meta.pthreadKey_, NULL);
224 static int create() {
226 auto & meta = instance();
227 boost::lock_guard<boost::mutex> g(meta.lock_);
228 if (!meta.freeIds_.empty()) {
229 id = meta.freeIds_.back();
230 meta.freeIds_.pop_back();
237 static void destroy(int id) {
239 auto & meta = instance();
240 // Elements in other threads that use this id.
241 std::vector<ElementWrapper> elements;
243 boost::lock_guard<boost::mutex> g(meta.lock_);
244 for (ThreadEntry* e = meta.head_.next; e != &meta.head_; e = e->next) {
245 if (id < e->elementsCapacity && e->elements[id].ptr) {
246 elements.push_back(e->elements[id]);
248 // Writing another thread's ThreadEntry from here is fine;
249 // the only other potential reader is the owning thread --
250 // from onThreadExit (which grabs the lock, so is properly
251 // synchronized with us) or from get() -- but using get() on a
252 // ThreadLocalPtr object that's being destroyed is a bug, so
253 // undefined behavior is fair game.
254 e->elements[id].ptr = NULL;
255 e->elements[id].deleter = NULL;
258 meta.freeIds_.push_back(id);
260 // Delete elements outside the lock
261 FOR_EACH(it, elements) {
262 it->dispose(TLPDestructionMode::ALL_THREADS);
264 } catch (...) { // Just in case we get a lock error or something anyway...
265 LOG(WARNING) << "Destructor discarding an exception that was thrown.";
270 * Reserve enough space in the threadEntry_.elements for the item
273 static void reserve(int id) {
274 size_t prevSize = threadEntry_.elementsCapacity;
275 size_t newSize = static_cast<size_t>((id + 5) * 1.7);
276 auto& meta = instance();
277 ElementWrapper* ptr = nullptr;
278 // Rely on jemalloc to zero the memory if possible -- maybe it knows
279 // it's already zeroed and saves us some work.
280 if (!usingJEMalloc() ||
281 prevSize < jemallocMinInPlaceExpandable ||
283 static_cast<void**>(static_cast<void*>(&threadEntry_.elements)),
284 NULL, newSize * sizeof(ElementWrapper), 0,
285 ALLOCM_NO_MOVE | ALLOCM_ZERO) != ALLOCM_SUCCESS)) {
286 // Sigh, must realloc, but we can't call realloc here, as elements is
287 // still linked in meta, so another thread might access invalid memory
288 // after realloc succeeds. We'll copy by hand and update threadEntry_
291 // Note that we're using calloc instead of malloc in order to zero
292 // the entire region. rallocm (ALLOCM_ZERO) will only zero newly
293 // allocated memory, so if a previous allocation allocated more than
294 // we requested, it's our responsibility to guarantee that the tail
295 // is zeroed. calloc() is simpler than malloc() followed by memset(),
296 // and potentially faster when dealing with a lot of memory, as
297 // it can get already-zeroed pages from the kernel.
298 if ((ptr = static_cast<ElementWrapper*>(
299 calloc(newSize, sizeof(ElementWrapper)))) != nullptr) {
300 memcpy(ptr, threadEntry_.elements, sizeof(ElementWrapper) * prevSize);
302 throw std::bad_alloc();
306 // Success, update the entry
308 boost::lock_guard<boost::mutex> g(meta.lock_);
310 meta.push_back(&threadEntry_);
314 swap(ptr, threadEntry_.elements);
316 threadEntry_.elementsCapacity = newSize;
322 pthread_setspecific(meta.pthreadKey_, &meta);
326 static ElementWrapper& get(int id) {
327 if (UNLIKELY(threadEntry_.elementsCapacity <= id)) {
330 return threadEntry_.elements[id];
334 template <class Tag> __thread ThreadEntry StaticMeta<Tag>::threadEntry_ = {0};
335 template <class Tag> StaticMeta<Tag>* StaticMeta<Tag>::inst_ = nullptr;
337 } // namespace threadlocal_detail
340 #endif /* FOLLY_DETAIL_THREADLOCALDETAIL_H_ */