2 * Copyright 2014 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_
27 #include <glog/logging.h>
29 #include <folly/Foreach.h>
30 #include <folly/Exception.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 != nullptr);
79 deleter->dispose(ptr, mode);
97 DCHECK(ptr == nullptr);
98 DCHECK(deleter == nullptr);
101 // We leak a single object here but that is ok. If we used an
102 // object directly, there is a chance that the destructor will be
103 // called on that static object before any of the ElementWrappers
104 // are disposed and that isn't so nice.
105 static auto d = new SimpleDeleter<Ptr>();
112 template <class Ptr, class Deleter>
113 void set(Ptr p, Deleter d) {
114 DCHECK(ptr == nullptr);
115 DCHECK(deleter == nullptr);
118 deleter = new CustomDeleter<Ptr,Deleter>(d);
133 DeleterBase* deleter;
138 * Per-thread entry. Each thread using a StaticMeta object has one.
139 * This is written from the owning thread only (under the lock), read
140 * from the owning thread (no lock necessary), and read from other threads
144 ElementWrapper* elements;
145 size_t elementsCapacity;
150 // Held in a singleton to track our global instances.
151 // We have one of these per "Tag", by default one for the whole system
154 // Creating and destroying ThreadLocalPtr objects, as well as thread exit
155 // for threads that use ThreadLocalPtr objects collide on a lock inside
156 // StaticMeta; you can specify multiple Tag types to break that lock.
159 static StaticMeta<Tag>& instance() {
160 // Leak it on exit, there's only one per process and we don't have to
161 // worry about synchronization with exiting threads.
162 static bool constructed = (inst_ = new StaticMeta<Tag>());
163 (void)constructed; // suppress unused warning
168 std::vector<int> freeIds_;
170 pthread_key_t pthreadKey_;
173 void push_back(ThreadEntry* t) {
175 t->prev = head_.prev;
176 head_.prev->next = t;
180 void erase(ThreadEntry* t) {
181 t->next->prev = t->prev;
182 t->prev->next = t->next;
183 t->next = t->prev = t;
187 static FOLLY_TLS ThreadEntry threadEntry_;
189 static StaticMeta<Tag>* inst_;
191 StaticMeta() : nextId_(1) {
192 head_.next = head_.prev = &head_;
193 int ret = pthread_key_create(&pthreadKey_, &onThreadExit);
194 checkPosixError(ret, "pthread_key_create failed");
196 // pthread_atfork is not part of the Android NDK at least as of n9d. If
197 // something is trying to call native fork() directly at all with Android's
198 // process management model, this is probably the least of the problems.
200 ret = pthread_atfork(/*prepare*/ &StaticMeta::preFork,
201 /*parent*/ &StaticMeta::onForkParent,
202 /*child*/ &StaticMeta::onForkChild);
203 checkPosixError(ret, "pthread_atfork failed");
207 LOG(FATAL) << "StaticMeta lives forever!";
210 static ThreadEntry* getThreadEntry() {
212 return &threadEntry_;
214 ThreadEntry* threadEntry =
215 static_cast<ThreadEntry*>(pthread_getspecific(inst_->pthreadKey_));
217 threadEntry = new ThreadEntry();
218 int ret = pthread_setspecific(inst_->pthreadKey_, threadEntry);
219 checkPosixError(ret, "pthread_setspecific failed");
225 static void preFork(void) {
226 instance().lock_.lock(); // Make sure it's created
229 static void onForkParent(void) {
230 inst_->lock_.unlock();
233 static void onForkChild(void) {
234 // only the current thread survives
235 inst_->head_.next = inst_->head_.prev = &inst_->head_;
236 ThreadEntry* threadEntry = getThreadEntry();
237 // If this thread was in the list before the fork, add it back.
238 if (threadEntry->elementsCapacity != 0) {
239 inst_->push_back(threadEntry);
241 inst_->lock_.unlock();
244 static void onThreadExit(void* ptr) {
245 auto & meta = instance();
247 ThreadEntry* threadEntry = getThreadEntry();
249 DCHECK_EQ(ptr, &meta);
250 DCHECK_GT(threadEntry->elementsCapacity, 0);
252 ThreadEntry* threadEntry = static_cast<ThreadEntry*>(ptr);
255 std::lock_guard<std::mutex> g(meta.lock_);
256 meta.erase(threadEntry);
257 // No need to hold the lock any longer; the ThreadEntry is private to this
258 // thread now that it's been removed from meta.
260 FOR_EACH_RANGE(i, 0, threadEntry->elementsCapacity) {
261 threadEntry->elements[i].dispose(TLPDestructionMode::THIS_THREAD);
263 free(threadEntry->elements);
264 threadEntry->elements = nullptr;
265 pthread_setspecific(meta.pthreadKey_, nullptr);
268 // Allocated in getThreadEntry(); free it
273 static int create() {
275 auto & meta = instance();
276 std::lock_guard<std::mutex> g(meta.lock_);
277 if (!meta.freeIds_.empty()) {
278 id = meta.freeIds_.back();
279 meta.freeIds_.pop_back();
286 static void destroy(size_t id) {
288 auto & meta = instance();
289 // Elements in other threads that use this id.
290 std::vector<ElementWrapper> elements;
292 std::lock_guard<std::mutex> g(meta.lock_);
293 for (ThreadEntry* e = meta.head_.next; e != &meta.head_; e = e->next) {
294 if (id < e->elementsCapacity && e->elements[id].ptr) {
295 elements.push_back(e->elements[id]);
298 * Writing another thread's ThreadEntry from here is fine;
299 * the only other potential reader is the owning thread --
300 * from onThreadExit (which grabs the lock, so is properly
301 * synchronized with us) or from get(), which also grabs
302 * the lock if it needs to resize the elements vector.
304 * We can't conflict with reads for a get(id), because
305 * it's illegal to call get on a thread local that's
308 e->elements[id].ptr = nullptr;
309 e->elements[id].deleter = nullptr;
310 e->elements[id].ownsDeleter = false;
313 meta.freeIds_.push_back(id);
315 // Delete elements outside the lock
316 FOR_EACH(it, elements) {
317 it->dispose(TLPDestructionMode::ALL_THREADS);
319 } catch (...) { // Just in case we get a lock error or something anyway...
320 LOG(WARNING) << "Destructor discarding an exception that was thrown.";
325 * Reserve enough space in the ThreadEntry::elements for the item
328 static void reserve(int id) {
329 auto& meta = instance();
330 ThreadEntry* threadEntry = getThreadEntry();
331 size_t prevCapacity = threadEntry->elementsCapacity;
332 // Growth factor < 2, see folly/docs/FBVector.md; + 5 to prevent
334 size_t newCapacity = static_cast<size_t>((id + 5) * 1.7);
335 assert(newCapacity > prevCapacity);
336 ElementWrapper* reallocated = nullptr;
338 // Need to grow. Note that we can't call realloc, as elements is
339 // still linked in meta, so another thread might access invalid memory
340 // after realloc succeeds. We'll copy by hand and update our ThreadEntry
342 if (usingJEMalloc()) {
343 bool success = false;
344 size_t newByteSize = nallocx(newCapacity * sizeof(ElementWrapper), 0);
346 // Try to grow in place.
348 // Note that xallocx(MALLOCX_ZERO) will only zero newly allocated memory,
349 // even if a previous allocation allocated more than we requested.
350 // This is fine; we always use MALLOCX_ZERO with jemalloc and we
351 // always expand our allocation to the real size.
352 if (prevCapacity * sizeof(ElementWrapper) >=
353 jemallocMinInPlaceExpandable) {
354 success = (xallocx(threadEntry->elements, newByteSize, 0, MALLOCX_ZERO)
358 // In-place growth failed.
360 success = ((reallocated = static_cast<ElementWrapper*>(
361 mallocx(newByteSize, MALLOCX_ZERO))) != nullptr);
365 // Expand to real size
366 assert(newByteSize / sizeof(ElementWrapper) >= newCapacity);
367 newCapacity = newByteSize / sizeof(ElementWrapper);
369 throw std::bad_alloc();
371 } else { // no jemalloc
372 // calloc() is simpler than malloc() followed by memset(), and
373 // potentially faster when dealing with a lot of memory, as it can get
374 // already-zeroed pages from the kernel.
375 reallocated = static_cast<ElementWrapper*>(
376 calloc(newCapacity, sizeof(ElementWrapper)));
378 throw std::bad_alloc();
382 // Success, update the entry
384 std::lock_guard<std::mutex> g(meta.lock_);
386 if (prevCapacity == 0) {
387 meta.push_back(threadEntry);
392 * Note: we need to hold the meta lock when copying data out of
393 * the old vector, because some other thread might be
394 * destructing a ThreadLocal and writing to the elements vector
397 memcpy(reallocated, threadEntry->elements,
398 sizeof(ElementWrapper) * prevCapacity);
400 swap(reallocated, threadEntry->elements);
402 threadEntry->elementsCapacity = newCapacity;
408 if (prevCapacity == 0) {
409 pthread_setspecific(meta.pthreadKey_, &meta);
414 static ElementWrapper& get(size_t id) {
415 ThreadEntry* threadEntry = getThreadEntry();
416 if (UNLIKELY(threadEntry->elementsCapacity <= id)) {
418 assert(threadEntry->elementsCapacity > id);
420 return threadEntry->elements[id];
426 FOLLY_TLS ThreadEntry StaticMeta<Tag>::threadEntry_{nullptr, 0,
429 template <class Tag> StaticMeta<Tag>* StaticMeta<Tag>::inst_ = nullptr;
431 } // namespace threadlocal_detail
434 #endif /* FOLLY_DETAIL_THREADLOCALDETAIL_H_ */