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 #include <folly/ThreadLocal.h>
20 #include <sys/types.h>
27 #include <condition_variable>
33 #include <unordered_map>
35 #include <boost/thread/tss.hpp>
36 #include <gflags/gflags.h>
37 #include <glog/logging.h>
38 #include <gtest/gtest.h>
40 #include <folly/Benchmark.h>
41 #include <folly/Baton.h>
42 #include <folly/experimental/io/FsUtil.h>
44 using namespace folly;
53 static void customDeleter(Widget* w, TLPDestructionMode mode) {
54 totalVal_ += (mode == TLPDestructionMode::ALL_THREADS) * 1000;
58 int Widget::totalVal_ = 0;
60 TEST(ThreadLocalPtr, BasicDestructor) {
61 Widget::totalVal_ = 0;
62 ThreadLocalPtr<Widget> w;
64 w.reset(new Widget());
67 EXPECT_EQ(10, Widget::totalVal_);
70 TEST(ThreadLocalPtr, CustomDeleter1) {
71 Widget::totalVal_ = 0;
73 ThreadLocalPtr<Widget> w;
75 w.reset(new Widget(), Widget::customDeleter);
78 EXPECT_EQ(10, Widget::totalVal_);
80 EXPECT_EQ(10, Widget::totalVal_);
83 TEST(ThreadLocalPtr, resetNull) {
84 ThreadLocalPtr<int> tl;
87 EXPECT_TRUE(static_cast<bool>(tl));
88 EXPECT_EQ(*tl.get(), 4);
93 TEST(ThreadLocalPtr, TestRelease) {
94 Widget::totalVal_ = 0;
95 ThreadLocalPtr<Widget> w;
96 std::unique_ptr<Widget> wPtr;
97 std::thread([&w, &wPtr]() {
98 w.reset(new Widget());
101 wPtr.reset(w.release());
103 EXPECT_EQ(0, Widget::totalVal_);
105 EXPECT_EQ(10, Widget::totalVal_);
108 TEST(ThreadLocalPtr, CreateOnThreadExit) {
109 Widget::totalVal_ = 0;
110 ThreadLocal<Widget> w;
111 ThreadLocalPtr<int> tl;
115 [&](int* ptr, TLPDestructionMode /* mode */) {
117 // This test ensures Widgets allocated here are not leaked.
119 ThreadLocal<Widget> wl;
123 EXPECT_EQ(2, Widget::totalVal_);
126 // Test deleting the ThreadLocalPtr object
127 TEST(ThreadLocalPtr, CustomDeleter2) {
128 Widget::totalVal_ = 0;
131 std::condition_variable cv;
137 State state = State::START;
139 ThreadLocalPtr<Widget> w;
140 t = std::thread([&]() {
141 w.reset(new Widget(), Widget::customDeleter);
144 // Notify main thread that we're done
146 std::unique_lock<std::mutex> lock(mutex);
151 // Wait for main thread to allow us to exit
153 std::unique_lock<std::mutex> lock(mutex);
154 while (state != State::EXIT) {
160 // Wait for main thread to start (and set w.get()->val_)
162 std::unique_lock<std::mutex> lock(mutex);
163 while (state != State::DONE) {
168 // Thread started but hasn't exited yet
169 EXPECT_EQ(0, Widget::totalVal_);
171 // Destroy ThreadLocalPtr<Widget> (by letting it go out of scope)
174 EXPECT_EQ(1010, Widget::totalVal_);
176 // Allow thread to exit
178 std::unique_lock<std::mutex> lock(mutex);
184 EXPECT_EQ(1010, Widget::totalVal_);
187 TEST(ThreadLocal, BasicDestructor) {
188 Widget::totalVal_ = 0;
189 ThreadLocal<Widget> w;
190 std::thread([&w]() { w->val_ += 10; }).join();
191 EXPECT_EQ(10, Widget::totalVal_);
194 TEST(ThreadLocal, SimpleRepeatDestructor) {
195 Widget::totalVal_ = 0;
197 ThreadLocal<Widget> w;
201 ThreadLocal<Widget> w;
204 EXPECT_EQ(20, Widget::totalVal_);
207 TEST(ThreadLocal, InterleavedDestructors) {
208 Widget::totalVal_ = 0;
209 std::unique_ptr<ThreadLocal<Widget>> w;
211 const int wVersionMax = 2;
214 auto th = std::thread([&]() {
215 int wVersionPrev = 0;
218 std::lock_guard<std::mutex> g(lock);
219 if (wVersion > wVersionMax) {
222 if (wVersion > wVersionPrev) {
223 // We have a new version of w, so it should be initialized to zero
224 EXPECT_EQ((*w)->val_, 0);
228 std::lock_guard<std::mutex> g(lock);
229 wVersionPrev = wVersion;
234 FOR_EACH_RANGE(i, 0, wVersionMax) {
237 std::lock_guard<std::mutex> g(lock);
239 w.reset(new ThreadLocal<Widget>());
243 std::lock_guard<std::mutex> g(lock);
244 if (thIter > thIterPrev) {
250 std::lock_guard<std::mutex> g(lock);
251 wVersion = wVersionMax + 1;
254 EXPECT_EQ(wVersionMax * 10, Widget::totalVal_);
257 class SimpleThreadCachedInt {
260 ThreadLocal<int,NewTag> val_;
269 for (const auto& i : val_.accessAllThreads()) {
276 TEST(ThreadLocalPtr, AccessAllThreadsCounter) {
277 const int kNumThreads = 10;
278 SimpleThreadCachedInt stci;
279 std::atomic<bool> run(true);
280 std::atomic<int> totalAtomic(0);
281 std::vector<std::thread> threads;
282 for (int i = 0; i < kNumThreads; ++i) {
283 threads.push_back(std::thread([&,i]() {
285 totalAtomic.fetch_add(1);
286 while (run.load()) { usleep(100); }
289 while (totalAtomic.load() != kNumThreads) { usleep(100); }
290 EXPECT_EQ(kNumThreads, stci.read());
292 for (auto& t : threads) {
297 TEST(ThreadLocal, resetNull) {
299 tl.reset(new int(4));
300 EXPECT_EQ(*tl.get(), 4);
302 EXPECT_EQ(*tl.get(), 0);
303 tl.reset(new int(5));
304 EXPECT_EQ(*tl.get(), 5);
311 folly::ThreadLocal<int, Tag> tl;
315 TEST(ThreadLocal, Movable1) {
318 EXPECT_TRUE(a.tl.get() != b.tl.get());
322 EXPECT_TRUE(a.tl.get() != b.tl.get());
325 TEST(ThreadLocal, Movable2) {
326 std::map<int, Foo> map;
334 for (auto& m : map) {
335 tls.insert(m.second.tl.get());
338 // Make sure that we have 4 different instances of *tl
339 EXPECT_EQ(4, tls.size());
344 constexpr size_t kFillObjectSize = 300;
346 std::atomic<uint64_t> gDestroyed;
349 * Fill a chunk of memory with a unique-ish pattern that includes the thread id
350 * (so deleting one of these from another thread would cause a failure)
352 * Verify it explicitly and on destruction.
356 explicit FillObject(uint64_t idx) : idx_(idx) {
358 for (size_t i = 0; i < kFillObjectSize; ++i) {
365 for (size_t i = 0; i < kFillObjectSize; ++i) {
366 CHECK_EQ(v, data_[i]);
375 uint64_t val() const {
376 return (idx_ << 40) | uint64_t(pthread_self());
380 uint64_t data_[kFillObjectSize];
385 #if FOLLY_HAVE_STD_THIS_THREAD_SLEEP_FOR
386 TEST(ThreadLocal, Stress) {
387 constexpr size_t numFillObjects = 250;
388 std::array<ThreadLocalPtr<FillObject>, numFillObjects> objects;
390 constexpr size_t numThreads = 32;
391 constexpr size_t numReps = 20;
393 std::vector<std::thread> threads;
394 threads.reserve(numThreads);
396 for (size_t i = 0; i < numThreads; ++i) {
397 threads.emplace_back([&objects] {
398 for (size_t rep = 0; rep < numReps; ++rep) {
399 for (size_t i = 0; i < objects.size(); ++i) {
400 objects[i].reset(new FillObject(rep * objects.size() + i));
401 std::this_thread::sleep_for(std::chrono::microseconds(100));
403 for (size_t i = 0; i < objects.size(); ++i) {
410 for (auto& t : threads) {
414 EXPECT_EQ(numFillObjects * numThreads * numReps, gDestroyed);
418 // Yes, threads and fork don't mix
419 // (http://cppwisdom.quora.com/Why-threads-and-fork-dont-mix) but if you're
420 // stupid or desperate enough to try, we shouldn't stand in your way.
424 HoldsOne() : value_(1) { }
425 // Do an actual access to catch the buggy case where this == nullptr
426 int value() const { return value_; }
431 struct HoldsOneTag {};
433 ThreadLocal<HoldsOne, HoldsOneTag> ptr;
437 for (auto& p : ptr.accessAllThreads()) {
445 #ifdef FOLLY_HAVE_PTHREAD_ATFORK
446 TEST(ThreadLocal, Fork) {
447 EXPECT_EQ(1, ptr->value()); // ensure created
448 EXPECT_EQ(1, totalValue());
449 // Spawn a new thread
452 bool started = false;
453 std::condition_variable startedCond;
454 bool stopped = false;
455 std::condition_variable stoppedCond;
457 std::thread t([&] () {
458 EXPECT_EQ(1, ptr->value()); // ensure created
460 std::unique_lock<std::mutex> lock(mutex);
462 startedCond.notify_all();
465 std::unique_lock<std::mutex> lock(mutex);
467 stoppedCond.wait(lock);
473 std::unique_lock<std::mutex> lock(mutex);
475 startedCond.wait(lock);
479 EXPECT_EQ(2, totalValue());
484 int v = totalValue();
486 // exit successfully if v == 1 (one thread)
487 // diagnostic error code otherwise :)
493 } else if (pid > 0) {
496 EXPECT_EQ(pid, waitpid(pid, &status, 0));
497 EXPECT_TRUE(WIFEXITED(status));
498 EXPECT_EQ(0, WEXITSTATUS(status));
500 EXPECT_TRUE(false) << "fork failed";
503 EXPECT_EQ(2, totalValue());
506 std::unique_lock<std::mutex> lock(mutex);
508 stoppedCond.notify_all();
513 EXPECT_EQ(1, totalValue());
517 struct HoldsOneTag2 {};
519 TEST(ThreadLocal, Fork2) {
520 // A thread-local tag that was used in the parent from a *different* thread
521 // (but not the forking thread) would cause the child to hang in a
522 // ThreadLocalPtr's object destructor. Yeah.
523 ThreadLocal<HoldsOne, HoldsOneTag2> p;
525 // use tag in different thread
526 std::thread t([&p] { p.get(); });
532 ThreadLocal<HoldsOne, HoldsOneTag2> q;
536 } else if (pid > 0) {
538 EXPECT_EQ(pid, waitpid(pid, &status, 0));
539 EXPECT_TRUE(WIFEXITED(status));
540 EXPECT_EQ(0, WEXITSTATUS(status));
542 EXPECT_TRUE(false) << "fork failed";
546 TEST(ThreadLocal, SharedLibrary) {
547 auto exe = fs::executable_path();
548 auto lib = exe.parent_path() / "lib_thread_local_test.so";
549 auto handle = dlopen(lib.string().c_str(), RTLD_LAZY);
550 EXPECT_NE(nullptr, handle);
552 typedef void (*useA_t)();
554 useA_t useA = (useA_t) dlsym(handle, "useA");
556 const char *dlsym_error = dlerror();
557 EXPECT_EQ(nullptr, dlsym_error);
561 folly::Baton<> b11, b12, b21, b22;
563 std::thread t1([&]() {
569 std::thread t2([&]() {
587 namespace folly { namespace threadlocal_detail {
588 struct PthreadKeyUnregisterTester {
589 PthreadKeyUnregister p;
590 constexpr PthreadKeyUnregisterTester() = default;
594 TEST(ThreadLocal, UnregisterClassHasConstExprCtor) {
595 folly::threadlocal_detail::PthreadKeyUnregisterTester x;
600 // clang is unable to compile this code unless in c++14 mode.
601 #if __cplusplus >= 201402L
603 // This will fail to compile unless ThreadLocal{Ptr} has a constexpr
604 // default constructor. This ensures that ThreadLocal is safe to use in
605 // static constructors without worrying about initialization order
606 class ConstexprThreadLocalCompile {
608 ThreadLocalPtr<int> b_;
610 constexpr ConstexprThreadLocalCompile() {}
615 // Simple reference implementation using pthread_get_specific
617 class PThreadGetSpecific {
619 PThreadGetSpecific() : key_(0) {
620 pthread_key_create(&key_, OnThreadExit);
624 return static_cast<T*>(pthread_getspecific(key_));
629 pthread_setspecific(key_, t);
631 static void OnThreadExit(void* obj) {
632 delete static_cast<T*>(obj);
638 DEFINE_int32(numThreads, 8, "Number simultaneous threads for benchmarks.");
641 BENCHMARK(FB_CONCATENATE(BM_mt_, var), iters) { \
642 const int itersPerThread = iters / FLAGS_numThreads; \
643 std::vector<std::thread> threads; \
644 for (int i = 0; i < FLAGS_numThreads; ++i) { \
645 threads.push_back(std::thread([&]() { \
646 var.reset(new int(0)); \
647 for (int i = 0; i < itersPerThread; ++i) { \
652 for (auto& t : threads) { \
657 ThreadLocalPtr<int> tlp;
659 PThreadGetSpecific<int> pthread_get_specific;
660 REG(pthread_get_specific);
661 boost::thread_specific_ptr<int> boost_tsp;
663 BENCHMARK_DRAW_LINE();
665 int main(int argc, char** argv) {
666 testing::InitGoogleTest(&argc, argv);
667 gflags::ParseCommandLineFlags(&argc, &argv, true);
668 gflags::SetCommandLineOptionWithMode(
669 "bm_max_iters", "100000000", gflags::SET_FLAG_IF_DEFAULT
671 if (FLAGS_benchmark) {
672 folly::runBenchmarks();
674 return RUN_ALL_TESTS();
678 Ran with 24 threads on dual 12-core Xeon(R) X5650 @ 2.67GHz with 12-MB caches
680 Benchmark Iters Total t t/iter iter/sec
681 ------------------------------------------------------------------------------
682 * BM_mt_tlp 100000000 39.88 ms 398.8 ps 2.335 G
683 +5.91% BM_mt_pthread_get_specific 100000000 42.23 ms 422.3 ps 2.205 G
684 + 295% BM_mt_boost_tsp 100000000 157.8 ms 1.578 ns 604.5 M
685 ------------------------------------------------------------------------------