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>
18 namespace folly { namespace threadlocal_detail {
20 StaticMetaBase::StaticMetaBase(ThreadEntry* (*threadEntry)())
21 : nextId_(1), threadEntry_(threadEntry) {
22 head_.next = head_.prev = &head_;
23 int ret = pthread_key_create(&pthreadKey_, &onThreadExit);
24 checkPosixError(ret, "pthread_key_create failed");
25 PthreadKeyUnregister::registerKey(pthreadKey_);
28 void StaticMetaBase::onThreadExit(void* ptr) {
29 #ifdef FOLLY_TLD_USE_FOLLY_TLS
30 auto threadEntry = static_cast<ThreadEntry*>(ptr);
32 std::unique_ptr<ThreadEntry> threadEntry(static_cast<ThreadEntry*>(ptr));
34 DCHECK_GT(threadEntry->elementsCapacity, 0);
35 auto& meta = *threadEntry->meta;
37 // Make sure this ThreadEntry is available if ThreadLocal A is accessed in
38 // ThreadLocal B destructor.
39 pthread_setspecific(meta.pthreadKey_, &(*threadEntry));
41 pthread_setspecific(meta.pthreadKey_, nullptr);
45 std::lock_guard<std::mutex> g(meta.lock_);
46 meta.erase(&(*threadEntry));
47 // No need to hold the lock any longer; the ThreadEntry is private to this
48 // thread now that it's been removed from meta.
50 // NOTE: User-provided deleter / object dtor itself may be using ThreadLocal
51 // with the same Tag, so dispose() calls below may (re)create some of the
52 // elements or even increase elementsCapacity, thus multiple cleanup rounds
54 for (bool shouldRun = true; shouldRun;) {
56 FOR_EACH_RANGE (i, 0, threadEntry->elementsCapacity) {
57 if (threadEntry->elements[i].dispose(TLPDestructionMode::THIS_THREAD)) {
62 free(threadEntry->elements);
63 threadEntry->elements = nullptr;
64 threadEntry->meta = nullptr;
67 uint32_t StaticMetaBase::allocate(EntryID* ent) {
70 std::lock_guard<std::mutex> g(meta.lock_);
72 id = ent->value.load();
73 if (id != kEntryIDInvalid) {
77 if (!meta.freeIds_.empty()) {
78 id = meta.freeIds_.back();
79 meta.freeIds_.pop_back();
84 uint32_t old_id = ent->value.exchange(id);
85 DCHECK_EQ(old_id, kEntryIDInvalid);
89 void StaticMetaBase::destroy(EntryID* ent) {
92 // Elements in other threads that use this id.
93 std::vector<ElementWrapper> elements;
95 std::lock_guard<std::mutex> g(meta.lock_);
96 uint32_t id = ent->value.exchange(kEntryIDInvalid);
97 if (id == kEntryIDInvalid) {
101 for (ThreadEntry* e = meta.head_.next; e != &meta.head_; e = e->next) {
102 if (id < e->elementsCapacity && e->elements[id].ptr) {
103 elements.push_back(e->elements[id]);
106 * Writing another thread's ThreadEntry from here is fine;
107 * the only other potential reader is the owning thread --
108 * from onThreadExit (which grabs the lock, so is properly
109 * synchronized with us) or from get(), which also grabs
110 * the lock if it needs to resize the elements vector.
112 * We can't conflict with reads for a get(id), because
113 * it's illegal to call get on a thread local that's
116 e->elements[id].ptr = nullptr;
117 e->elements[id].deleter1 = nullptr;
118 e->elements[id].ownsDeleter = false;
121 meta.freeIds_.push_back(id);
123 // Delete elements outside the lock
124 for (ElementWrapper& elem : elements) {
125 elem.dispose(TLPDestructionMode::ALL_THREADS);
127 } catch (...) { // Just in case we get a lock error or something anyway...
128 LOG(WARNING) << "Destructor discarding an exception that was thrown.";
133 * Reserve enough space in the ThreadEntry::elements for the item
136 void StaticMetaBase::reserve(EntryID* id) {
138 ThreadEntry* threadEntry = (*threadEntry_)();
139 size_t prevCapacity = threadEntry->elementsCapacity;
141 uint32_t idval = id->getOrAllocate(meta);
142 if (prevCapacity > idval) {
145 // Growth factor < 2, see folly/docs/FBVector.md; + 5 to prevent
147 size_t newCapacity = static_cast<size_t>((idval + 5) * 1.7);
148 assert(newCapacity > prevCapacity);
149 ElementWrapper* reallocated = nullptr;
151 // Need to grow. Note that we can't call realloc, as elements is
152 // still linked in meta, so another thread might access invalid memory
153 // after realloc succeeds. We'll copy by hand and update our ThreadEntry
155 if (usingJEMalloc()) {
156 bool success = false;
157 size_t newByteSize = nallocx(newCapacity * sizeof(ElementWrapper), 0);
159 // Try to grow in place.
161 // Note that xallocx(MALLOCX_ZERO) will only zero newly allocated memory,
162 // even if a previous allocation allocated more than we requested.
163 // This is fine; we always use MALLOCX_ZERO with jemalloc and we
164 // always expand our allocation to the real size.
165 if (prevCapacity * sizeof(ElementWrapper) >= jemallocMinInPlaceExpandable) {
167 (xallocx(threadEntry->elements, newByteSize, 0, MALLOCX_ZERO) ==
171 // In-place growth failed.
174 ((reallocated = static_cast<ElementWrapper*>(
175 mallocx(newByteSize, MALLOCX_ZERO))) != nullptr);
179 // Expand to real size
180 assert(newByteSize / sizeof(ElementWrapper) >= newCapacity);
181 newCapacity = newByteSize / sizeof(ElementWrapper);
183 throw std::bad_alloc();
185 } else { // no jemalloc
186 // calloc() is simpler than malloc() followed by memset(), and
187 // potentially faster when dealing with a lot of memory, as it can get
188 // already-zeroed pages from the kernel.
189 reallocated = static_cast<ElementWrapper*>(
190 calloc(newCapacity, sizeof(ElementWrapper)));
192 throw std::bad_alloc();
196 // Success, update the entry
198 std::lock_guard<std::mutex> g(meta.lock_);
200 if (prevCapacity == 0) {
201 meta.push_back(threadEntry);
206 * Note: we need to hold the meta lock when copying data out of
207 * the old vector, because some other thread might be
208 * destructing a ThreadLocal and writing to the elements vector
211 if (prevCapacity != 0) {
214 threadEntry->elements,
215 sizeof(*reallocated) * prevCapacity);
217 std::swap(reallocated, threadEntry->elements);
219 threadEntry->elementsCapacity = newCapacity;
225 FOLLY_STATIC_CTOR_PRIORITY_MAX
226 PthreadKeyUnregister PthreadKeyUnregister::instance_;