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.
16 #include <folly/ThreadLocal.h>
21 namespace folly { namespace threadlocal_detail {
23 StaticMetaBase::StaticMetaBase(ThreadEntry* (*threadEntry)(), bool strict)
24 : nextId_(1), threadEntry_(threadEntry), strict_(strict) {
25 head_.next = head_.prev = &head_;
26 int ret = pthread_key_create(&pthreadKey_, &onThreadExit);
27 checkPosixError(ret, "pthread_key_create failed");
28 PthreadKeyUnregister::registerKey(pthreadKey_);
31 void StaticMetaBase::onThreadExit(void* ptr) {
32 #ifdef FOLLY_TLD_USE_FOLLY_TLS
33 auto threadEntry = static_cast<ThreadEntry*>(ptr);
35 std::unique_ptr<ThreadEntry> threadEntry(static_cast<ThreadEntry*>(ptr));
37 DCHECK_GT(threadEntry->elementsCapacity, 0);
38 auto& meta = *threadEntry->meta;
40 // Make sure this ThreadEntry is available if ThreadLocal A is accessed in
41 // ThreadLocal B destructor.
42 pthread_setspecific(meta.pthreadKey_, &(*threadEntry));
44 pthread_setspecific(meta.pthreadKey_, nullptr);
48 SharedMutex::ReadHolder rlock;
50 rlock = SharedMutex::ReadHolder(meta.accessAllThreadsLock_);
53 std::lock_guard<std::mutex> g(meta.lock_);
54 meta.erase(&(*threadEntry));
55 // No need to hold the lock any longer; the ThreadEntry is private to this
56 // thread now that it's been removed from meta.
58 // NOTE: User-provided deleter / object dtor itself may be using ThreadLocal
59 // with the same Tag, so dispose() calls below may (re)create some of the
60 // elements or even increase elementsCapacity, thus multiple cleanup rounds
62 for (bool shouldRun = true; shouldRun;) {
64 FOR_EACH_RANGE (i, 0, threadEntry->elementsCapacity) {
65 if (threadEntry->elements[i].dispose(TLPDestructionMode::THIS_THREAD)) {
71 free(threadEntry->elements);
72 threadEntry->elements = nullptr;
73 threadEntry->meta = nullptr;
76 uint32_t StaticMetaBase::allocate(EntryID* ent) {
79 std::lock_guard<std::mutex> g(meta.lock_);
81 id = ent->value.load();
82 if (id != kEntryIDInvalid) {
86 if (!meta.freeIds_.empty()) {
87 id = meta.freeIds_.back();
88 meta.freeIds_.pop_back();
93 uint32_t old_id = ent->value.exchange(id);
94 DCHECK_EQ(old_id, kEntryIDInvalid);
98 void StaticMetaBase::destroy(EntryID* ent) {
101 // Elements in other threads that use this id.
102 std::vector<ElementWrapper> elements;
104 std::lock_guard<std::mutex> g(meta.lock_);
105 uint32_t id = ent->value.exchange(kEntryIDInvalid);
106 if (id == kEntryIDInvalid) {
110 for (ThreadEntry* e = meta.head_.next; e != &meta.head_; e = e->next) {
111 if (id < e->elementsCapacity && e->elements[id].ptr) {
112 elements.push_back(e->elements[id]);
115 * Writing another thread's ThreadEntry from here is fine;
116 * the only other potential reader is the owning thread --
117 * from onThreadExit (which grabs the lock, so is properly
118 * synchronized with us) or from get(), which also grabs
119 * the lock if it needs to resize the elements vector.
121 * We can't conflict with reads for a get(id), because
122 * it's illegal to call get on a thread local that's
125 e->elements[id].ptr = nullptr;
126 e->elements[id].deleter1 = nullptr;
127 e->elements[id].ownsDeleter = false;
130 meta.freeIds_.push_back(id);
132 // Delete elements outside the lock
133 for (ElementWrapper& elem : elements) {
134 elem.dispose(TLPDestructionMode::ALL_THREADS);
136 } catch (...) { // Just in case we get a lock error or something anyway...
137 LOG(WARNING) << "Destructor discarding an exception that was thrown.";
142 * Reserve enough space in the ThreadEntry::elements for the item
145 void StaticMetaBase::reserve(EntryID* id) {
147 ThreadEntry* threadEntry = (*threadEntry_)();
148 size_t prevCapacity = threadEntry->elementsCapacity;
150 uint32_t idval = id->getOrAllocate(meta);
151 if (prevCapacity > idval) {
154 // Growth factor < 2, see folly/docs/FBVector.md; + 5 to prevent
156 size_t newCapacity = static_cast<size_t>((idval + 5) * 1.7);
157 assert(newCapacity > prevCapacity);
158 ElementWrapper* reallocated = nullptr;
160 // Need to grow. Note that we can't call realloc, as elements is
161 // still linked in meta, so another thread might access invalid memory
162 // after realloc succeeds. We'll copy by hand and update our ThreadEntry
164 if (usingJEMalloc()) {
165 bool success = false;
166 size_t newByteSize = nallocx(newCapacity * sizeof(ElementWrapper), 0);
168 // Try to grow in place.
170 // Note that xallocx(MALLOCX_ZERO) will only zero newly allocated memory,
171 // even if a previous allocation allocated more than we requested.
172 // This is fine; we always use MALLOCX_ZERO with jemalloc and we
173 // always expand our allocation to the real size.
174 if (prevCapacity * sizeof(ElementWrapper) >= jemallocMinInPlaceExpandable) {
176 (xallocx(threadEntry->elements, newByteSize, 0, MALLOCX_ZERO) ==
180 // In-place growth failed.
183 ((reallocated = static_cast<ElementWrapper*>(
184 mallocx(newByteSize, MALLOCX_ZERO))) != nullptr);
188 // Expand to real size
189 assert(newByteSize / sizeof(ElementWrapper) >= newCapacity);
190 newCapacity = newByteSize / sizeof(ElementWrapper);
192 throw std::bad_alloc();
194 } else { // no jemalloc
195 // calloc() is simpler than malloc() followed by memset(), and
196 // potentially faster when dealing with a lot of memory, as it can get
197 // already-zeroed pages from the kernel.
198 reallocated = static_cast<ElementWrapper*>(
199 calloc(newCapacity, sizeof(ElementWrapper)));
201 throw std::bad_alloc();
205 // Success, update the entry
207 std::lock_guard<std::mutex> g(meta.lock_);
209 if (prevCapacity == 0) {
210 meta.push_back(threadEntry);
215 * Note: we need to hold the meta lock when copying data out of
216 * the old vector, because some other thread might be
217 * destructing a ThreadLocal and writing to the elements vector
220 if (prevCapacity != 0) {
223 threadEntry->elements,
224 sizeof(*reallocated) * prevCapacity);
226 std::swap(reallocated, threadEntry->elements);
228 threadEntry->elementsCapacity = newCapacity;
237 folly::Function<void()> prepare;
238 folly::Function<void()> parent;
239 folly::Function<void()> child;
244 static AtForkList& instance() {
245 static auto instance = new AtForkList();
249 static void prepare() noexcept {
250 instance().tasksLock.lock();
251 auto& tasks = instance().tasks;
252 for (auto task = tasks.rbegin(); task != tasks.rend(); ++task) {
257 static void parent() noexcept {
258 auto& tasks = instance().tasks;
259 for (auto& task : tasks) {
262 instance().tasksLock.unlock();
265 static void child() noexcept {
266 auto& tasks = instance().tasks;
267 for (auto& task : tasks) {
270 instance().tasksLock.unlock();
273 std::mutex tasksLock;
274 std::list<AtForkTask> tasks;
278 #if FOLLY_HAVE_PTHREAD_ATFORK
279 int ret = pthread_atfork(
280 &AtForkList::prepare, &AtForkList::parent, &AtForkList::child);
281 checkPosixError(ret, "pthread_atfork failed");
282 #elif !__ANDROID__ && !defined(_MSC_VER)
283 // pthread_atfork is not part of the Android NDK at least as of n9d. If
284 // something is trying to call native fork() directly at all with Android's
285 // process management model, this is probably the least of the problems.
287 // But otherwise, this is a problem.
288 #warning pthread_atfork unavailable
294 void StaticMetaBase::initAtFork() {
295 AtForkList::instance();
298 void StaticMetaBase::registerAtFork(
299 folly::Function<void()> prepare,
300 folly::Function<void()> parent,
301 folly::Function<void()> child) {
302 std::lock_guard<std::mutex> lg(AtForkList::instance().tasksLock);
303 AtForkList::instance().tasks.push_back(
304 {std::move(prepare), std::move(parent), std::move(child)});
307 FOLLY_STATIC_CTOR_PRIORITY_MAX
308 PthreadKeyUnregister PthreadKeyUnregister::instance_;