2 * Copyright 2015 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>
43 using namespace folly;
52 static void customDeleter(Widget* w, TLPDestructionMode mode) {
53 totalVal_ += (mode == TLPDestructionMode::ALL_THREADS) * 1000;
57 int Widget::totalVal_ = 0;
59 TEST(ThreadLocalPtr, BasicDestructor) {
60 Widget::totalVal_ = 0;
61 ThreadLocalPtr<Widget> w;
63 w.reset(new Widget());
66 EXPECT_EQ(10, Widget::totalVal_);
69 TEST(ThreadLocalPtr, CustomDeleter1) {
70 Widget::totalVal_ = 0;
72 ThreadLocalPtr<Widget> w;
74 w.reset(new Widget(), Widget::customDeleter);
77 EXPECT_EQ(10, Widget::totalVal_);
79 EXPECT_EQ(10, Widget::totalVal_);
82 TEST(ThreadLocalPtr, resetNull) {
83 ThreadLocalPtr<int> tl;
86 EXPECT_TRUE(static_cast<bool>(tl));
87 EXPECT_EQ(*tl.get(), 4);
92 TEST(ThreadLocalPtr, TestRelease) {
93 Widget::totalVal_ = 0;
94 ThreadLocalPtr<Widget> w;
95 std::unique_ptr<Widget> wPtr;
96 std::thread([&w, &wPtr]() {
97 w.reset(new Widget());
100 wPtr.reset(w.release());
102 EXPECT_EQ(0, Widget::totalVal_);
104 EXPECT_EQ(10, Widget::totalVal_);
107 TEST(ThreadLocalPtr, CreateOnThreadExit) {
108 Widget::totalVal_ = 0;
109 ThreadLocal<Widget> w;
110 ThreadLocalPtr<int> tl;
113 tl.reset(new int(1), [&] (int* ptr, TLPDestructionMode mode) {
115 // This test ensures Widgets allocated here are not leaked.
117 ThreadLocal<Widget> wl;
121 EXPECT_EQ(2, Widget::totalVal_);
124 // Test deleting the ThreadLocalPtr object
125 TEST(ThreadLocalPtr, CustomDeleter2) {
126 Widget::totalVal_ = 0;
129 std::condition_variable cv;
135 State state = State::START;
137 ThreadLocalPtr<Widget> w;
138 t = std::thread([&]() {
139 w.reset(new Widget(), Widget::customDeleter);
142 // Notify main thread that we're done
144 std::unique_lock<std::mutex> lock(mutex);
149 // Wait for main thread to allow us to exit
151 std::unique_lock<std::mutex> lock(mutex);
152 while (state != State::EXIT) {
158 // Wait for main thread to start (and set w.get()->val_)
160 std::unique_lock<std::mutex> lock(mutex);
161 while (state != State::DONE) {
166 // Thread started but hasn't exited yet
167 EXPECT_EQ(0, Widget::totalVal_);
169 // Destroy ThreadLocalPtr<Widget> (by letting it go out of scope)
172 EXPECT_EQ(1010, Widget::totalVal_);
174 // Allow thread to exit
176 std::unique_lock<std::mutex> lock(mutex);
182 EXPECT_EQ(1010, Widget::totalVal_);
185 TEST(ThreadLocal, BasicDestructor) {
186 Widget::totalVal_ = 0;
187 ThreadLocal<Widget> w;
188 std::thread([&w]() { w->val_ += 10; }).join();
189 EXPECT_EQ(10, Widget::totalVal_);
192 TEST(ThreadLocal, SimpleRepeatDestructor) {
193 Widget::totalVal_ = 0;
195 ThreadLocal<Widget> w;
199 ThreadLocal<Widget> w;
202 EXPECT_EQ(20, Widget::totalVal_);
205 TEST(ThreadLocal, InterleavedDestructors) {
206 Widget::totalVal_ = 0;
207 std::unique_ptr<ThreadLocal<Widget>> w;
209 const int wVersionMax = 2;
212 auto th = std::thread([&]() {
213 int wVersionPrev = 0;
216 std::lock_guard<std::mutex> g(lock);
217 if (wVersion > wVersionMax) {
220 if (wVersion > wVersionPrev) {
221 // We have a new version of w, so it should be initialized to zero
222 EXPECT_EQ((*w)->val_, 0);
226 std::lock_guard<std::mutex> g(lock);
227 wVersionPrev = wVersion;
232 FOR_EACH_RANGE(i, 0, wVersionMax) {
235 std::lock_guard<std::mutex> g(lock);
237 w.reset(new ThreadLocal<Widget>());
241 std::lock_guard<std::mutex> g(lock);
242 if (thIter > thIterPrev) {
248 std::lock_guard<std::mutex> g(lock);
249 wVersion = wVersionMax + 1;
252 EXPECT_EQ(wVersionMax * 10, Widget::totalVal_);
255 class SimpleThreadCachedInt {
258 ThreadLocal<int,NewTag> val_;
267 for (const auto& i : val_.accessAllThreads()) {
274 TEST(ThreadLocalPtr, AccessAllThreadsCounter) {
275 const int kNumThreads = 10;
276 SimpleThreadCachedInt stci;
277 std::atomic<bool> run(true);
278 std::atomic<int> totalAtomic(0);
279 std::vector<std::thread> threads;
280 for (int i = 0; i < kNumThreads; ++i) {
281 threads.push_back(std::thread([&,i]() {
283 totalAtomic.fetch_add(1);
284 while (run.load()) { usleep(100); }
287 while (totalAtomic.load() != kNumThreads) { usleep(100); }
288 EXPECT_EQ(kNumThreads, stci.read());
290 for (auto& t : threads) {
295 TEST(ThreadLocal, resetNull) {
297 tl.reset(new int(4));
298 EXPECT_EQ(*tl.get(), 4);
300 EXPECT_EQ(*tl.get(), 0);
301 tl.reset(new int(5));
302 EXPECT_EQ(*tl.get(), 5);
309 folly::ThreadLocal<int, Tag> tl;
313 TEST(ThreadLocal, Movable1) {
316 EXPECT_TRUE(a.tl.get() != b.tl.get());
320 EXPECT_TRUE(a.tl.get() != b.tl.get());
323 TEST(ThreadLocal, Movable2) {
324 std::map<int, Foo> map;
332 for (auto& m : map) {
333 tls.insert(m.second.tl.get());
336 // Make sure that we have 4 different instances of *tl
337 EXPECT_EQ(4, tls.size());
342 constexpr size_t kFillObjectSize = 300;
344 std::atomic<uint64_t> gDestroyed;
347 * Fill a chunk of memory with a unique-ish pattern that includes the thread id
348 * (so deleting one of these from another thread would cause a failure)
350 * Verify it explicitly and on destruction.
354 explicit FillObject(uint64_t idx) : idx_(idx) {
356 for (size_t i = 0; i < kFillObjectSize; ++i) {
363 for (size_t i = 0; i < kFillObjectSize; ++i) {
364 CHECK_EQ(v, data_[i]);
373 uint64_t val() const {
374 return (idx_ << 40) | uint64_t(pthread_self());
378 uint64_t data_[kFillObjectSize];
383 #if FOLLY_HAVE_STD_THIS_THREAD_SLEEP_FOR
384 TEST(ThreadLocal, Stress) {
385 constexpr size_t numFillObjects = 250;
386 std::array<ThreadLocalPtr<FillObject>, numFillObjects> objects;
388 constexpr size_t numThreads = 32;
389 constexpr size_t numReps = 20;
391 std::vector<std::thread> threads;
392 threads.reserve(numThreads);
394 for (size_t i = 0; i < numThreads; ++i) {
395 threads.emplace_back([&objects] {
396 for (size_t rep = 0; rep < numReps; ++rep) {
397 for (size_t i = 0; i < objects.size(); ++i) {
398 objects[i].reset(new FillObject(rep * objects.size() + i));
399 std::this_thread::sleep_for(std::chrono::microseconds(100));
401 for (size_t i = 0; i < objects.size(); ++i) {
408 for (auto& t : threads) {
412 EXPECT_EQ(numFillObjects * numThreads * numReps, gDestroyed);
416 // Yes, threads and fork don't mix
417 // (http://cppwisdom.quora.com/Why-threads-and-fork-dont-mix) but if you're
418 // stupid or desperate enough to try, we shouldn't stand in your way.
422 HoldsOne() : value_(1) { }
423 // Do an actual access to catch the buggy case where this == nullptr
424 int value() const { return value_; }
429 struct HoldsOneTag {};
431 ThreadLocal<HoldsOne, HoldsOneTag> ptr;
435 for (auto& p : ptr.accessAllThreads()) {
443 #ifdef FOLLY_HAVE_PTHREAD_ATFORK
444 TEST(ThreadLocal, Fork) {
445 EXPECT_EQ(1, ptr->value()); // ensure created
446 EXPECT_EQ(1, totalValue());
447 // Spawn a new thread
450 bool started = false;
451 std::condition_variable startedCond;
452 bool stopped = false;
453 std::condition_variable stoppedCond;
455 std::thread t([&] () {
456 EXPECT_EQ(1, ptr->value()); // ensure created
458 std::unique_lock<std::mutex> lock(mutex);
460 startedCond.notify_all();
463 std::unique_lock<std::mutex> lock(mutex);
465 stoppedCond.wait(lock);
471 std::unique_lock<std::mutex> lock(mutex);
473 startedCond.wait(lock);
477 EXPECT_EQ(2, totalValue());
482 int v = totalValue();
484 // exit successfully if v == 1 (one thread)
485 // diagnostic error code otherwise :)
491 } else if (pid > 0) {
494 EXPECT_EQ(pid, waitpid(pid, &status, 0));
495 EXPECT_TRUE(WIFEXITED(status));
496 EXPECT_EQ(0, WEXITSTATUS(status));
498 EXPECT_TRUE(false) << "fork failed";
501 EXPECT_EQ(2, totalValue());
504 std::unique_lock<std::mutex> lock(mutex);
506 stoppedCond.notify_all();
511 EXPECT_EQ(1, totalValue());
515 struct HoldsOneTag2 {};
517 TEST(ThreadLocal, Fork2) {
518 // A thread-local tag that was used in the parent from a *different* thread
519 // (but not the forking thread) would cause the child to hang in a
520 // ThreadLocalPtr's object destructor. Yeah.
521 ThreadLocal<HoldsOne, HoldsOneTag2> p;
523 // use tag in different thread
524 std::thread t([&p] { p.get(); });
530 ThreadLocal<HoldsOne, HoldsOneTag2> q;
534 } else if (pid > 0) {
536 EXPECT_EQ(pid, waitpid(pid, &status, 0));
537 EXPECT_TRUE(WIFEXITED(status));
538 EXPECT_EQ(0, WEXITSTATUS(status));
540 EXPECT_TRUE(false) << "fork failed";
544 TEST(ThreadLocal, SharedLibrary)
546 auto handle = dlopen("./_bin/folly/test/lib_thread_local_test.so",
548 EXPECT_NE(nullptr, handle);
550 typedef void (*useA_t)();
552 useA_t useA = (useA_t) dlsym(handle, "useA");
554 const char *dlsym_error = dlerror();
555 EXPECT_EQ(nullptr, dlsym_error);
559 folly::Baton<> b11, b12, b21, b22;
561 std::thread t1([&]() {
567 std::thread t2([&]() {
585 // clang is unable to compile this code unless in c++14 mode.
586 #if __cplusplus >= 201402L
588 // This will fail to compile unless ThreadLocal{Ptr} has a constexpr
589 // default constructor. This ensures that ThreadLocal is safe to use in
590 // static constructors without worrying about initialization order
591 class ConstexprThreadLocalCompile {
593 ThreadLocalPtr<int> b_;
595 constexpr ConstexprThreadLocalCompile() {}
600 // Simple reference implementation using pthread_get_specific
602 class PThreadGetSpecific {
604 PThreadGetSpecific() : key_(0) {
605 pthread_key_create(&key_, OnThreadExit);
609 return static_cast<T*>(pthread_getspecific(key_));
614 pthread_setspecific(key_, t);
616 static void OnThreadExit(void* obj) {
617 delete static_cast<T*>(obj);
623 DEFINE_int32(numThreads, 8, "Number simultaneous threads for benchmarks.");
626 BENCHMARK(FB_CONCATENATE(BM_mt_, var), iters) { \
627 const int itersPerThread = iters / FLAGS_numThreads; \
628 std::vector<std::thread> threads; \
629 for (int i = 0; i < FLAGS_numThreads; ++i) { \
630 threads.push_back(std::thread([&]() { \
631 var.reset(new int(0)); \
632 for (int i = 0; i < itersPerThread; ++i) { \
637 for (auto& t : threads) { \
642 ThreadLocalPtr<int> tlp;
644 PThreadGetSpecific<int> pthread_get_specific;
645 REG(pthread_get_specific);
646 boost::thread_specific_ptr<int> boost_tsp;
648 BENCHMARK_DRAW_LINE();
650 int main(int argc, char** argv) {
651 testing::InitGoogleTest(&argc, argv);
652 gflags::ParseCommandLineFlags(&argc, &argv, true);
653 gflags::SetCommandLineOptionWithMode(
654 "bm_max_iters", "100000000", gflags::SET_FLAG_IF_DEFAULT
656 if (FLAGS_benchmark) {
657 folly::runBenchmarks();
659 return RUN_ALL_TESTS();
663 Ran with 24 threads on dual 12-core Xeon(R) X5650 @ 2.67GHz with 12-MB caches
665 Benchmark Iters Total t t/iter iter/sec
666 ------------------------------------------------------------------------------
667 * BM_mt_tlp 100000000 39.88 ms 398.8 ps 2.335 G
668 +5.91% BM_mt_pthread_get_specific 100000000 42.23 ms 422.3 ps 2.205 G
669 + 295% BM_mt_boost_tsp 100000000 157.8 ms 1.578 ns 604.5 M
670 ------------------------------------------------------------------------------