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]);
249 * Writing another thread's ThreadEntry from here is fine;
250 * the only other potential reader is the owning thread --
251 * from onThreadExit (which grabs the lock, so is properly
252 * synchronized with us) or from get(), which also grabs
253 * the lock if it needs to resize the elements vector.
255 * We can't conflict with reads for a get(id), because
256 * it's illegal to call get on a thread local that's
259 e->elements[id].ptr = nullptr;
260 e->elements[id].deleter = nullptr;
261 e->elements[id].ownsDeleter = false;
264 meta.freeIds_.push_back(id);
266 // Delete elements outside the lock
267 FOR_EACH(it, elements) {
268 it->dispose(TLPDestructionMode::ALL_THREADS);
270 } catch (...) { // Just in case we get a lock error or something anyway...
271 LOG(WARNING) << "Destructor discarding an exception that was thrown.";
276 * Reserve enough space in the threadEntry_.elements for the item
279 static void reserve(int id) {
280 size_t prevSize = threadEntry_.elementsCapacity;
281 size_t newSize = static_cast<size_t>((id + 5) * 1.7);
282 auto& meta = instance();
283 ElementWrapper* ptr = nullptr;
285 // Rely on jemalloc to zero the memory if possible -- maybe it knows
286 // it's already zeroed and saves us some work.
287 if (!usingJEMalloc() ||
288 prevSize < jemallocMinInPlaceExpandable ||
290 static_cast<void**>(static_cast<void*>(&threadEntry_.elements)),
291 nullptr, newSize * sizeof(ElementWrapper), 0,
292 ALLOCM_NO_MOVE | ALLOCM_ZERO) != ALLOCM_SUCCESS)) {
293 // Sigh, must realloc, but we can't call realloc here, as elements is
294 // still linked in meta, so another thread might access invalid memory
295 // after realloc succeeds. We'll copy by hand and update threadEntry_
298 // Note that we're using calloc instead of malloc in order to zero
299 // the entire region. rallocm (ALLOCM_ZERO) will only zero newly
300 // allocated memory, so if a previous allocation allocated more than
301 // we requested, it's our responsibility to guarantee that the tail
302 // is zeroed. calloc() is simpler than malloc() followed by memset(),
303 // and potentially faster when dealing with a lot of memory, as
304 // it can get already-zeroed pages from the kernel.
305 ptr = static_cast<ElementWrapper*>(
306 calloc(newSize, sizeof(ElementWrapper))
308 if (!ptr) throw std::bad_alloc();
311 // Success, update the entry
313 boost::lock_guard<boost::mutex> g(meta.lock_);
316 meta.push_back(&threadEntry_);
321 * Note: we need to hold the meta lock when copying data out of
322 * the old vector, because some other thread might be
323 * destructing a ThreadLocal and writing to the elements vector
326 memcpy(ptr, threadEntry_.elements, sizeof(ElementWrapper) * prevSize);
328 swap(ptr, threadEntry_.elements);
329 threadEntry_.elementsCapacity = newSize;
336 pthread_setspecific(meta.pthreadKey_, &meta);
340 static ElementWrapper& get(int id) {
341 if (UNLIKELY(threadEntry_.elementsCapacity <= id)) {
344 return threadEntry_.elements[id];
348 template <class Tag> __thread ThreadEntry StaticMeta<Tag>::threadEntry_ = {0};
349 template <class Tag> StaticMeta<Tag>* StaticMeta<Tag>::inst_ = nullptr;
351 } // namespace threadlocal_detail
354 #endif /* FOLLY_DETAIL_THREADLOCALDETAIL_H_ */