2 * Copyright 2016 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.
28 #include <glog/logging.h>
30 #include <folly/Exception.h>
31 #include <folly/Foreach.h>
32 #include <folly/Function.h>
33 #include <folly/Malloc.h>
34 #include <folly/MicroSpinLock.h>
35 #include <folly/Portability.h>
36 #include <folly/ScopeGuard.h>
38 #include <folly/detail/StaticSingletonManager.h>
40 // In general, emutls cleanup is not guaranteed to play nice with the way
41 // StaticMeta mixes direct pthread calls and the use of __thread. This has
42 // caused problems on multiple platforms so don't use __thread there.
44 // XXX: Ideally we would instead determine if emutls is in use at runtime as it
45 // is possible to configure glibc on Linux to use emutls regardless.
46 #if !FOLLY_MOBILE && !defined(__APPLE__)
47 #define FOLLY_TLD_USE_FOLLY_TLS 1
49 #undef FOLLY_TLD_USE_FOLLY_TLS
53 namespace threadlocal_detail {
56 * POD wrapper around an element (a void*) and an associated deleter.
57 * This must be POD, as we memset() it to 0 and memcpy() it around.
59 struct ElementWrapper {
60 using DeleterFunType = void(void*, TLPDestructionMode);
62 bool dispose(TLPDestructionMode mode) {
67 DCHECK(deleter1 != nullptr);
68 ownsDeleter ? (*deleter2)(ptr, mode) : (*deleter1)(ptr, mode);
85 auto guard = makeGuard([&] { delete p; });
86 DCHECK(ptr == nullptr);
87 DCHECK(deleter1 == nullptr);
91 deleter1 = [](void* pt, TLPDestructionMode) {
92 delete static_cast<Ptr>(pt);
99 template <class Ptr, class Deleter>
100 void set(Ptr p, const Deleter& d) {
101 auto guard = makeGuard([&] {
103 d(p, TLPDestructionMode::THIS_THREAD);
106 DCHECK(ptr == nullptr);
107 DCHECK(deleter2 == nullptr);
110 auto d2 = d; // gcc-4.8 doesn't decay types correctly in lambda captures
111 deleter2 = new std::function<DeleterFunType>(
112 [d2](void* pt, TLPDestructionMode mode) {
113 d2(static_cast<Ptr>(pt), mode);
131 DeleterFunType* deleter1;
132 std::function<DeleterFunType>* deleter2;
137 struct StaticMetaBase;
140 * Per-thread entry. Each thread using a StaticMeta object has one.
141 * This is written from the owning thread only (under the lock), read
142 * from the owning thread (no lock necessary), and read from other threads
146 ElementWrapper* elements{nullptr};
147 size_t elementsCapacity{0};
148 ThreadEntry* next{nullptr};
149 ThreadEntry* prev{nullptr};
150 StaticMetaBase* meta{nullptr};
153 constexpr uint32_t kEntryIDInvalid = std::numeric_limits<uint32_t>::max();
155 class PthreadKeyUnregisterTester;
158 * We want to disable onThreadExit call at the end of shutdown, we don't care
159 * about leaking memory at that point.
161 * Otherwise if ThreadLocal is used in a shared library, onThreadExit may be
162 * called after dlclose().
164 * This class has one single static instance; however since it's so widely used,
165 * directly or indirectly, by so many classes, we need to take care to avoid
166 * problems stemming from the Static Initialization/Destruction Order Fiascos.
167 * Therefore this class needs to be constexpr-constructible, so as to avoid
168 * the need for this to participate in init/destruction order.
170 class PthreadKeyUnregister {
172 static constexpr size_t kMaxKeys = 1UL << 16;
174 ~PthreadKeyUnregister() {
177 pthread_key_delete(keys_[--size_]);
181 static void registerKey(pthread_key_t key) {
182 instance_.registerKeyImpl(key);
187 * Only one global instance should exist, hence this is private.
188 * See also the important note at the top of this class about `constexpr`
191 constexpr PthreadKeyUnregister() : lock_(), size_(0), keys_() { }
192 friend class folly::threadlocal_detail::PthreadKeyUnregisterTester;
194 void registerKeyImpl(pthread_key_t key) {
196 if (size_ == kMaxKeys) {
197 throw std::logic_error("pthread_key limit has already been reached");
199 keys_[size_++] = key;
204 pthread_key_t keys_[kMaxKeys];
206 static PthreadKeyUnregister instance_;
209 struct StaticMetaBase {
210 // Represents an ID of a thread local object. Initially set to the maximum
211 // uint. This representation allows us to avoid a branch in accessing TLS data
212 // (because if you test capacity > id if id = maxint then the test will always
213 // fail). It allows us to keep a constexpr constructor and avoid SIOF.
216 std::atomic<uint32_t> value;
218 constexpr EntryID() : value(kEntryIDInvalid) {
221 EntryID(EntryID&& other) noexcept : value(other.value.load()) {
222 other.value = kEntryIDInvalid;
225 EntryID& operator=(EntryID&& other) {
226 assert(this != &other);
227 value = other.value.load();
228 other.value = kEntryIDInvalid;
232 EntryID(const EntryID& other) = delete;
233 EntryID& operator=(const EntryID& other) = delete;
235 uint32_t getOrInvalid() {
236 // It's OK for this to be relaxed, even though we're effectively doing
237 // double checked locking in using this value. We only care about the
238 // uniqueness of IDs, getOrAllocate does not modify any other memory
239 // this thread will use.
240 return value.load(std::memory_order_relaxed);
243 uint32_t getOrAllocate(StaticMetaBase& meta) {
244 uint32_t id = getOrInvalid();
245 if (id != kEntryIDInvalid) {
248 // The lock inside allocate ensures that a single value is allocated
249 return meta.allocate(this);
253 explicit StaticMetaBase(ThreadEntry* (*threadEntry)());
256 LOG(FATAL) << "StaticMeta lives forever!";
259 void push_back(ThreadEntry* t) {
261 t->prev = head_.prev;
262 head_.prev->next = t;
266 void erase(ThreadEntry* t) {
267 t->next->prev = t->prev;
268 t->prev->next = t->next;
269 t->next = t->prev = t;
272 static void onThreadExit(void* ptr);
274 uint32_t allocate(EntryID* ent);
276 void destroy(EntryID* ent);
279 * Reserve enough space in the ThreadEntry::elements for the item
282 void reserve(EntryID* id);
284 ElementWrapper& get(EntryID* ent);
286 static void initAtFork();
287 static void registerAtFork(
288 folly::Function<void()> prepare,
289 folly::Function<void()> parent,
290 folly::Function<void()> child);
293 std::vector<uint32_t> freeIds_;
295 pthread_key_t pthreadKey_;
297 ThreadEntry* (*threadEntry_)();
300 // Held in a singleton to track our global instances.
301 // We have one of these per "Tag", by default one for the whole system
304 // Creating and destroying ThreadLocalPtr objects, as well as thread exit
305 // for threads that use ThreadLocalPtr objects collide on a lock inside
306 // StaticMeta; you can specify multiple Tag types to break that lock.
308 struct StaticMeta : StaticMetaBase {
309 StaticMeta() : StaticMetaBase(&StaticMeta::getThreadEntrySlow) {
311 /*prepare*/ &StaticMeta::preFork,
312 /*parent*/ &StaticMeta::onForkParent,
313 /*child*/ &StaticMeta::onForkChild);
316 static StaticMeta<Tag>& instance() {
317 // Leak it on exit, there's only one per process and we don't have to
318 // worry about synchronization with exiting threads.
319 static auto instance = detail::createGlobal<StaticMeta<Tag>, void>();
323 ElementWrapper& get(EntryID* ent) {
324 ThreadEntry* threadEntry = getThreadEntry();
325 uint32_t id = ent->getOrInvalid();
326 // if id is invalid, it is equal to uint32_t's max value.
327 // x <= max value is always true
328 if (UNLIKELY(threadEntry->elementsCapacity <= id)) {
330 id = ent->getOrInvalid();
331 assert(threadEntry->elementsCapacity > id);
333 return threadEntry->elements[id];
336 static ThreadEntry* getThreadEntrySlow() {
337 auto& meta = instance();
338 auto key = meta.pthreadKey_;
339 ThreadEntry* threadEntry =
340 static_cast<ThreadEntry*>(pthread_getspecific(key));
342 #ifdef FOLLY_TLD_USE_FOLLY_TLS
343 static FOLLY_TLS ThreadEntry threadEntrySingleton;
344 threadEntry = &threadEntrySingleton;
346 threadEntry = new ThreadEntry();
348 threadEntry->meta = &meta;
349 int ret = pthread_setspecific(key, threadEntry);
350 checkPosixError(ret, "pthread_setspecific failed");
355 inline static ThreadEntry* getThreadEntry() {
356 #ifdef FOLLY_TLD_USE_FOLLY_TLS
357 static FOLLY_TLS ThreadEntry* threadEntryCache{nullptr};
358 if (UNLIKELY(threadEntryCache == nullptr)) {
359 threadEntryCache = instance().threadEntry_();
361 return threadEntryCache;
363 return instance().threadEntry_();
367 static void preFork(void) {
368 instance().lock_.lock(); // Make sure it's created
371 static void onForkParent(void) { instance().lock_.unlock(); }
373 static void onForkChild(void) {
374 // only the current thread survives
375 instance().head_.next = instance().head_.prev = &instance().head_;
376 ThreadEntry* threadEntry = getThreadEntry();
377 // If this thread was in the list before the fork, add it back.
378 if (threadEntry->elementsCapacity != 0) {
379 instance().push_back(threadEntry);
381 instance().lock_.unlock();
385 } // namespace threadlocal_detail