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.
17 #ifndef FOLLY_DETAIL_THREADLOCALDETAIL_H_
18 #define FOLLY_DETAIL_THREADLOCALDETAIL_H_
29 #include <glog/logging.h>
31 #include <folly/Foreach.h>
32 #include <folly/Exception.h>
33 #include <folly/Malloc.h>
34 #include <folly/MicroSpinLock.h>
36 #include <folly/detail/StaticSingletonManager.h>
38 // In general, emutls cleanup is not guaranteed to play nice with the way
39 // StaticMeta mixes direct pthread calls and the use of __thread. This has
40 // caused problems on multiple platforms so don't use __thread there.
42 // XXX: Ideally we would instead determine if emutls is in use at runtime as it
43 // is possible to configure glibc on Linux to use emutls regardless.
44 #if !__APPLE__ && !__ANDROID__
45 #define FOLLY_TLD_USE_FOLLY_TLS 1
47 #undef FOLLY_TLD_USE_FOLLY_TLS
51 namespace threadlocal_detail {
54 * POD wrapper around an element (a void*) and an associated deleter.
55 * This must be POD, as we memset() it to 0 and memcpy() it around.
57 struct ElementWrapper {
58 using DeleterFunType = void(void*, TLPDestructionMode);
60 bool dispose(TLPDestructionMode mode) {
65 DCHECK(deleter1 != nullptr);
66 ownsDeleter ? (*deleter2)(ptr, mode) : (*deleter1)(ptr, mode);
83 DCHECK(ptr == nullptr);
84 DCHECK(deleter1 == nullptr);
89 +[](void* pt, TLPDestructionMode) { delete static_cast<Ptr>(pt); };
94 template <class Ptr, class Deleter>
95 void set(Ptr p, Deleter d) {
96 DCHECK(ptr == nullptr);
97 DCHECK(deleter2 == nullptr);
100 deleter2 = new std::function<DeleterFunType>(
101 [d](void* pt, TLPDestructionMode mode) {
102 d(static_cast<Ptr>(pt), mode);
119 DeleterFunType* deleter1;
120 std::function<DeleterFunType>* deleter2;
125 struct StaticMetaBase;
128 * Per-thread entry. Each thread using a StaticMeta object has one.
129 * This is written from the owning thread only (under the lock), read
130 * from the owning thread (no lock necessary), and read from other threads
134 ElementWrapper* elements{nullptr};
135 size_t elementsCapacity{0};
136 ThreadEntry* next{nullptr};
137 ThreadEntry* prev{nullptr};
138 StaticMetaBase* meta{nullptr};
141 constexpr uint32_t kEntryIDInvalid = std::numeric_limits<uint32_t>::max();
143 class PthreadKeyUnregisterTester;
146 * We want to disable onThreadExit call at the end of shutdown, we don't care
147 * about leaking memory at that point.
149 * Otherwise if ThreadLocal is used in a shared library, onThreadExit may be
150 * called after dlclose().
152 * This class has one single static instance; however since it's so widely used,
153 * directly or indirectly, by so many classes, we need to take care to avoid
154 * problems stemming from the Static Initialization/Destruction Order Fiascos.
155 * Therefore this class needs to be constexpr-constructible, so as to avoid
156 * the need for this to participate in init/destruction order.
158 class PthreadKeyUnregister {
160 static constexpr size_t kMaxKeys = 1UL << 16;
162 ~PthreadKeyUnregister() {
165 pthread_key_delete(keys_[--size_]);
169 static void registerKey(pthread_key_t key) {
170 instance_.registerKeyImpl(key);
175 * Only one global instance should exist, hence this is private.
176 * See also the important note at the top of this class about `constexpr`
179 constexpr PthreadKeyUnregister() : lock_(), size_(0), keys_() { }
180 friend class folly::threadlocal_detail::PthreadKeyUnregisterTester;
182 void registerKeyImpl(pthread_key_t key) {
184 if (size_ == kMaxKeys) {
185 throw std::logic_error("pthread_key limit has already been reached");
187 keys_[size_++] = key;
192 pthread_key_t keys_[kMaxKeys];
194 static PthreadKeyUnregister instance_;
197 struct StaticMetaBase {
198 // Represents an ID of a thread local object. Initially set to the maximum
199 // uint. This representation allows us to avoid a branch in accessing TLS data
200 // (because if you test capacity > id if id = maxint then the test will always
201 // fail). It allows us to keep a constexpr constructor and avoid SIOF.
204 std::atomic<uint32_t> value;
206 constexpr EntryID() : value(kEntryIDInvalid) {
209 EntryID(EntryID&& other) noexcept : value(other.value.load()) {
210 other.value = kEntryIDInvalid;
213 EntryID& operator=(EntryID&& other) {
214 assert(this != &other);
215 value = other.value.load();
216 other.value = kEntryIDInvalid;
220 EntryID(const EntryID& other) = delete;
221 EntryID& operator=(const EntryID& other) = delete;
223 uint32_t getOrInvalid() {
224 // It's OK for this to be relaxed, even though we're effectively doing
225 // double checked locking in using this value. We only care about the
226 // uniqueness of IDs, getOrAllocate does not modify any other memory
227 // this thread will use.
228 return value.load(std::memory_order_relaxed);
231 uint32_t getOrAllocate(StaticMetaBase& meta) {
232 uint32_t id = getOrInvalid();
233 if (id != kEntryIDInvalid) {
236 // The lock inside allocate ensures that a single value is allocated
237 return meta.allocate(this);
241 explicit StaticMetaBase(ThreadEntry* (*threadEntry)());
244 LOG(FATAL) << "StaticMeta lives forever!";
247 void push_back(ThreadEntry* t) {
249 t->prev = head_.prev;
250 head_.prev->next = t;
254 void erase(ThreadEntry* t) {
255 t->next->prev = t->prev;
256 t->prev->next = t->next;
257 t->next = t->prev = t;
260 static void onThreadExit(void* ptr);
262 uint32_t allocate(EntryID* ent);
264 void destroy(EntryID* ent);
267 * Reserve enough space in the ThreadEntry::elements for the item
270 void reserve(EntryID* id);
272 ElementWrapper& get(EntryID* ent);
275 std::vector<uint32_t> freeIds_;
277 pthread_key_t pthreadKey_;
279 ThreadEntry* (*threadEntry_)();
282 // Held in a singleton to track our global instances.
283 // We have one of these per "Tag", by default one for the whole system
286 // Creating and destroying ThreadLocalPtr objects, as well as thread exit
287 // for threads that use ThreadLocalPtr objects collide on a lock inside
288 // StaticMeta; you can specify multiple Tag types to break that lock.
290 struct StaticMeta : StaticMetaBase {
291 StaticMeta() : StaticMetaBase(&StaticMeta::getThreadEntry) {
292 #if FOLLY_HAVE_PTHREAD_ATFORK
293 int ret = pthread_atfork(
294 /*prepare*/ &StaticMeta::preFork,
295 /*parent*/ &StaticMeta::onForkParent,
296 /*child*/ &StaticMeta::onForkChild);
297 checkPosixError(ret, "pthread_atfork failed");
298 #elif !__ANDROID__ && !defined(_MSC_VER)
299 // pthread_atfork is not part of the Android NDK at least as of n9d. If
300 // something is trying to call native fork() directly at all with Android's
301 // process management model, this is probably the least of the problems.
303 // But otherwise, this is a problem.
304 #warning pthread_atfork unavailable
308 static StaticMeta<Tag>& instance() {
309 // Leak it on exit, there's only one per process and we don't have to
310 // worry about synchronization with exiting threads.
311 static auto instance = detail::createGlobal<StaticMeta<Tag>, void>();
315 static ThreadEntry* getThreadEntrySlow() {
316 auto& meta = instance();
317 auto key = meta.pthreadKey_;
318 ThreadEntry* threadEntry =
319 static_cast<ThreadEntry*>(pthread_getspecific(key));
321 threadEntry = new ThreadEntry();
322 threadEntry->meta = &meta;
323 int ret = pthread_setspecific(key, threadEntry);
324 checkPosixError(ret, "pthread_setspecific failed");
329 static ThreadEntry* getThreadEntry() {
330 #ifdef FOLLY_TLD_USE_FOLLY_TLS
331 static FOLLY_TLS ThreadEntry* threadEntryCache{nullptr};
332 if (UNLIKELY(threadEntryCache == nullptr)) {
333 threadEntryCache = getThreadEntrySlow();
335 return threadEntryCache;
337 return getThreadEntrySlow();
341 static void preFork(void) {
342 instance().lock_.lock(); // Make sure it's created
345 static void onForkParent(void) { instance().lock_.unlock(); }
347 static void onForkChild(void) {
348 // only the current thread survives
349 instance().head_.next = instance().head_.prev = &instance().head_;
350 ThreadEntry* threadEntry = getThreadEntry();
351 // If this thread was in the list before the fork, add it back.
352 if (threadEntry->elementsCapacity != 0) {
353 instance().push_back(threadEntry);
355 instance().lock_.unlock();
359 } // namespace threadlocal_detail
362 #endif /* FOLLY_DETAIL_THREADLOCALDETAIL_H_ */