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>
19 #include <sys/types.h>
26 #include <condition_variable>
32 #include <unordered_map>
34 #include <boost/thread/tss.hpp>
35 #include <gflags/gflags.h>
36 #include <glog/logging.h>
37 #include <gtest/gtest.h>
39 #include <folly/Benchmark.h>
41 using namespace folly;
50 static void customDeleter(Widget* w, TLPDestructionMode mode) {
51 totalVal_ += (mode == TLPDestructionMode::ALL_THREADS) * 1000;
55 int Widget::totalVal_ = 0;
57 TEST(ThreadLocalPtr, BasicDestructor) {
58 Widget::totalVal_ = 0;
59 ThreadLocalPtr<Widget> w;
61 w.reset(new Widget());
64 EXPECT_EQ(10, Widget::totalVal_);
67 TEST(ThreadLocalPtr, CustomDeleter1) {
68 Widget::totalVal_ = 0;
70 ThreadLocalPtr<Widget> w;
72 w.reset(new Widget(), Widget::customDeleter);
75 EXPECT_EQ(10, Widget::totalVal_);
77 EXPECT_EQ(10, Widget::totalVal_);
80 TEST(ThreadLocalPtr, resetNull) {
81 ThreadLocalPtr<int> tl;
84 EXPECT_TRUE(static_cast<bool>(tl));
85 EXPECT_EQ(*tl.get(), 4);
90 TEST(ThreadLocalPtr, TestRelease) {
91 Widget::totalVal_ = 0;
92 ThreadLocalPtr<Widget> w;
93 std::unique_ptr<Widget> wPtr;
94 std::thread([&w, &wPtr]() {
95 w.reset(new Widget());
98 wPtr.reset(w.release());
100 EXPECT_EQ(0, Widget::totalVal_);
102 EXPECT_EQ(10, Widget::totalVal_);
105 TEST(ThreadLocalPtr, CreateOnThreadExit) {
106 Widget::totalVal_ = 0;
107 ThreadLocal<Widget> w;
108 ThreadLocalPtr<int> tl;
111 tl.reset(new int(1), [&] (int* ptr, TLPDestructionMode mode) {
113 // This test ensures Widgets allocated here are not leaked.
115 ThreadLocal<Widget> wl;
119 EXPECT_EQ(2, Widget::totalVal_);
122 // Test deleting the ThreadLocalPtr object
123 TEST(ThreadLocalPtr, CustomDeleter2) {
124 Widget::totalVal_ = 0;
127 std::condition_variable cv;
133 State state = State::START;
135 ThreadLocalPtr<Widget> w;
136 t = std::thread([&]() {
137 w.reset(new Widget(), Widget::customDeleter);
140 // Notify main thread that we're done
142 std::unique_lock<std::mutex> lock(mutex);
147 // Wait for main thread to allow us to exit
149 std::unique_lock<std::mutex> lock(mutex);
150 while (state != State::EXIT) {
156 // Wait for main thread to start (and set w.get()->val_)
158 std::unique_lock<std::mutex> lock(mutex);
159 while (state != State::DONE) {
164 // Thread started but hasn't exited yet
165 EXPECT_EQ(0, Widget::totalVal_);
167 // Destroy ThreadLocalPtr<Widget> (by letting it go out of scope)
170 EXPECT_EQ(1010, Widget::totalVal_);
172 // Allow thread to exit
174 std::unique_lock<std::mutex> lock(mutex);
180 EXPECT_EQ(1010, Widget::totalVal_);
183 TEST(ThreadLocal, BasicDestructor) {
184 Widget::totalVal_ = 0;
185 ThreadLocal<Widget> w;
186 std::thread([&w]() { w->val_ += 10; }).join();
187 EXPECT_EQ(10, Widget::totalVal_);
190 TEST(ThreadLocal, SimpleRepeatDestructor) {
191 Widget::totalVal_ = 0;
193 ThreadLocal<Widget> w;
197 ThreadLocal<Widget> w;
200 EXPECT_EQ(20, Widget::totalVal_);
203 TEST(ThreadLocal, InterleavedDestructors) {
204 Widget::totalVal_ = 0;
205 std::unique_ptr<ThreadLocal<Widget>> w;
207 const int wVersionMax = 2;
210 auto th = std::thread([&]() {
211 int wVersionPrev = 0;
214 std::lock_guard<std::mutex> g(lock);
215 if (wVersion > wVersionMax) {
218 if (wVersion > wVersionPrev) {
219 // We have a new version of w, so it should be initialized to zero
220 EXPECT_EQ((*w)->val_, 0);
224 std::lock_guard<std::mutex> g(lock);
225 wVersionPrev = wVersion;
230 FOR_EACH_RANGE(i, 0, wVersionMax) {
233 std::lock_guard<std::mutex> g(lock);
235 w.reset(new ThreadLocal<Widget>());
239 std::lock_guard<std::mutex> g(lock);
240 if (thIter > thIterPrev) {
246 std::lock_guard<std::mutex> g(lock);
247 wVersion = wVersionMax + 1;
250 EXPECT_EQ(wVersionMax * 10, Widget::totalVal_);
253 class SimpleThreadCachedInt {
256 ThreadLocal<int,NewTag> val_;
265 for (const auto& i : val_.accessAllThreads()) {
272 TEST(ThreadLocalPtr, AccessAllThreadsCounter) {
273 const int kNumThreads = 10;
274 SimpleThreadCachedInt stci;
275 std::atomic<bool> run(true);
276 std::atomic<int> totalAtomic(0);
277 std::vector<std::thread> threads;
278 for (int i = 0; i < kNumThreads; ++i) {
279 threads.push_back(std::thread([&,i]() {
281 totalAtomic.fetch_add(1);
282 while (run.load()) { usleep(100); }
285 while (totalAtomic.load() != kNumThreads) { usleep(100); }
286 EXPECT_EQ(kNumThreads, stci.read());
288 for (auto& t : threads) {
293 TEST(ThreadLocal, resetNull) {
295 tl.reset(new int(4));
296 EXPECT_EQ(*tl.get(), 4);
298 EXPECT_EQ(*tl.get(), 0);
299 tl.reset(new int(5));
300 EXPECT_EQ(*tl.get(), 5);
307 folly::ThreadLocal<int, Tag> tl;
311 TEST(ThreadLocal, Movable1) {
314 EXPECT_TRUE(a.tl.get() != b.tl.get());
318 EXPECT_TRUE(a.tl.get() != b.tl.get());
321 TEST(ThreadLocal, Movable2) {
322 std::map<int, Foo> map;
330 for (auto& m : map) {
331 tls.insert(m.second.tl.get());
334 // Make sure that we have 4 different instances of *tl
335 EXPECT_EQ(4, tls.size());
340 constexpr size_t kFillObjectSize = 300;
342 std::atomic<uint64_t> gDestroyed;
345 * Fill a chunk of memory with a unique-ish pattern that includes the thread id
346 * (so deleting one of these from another thread would cause a failure)
348 * Verify it explicitly and on destruction.
352 explicit FillObject(uint64_t idx) : idx_(idx) {
354 for (size_t i = 0; i < kFillObjectSize; ++i) {
361 for (size_t i = 0; i < kFillObjectSize; ++i) {
362 CHECK_EQ(v, data_[i]);
371 uint64_t val() const {
372 return (idx_ << 40) | uint64_t(pthread_self());
376 uint64_t data_[kFillObjectSize];
381 #if FOLLY_HAVE_STD_THIS_THREAD_SLEEP_FOR
382 TEST(ThreadLocal, Stress) {
383 constexpr size_t numFillObjects = 250;
384 std::array<ThreadLocalPtr<FillObject>, numFillObjects> objects;
386 constexpr size_t numThreads = 32;
387 constexpr size_t numReps = 20;
389 std::vector<std::thread> threads;
390 threads.reserve(numThreads);
392 for (size_t i = 0; i < numThreads; ++i) {
393 threads.emplace_back([&objects] {
394 for (size_t rep = 0; rep < numReps; ++rep) {
395 for (size_t i = 0; i < objects.size(); ++i) {
396 objects[i].reset(new FillObject(rep * objects.size() + i));
397 std::this_thread::sleep_for(std::chrono::microseconds(100));
399 for (size_t i = 0; i < objects.size(); ++i) {
406 for (auto& t : threads) {
410 EXPECT_EQ(numFillObjects * numThreads * numReps, gDestroyed);
414 // Yes, threads and fork don't mix
415 // (http://cppwisdom.quora.com/Why-threads-and-fork-dont-mix) but if you're
416 // stupid or desperate enough to try, we shouldn't stand in your way.
420 HoldsOne() : value_(1) { }
421 // Do an actual access to catch the buggy case where this == nullptr
422 int value() const { return value_; }
427 struct HoldsOneTag {};
429 ThreadLocal<HoldsOne, HoldsOneTag> ptr;
433 for (auto& p : ptr.accessAllThreads()) {
441 #ifdef FOLLY_HAVE_PTHREAD_ATFORK
442 TEST(ThreadLocal, Fork) {
443 EXPECT_EQ(1, ptr->value()); // ensure created
444 EXPECT_EQ(1, totalValue());
445 // Spawn a new thread
448 bool started = false;
449 std::condition_variable startedCond;
450 bool stopped = false;
451 std::condition_variable stoppedCond;
453 std::thread t([&] () {
454 EXPECT_EQ(1, ptr->value()); // ensure created
456 std::unique_lock<std::mutex> lock(mutex);
458 startedCond.notify_all();
461 std::unique_lock<std::mutex> lock(mutex);
463 stoppedCond.wait(lock);
469 std::unique_lock<std::mutex> lock(mutex);
471 startedCond.wait(lock);
475 EXPECT_EQ(2, totalValue());
480 int v = totalValue();
482 // exit successfully if v == 1 (one thread)
483 // diagnostic error code otherwise :)
489 } else if (pid > 0) {
492 EXPECT_EQ(pid, waitpid(pid, &status, 0));
493 EXPECT_TRUE(WIFEXITED(status));
494 EXPECT_EQ(0, WEXITSTATUS(status));
496 EXPECT_TRUE(false) << "fork failed";
499 EXPECT_EQ(2, totalValue());
502 std::unique_lock<std::mutex> lock(mutex);
504 stoppedCond.notify_all();
509 EXPECT_EQ(1, totalValue());
513 struct HoldsOneTag2 {};
515 TEST(ThreadLocal, Fork2) {
516 // A thread-local tag that was used in the parent from a *different* thread
517 // (but not the forking thread) would cause the child to hang in a
518 // ThreadLocalPtr's object destructor. Yeah.
519 ThreadLocal<HoldsOne, HoldsOneTag2> p;
521 // use tag in different thread
522 std::thread t([&p] { p.get(); });
528 ThreadLocal<HoldsOne, HoldsOneTag2> q;
532 } else if (pid > 0) {
534 EXPECT_EQ(pid, waitpid(pid, &status, 0));
535 EXPECT_TRUE(WIFEXITED(status));
536 EXPECT_EQ(0, WEXITSTATUS(status));
538 EXPECT_TRUE(false) << "fork failed";
542 // clang is unable to compile this code unless in c++14 mode.
543 #if __cplusplus >= 201402L
545 // This will fail to compile unless ThreadLocal{Ptr} has a constexpr
546 // default constructor. This ensures that ThreadLocal is safe to use in
547 // static constructors without worrying about initialization order
548 class ConstexprThreadLocalCompile {
550 ThreadLocalPtr<int> b_;
552 constexpr ConstexprThreadLocalCompile() {}
557 // Simple reference implementation using pthread_get_specific
559 class PThreadGetSpecific {
561 PThreadGetSpecific() : key_(0) {
562 pthread_key_create(&key_, OnThreadExit);
566 return static_cast<T*>(pthread_getspecific(key_));
571 pthread_setspecific(key_, t);
573 static void OnThreadExit(void* obj) {
574 delete static_cast<T*>(obj);
580 DEFINE_int32(numThreads, 8, "Number simultaneous threads for benchmarks.");
583 BENCHMARK(FB_CONCATENATE(BM_mt_, var), iters) { \
584 const int itersPerThread = iters / FLAGS_numThreads; \
585 std::vector<std::thread> threads; \
586 for (int i = 0; i < FLAGS_numThreads; ++i) { \
587 threads.push_back(std::thread([&]() { \
588 var.reset(new int(0)); \
589 for (int i = 0; i < itersPerThread; ++i) { \
594 for (auto& t : threads) { \
599 ThreadLocalPtr<int> tlp;
601 PThreadGetSpecific<int> pthread_get_specific;
602 REG(pthread_get_specific);
603 boost::thread_specific_ptr<int> boost_tsp;
605 BENCHMARK_DRAW_LINE();
607 int main(int argc, char** argv) {
608 testing::InitGoogleTest(&argc, argv);
609 gflags::ParseCommandLineFlags(&argc, &argv, true);
610 gflags::SetCommandLineOptionWithMode(
611 "bm_max_iters", "100000000", gflags::SET_FLAG_IF_DEFAULT
613 if (FLAGS_benchmark) {
614 folly::runBenchmarks();
616 return RUN_ALL_TESTS();
620 Ran with 24 threads on dual 12-core Xeon(R) X5650 @ 2.67GHz with 12-MB caches
622 Benchmark Iters Total t t/iter iter/sec
623 ------------------------------------------------------------------------------
624 * BM_mt_tlp 100000000 39.88 ms 398.8 ps 2.335 G
625 +5.91% BM_mt_pthread_get_specific 100000000 42.23 ms 422.3 ps 2.205 G
626 + 295% BM_mt_boost_tsp 100000000 157.8 ms 1.578 ns 604.5 M
627 ------------------------------------------------------------------------------