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>
31 #include <unordered_map>
33 #include <boost/thread/tss.hpp>
34 #include <gflags/gflags.h>
35 #include <glog/logging.h>
36 #include <gtest/gtest.h>
38 #include <folly/Benchmark.h>
40 using namespace folly;
49 static void customDeleter(Widget* w, TLPDestructionMode mode) {
50 totalVal_ += (mode == TLPDestructionMode::ALL_THREADS) * 1000;
54 int Widget::totalVal_ = 0;
56 TEST(ThreadLocalPtr, BasicDestructor) {
57 Widget::totalVal_ = 0;
58 ThreadLocalPtr<Widget> w;
60 w.reset(new Widget());
63 EXPECT_EQ(10, Widget::totalVal_);
66 TEST(ThreadLocalPtr, CustomDeleter1) {
67 Widget::totalVal_ = 0;
69 ThreadLocalPtr<Widget> w;
71 w.reset(new Widget(), Widget::customDeleter);
74 EXPECT_EQ(10, Widget::totalVal_);
76 EXPECT_EQ(10, Widget::totalVal_);
79 TEST(ThreadLocalPtr, resetNull) {
80 ThreadLocalPtr<int> tl;
83 EXPECT_TRUE(static_cast<bool>(tl));
84 EXPECT_EQ(*tl.get(), 4);
89 TEST(ThreadLocalPtr, TestRelease) {
90 Widget::totalVal_ = 0;
91 ThreadLocalPtr<Widget> w;
92 std::unique_ptr<Widget> wPtr;
93 std::thread([&w, &wPtr]() {
94 w.reset(new Widget());
97 wPtr.reset(w.release());
99 EXPECT_EQ(0, Widget::totalVal_);
101 EXPECT_EQ(10, Widget::totalVal_);
104 TEST(ThreadLocalPtr, CreateOnThreadExit) {
105 Widget::totalVal_ = 0;
106 ThreadLocal<Widget> w;
107 ThreadLocalPtr<int> tl;
110 tl.reset(new int(1), [&] (int* ptr, TLPDestructionMode mode) {
112 // This test ensures Widgets allocated here are not leaked.
114 ThreadLocal<Widget> wl;
118 EXPECT_EQ(2, Widget::totalVal_);
121 // Test deleting the ThreadLocalPtr object
122 TEST(ThreadLocalPtr, CustomDeleter2) {
123 Widget::totalVal_ = 0;
126 std::condition_variable cv;
132 State state = State::START;
134 ThreadLocalPtr<Widget> w;
135 t = std::thread([&]() {
136 w.reset(new Widget(), Widget::customDeleter);
139 // Notify main thread that we're done
141 std::unique_lock<std::mutex> lock(mutex);
146 // Wait for main thread to allow us to exit
148 std::unique_lock<std::mutex> lock(mutex);
149 while (state != State::EXIT) {
155 // Wait for main thread to start (and set w.get()->val_)
157 std::unique_lock<std::mutex> lock(mutex);
158 while (state != State::DONE) {
163 // Thread started but hasn't exited yet
164 EXPECT_EQ(0, Widget::totalVal_);
166 // Destroy ThreadLocalPtr<Widget> (by letting it go out of scope)
169 EXPECT_EQ(1010, Widget::totalVal_);
171 // Allow thread to exit
173 std::unique_lock<std::mutex> lock(mutex);
179 EXPECT_EQ(1010, Widget::totalVal_);
182 TEST(ThreadLocal, BasicDestructor) {
183 Widget::totalVal_ = 0;
184 ThreadLocal<Widget> w;
185 std::thread([&w]() { w->val_ += 10; }).join();
186 EXPECT_EQ(10, Widget::totalVal_);
189 TEST(ThreadLocal, SimpleRepeatDestructor) {
190 Widget::totalVal_ = 0;
192 ThreadLocal<Widget> w;
196 ThreadLocal<Widget> w;
199 EXPECT_EQ(20, Widget::totalVal_);
202 TEST(ThreadLocal, InterleavedDestructors) {
203 Widget::totalVal_ = 0;
204 std::unique_ptr<ThreadLocal<Widget>> w;
206 const int wVersionMax = 2;
209 auto th = std::thread([&]() {
210 int wVersionPrev = 0;
213 std::lock_guard<std::mutex> g(lock);
214 if (wVersion > wVersionMax) {
217 if (wVersion > wVersionPrev) {
218 // We have a new version of w, so it should be initialized to zero
219 EXPECT_EQ((*w)->val_, 0);
223 std::lock_guard<std::mutex> g(lock);
224 wVersionPrev = wVersion;
229 FOR_EACH_RANGE(i, 0, wVersionMax) {
232 std::lock_guard<std::mutex> g(lock);
234 w.reset(new ThreadLocal<Widget>());
238 std::lock_guard<std::mutex> g(lock);
239 if (thIter > thIterPrev) {
245 std::lock_guard<std::mutex> g(lock);
246 wVersion = wVersionMax + 1;
249 EXPECT_EQ(wVersionMax * 10, Widget::totalVal_);
252 class SimpleThreadCachedInt {
255 ThreadLocal<int,NewTag> val_;
264 for (const auto& i : val_.accessAllThreads()) {
271 TEST(ThreadLocalPtr, AccessAllThreadsCounter) {
272 const int kNumThreads = 10;
273 SimpleThreadCachedInt stci;
274 std::atomic<bool> run(true);
275 std::atomic<int> totalAtomic(0);
276 std::vector<std::thread> threads;
277 for (int i = 0; i < kNumThreads; ++i) {
278 threads.push_back(std::thread([&,i]() {
280 totalAtomic.fetch_add(1);
281 while (run.load()) { usleep(100); }
284 while (totalAtomic.load() != kNumThreads) { usleep(100); }
285 EXPECT_EQ(kNumThreads, stci.read());
287 for (auto& t : threads) {
292 TEST(ThreadLocal, resetNull) {
294 tl.reset(new int(4));
295 EXPECT_EQ(*tl.get(), 4);
297 EXPECT_EQ(*tl.get(), 0);
298 tl.reset(new int(5));
299 EXPECT_EQ(*tl.get(), 5);
306 folly::ThreadLocal<int, Tag> tl;
310 TEST(ThreadLocal, Movable1) {
313 EXPECT_TRUE(a.tl.get() != b.tl.get());
317 EXPECT_TRUE(a.tl.get() != b.tl.get());
320 TEST(ThreadLocal, Movable2) {
321 std::map<int, Foo> map;
329 for (auto& m : map) {
330 tls.insert(m.second.tl.get());
333 // Make sure that we have 4 different instances of *tl
334 EXPECT_EQ(4, tls.size());
339 constexpr size_t kFillObjectSize = 300;
341 std::atomic<uint64_t> gDestroyed;
344 * Fill a chunk of memory with a unique-ish pattern that includes the thread id
345 * (so deleting one of these from another thread would cause a failure)
347 * Verify it explicitly and on destruction.
351 explicit FillObject(uint64_t idx) : idx_(idx) {
353 for (size_t i = 0; i < kFillObjectSize; ++i) {
360 for (size_t i = 0; i < kFillObjectSize; ++i) {
361 CHECK_EQ(v, data_[i]);
370 uint64_t val() const {
371 return (idx_ << 40) | uint64_t(pthread_self());
375 uint64_t data_[kFillObjectSize];
380 #if FOLLY_HAVE_STD_THIS_THREAD_SLEEP_FOR
381 TEST(ThreadLocal, Stress) {
382 constexpr size_t numFillObjects = 250;
383 std::array<ThreadLocalPtr<FillObject>, numFillObjects> objects;
385 constexpr size_t numThreads = 32;
386 constexpr size_t numReps = 20;
388 std::vector<std::thread> threads;
389 threads.reserve(numThreads);
391 for (size_t i = 0; i < numThreads; ++i) {
392 threads.emplace_back([&objects] {
393 for (size_t rep = 0; rep < numReps; ++rep) {
394 for (size_t i = 0; i < objects.size(); ++i) {
395 objects[i].reset(new FillObject(rep * objects.size() + i));
396 std::this_thread::sleep_for(std::chrono::microseconds(100));
398 for (size_t i = 0; i < objects.size(); ++i) {
405 for (auto& t : threads) {
409 EXPECT_EQ(numFillObjects * numThreads * numReps, gDestroyed);
413 // Yes, threads and fork don't mix
414 // (http://cppwisdom.quora.com/Why-threads-and-fork-dont-mix) but if you're
415 // stupid or desperate enough to try, we shouldn't stand in your way.
419 HoldsOne() : value_(1) { }
420 // Do an actual access to catch the buggy case where this == nullptr
421 int value() const { return value_; }
426 struct HoldsOneTag {};
428 ThreadLocal<HoldsOne, HoldsOneTag> ptr;
432 for (auto& p : ptr.accessAllThreads()) {
440 #ifdef FOLLY_HAVE_PTHREAD_ATFORK
441 TEST(ThreadLocal, Fork) {
442 EXPECT_EQ(1, ptr->value()); // ensure created
443 EXPECT_EQ(1, totalValue());
444 // Spawn a new thread
447 bool started = false;
448 std::condition_variable startedCond;
449 bool stopped = false;
450 std::condition_variable stoppedCond;
452 std::thread t([&] () {
453 EXPECT_EQ(1, ptr->value()); // ensure created
455 std::unique_lock<std::mutex> lock(mutex);
457 startedCond.notify_all();
460 std::unique_lock<std::mutex> lock(mutex);
462 stoppedCond.wait(lock);
468 std::unique_lock<std::mutex> lock(mutex);
470 startedCond.wait(lock);
474 EXPECT_EQ(2, totalValue());
479 int v = totalValue();
481 // exit successfully if v == 1 (one thread)
482 // diagnostic error code otherwise :)
488 } else if (pid > 0) {
491 EXPECT_EQ(pid, waitpid(pid, &status, 0));
492 EXPECT_TRUE(WIFEXITED(status));
493 EXPECT_EQ(0, WEXITSTATUS(status));
495 EXPECT_TRUE(false) << "fork failed";
498 EXPECT_EQ(2, totalValue());
501 std::unique_lock<std::mutex> lock(mutex);
503 stoppedCond.notify_all();
508 EXPECT_EQ(1, totalValue());
512 struct HoldsOneTag2 {};
514 TEST(ThreadLocal, Fork2) {
515 // A thread-local tag that was used in the parent from a *different* thread
516 // (but not the forking thread) would cause the child to hang in a
517 // ThreadLocalPtr's object destructor. Yeah.
518 ThreadLocal<HoldsOne, HoldsOneTag2> p;
520 // use tag in different thread
521 std::thread t([&p] { p.get(); });
527 ThreadLocal<HoldsOne, HoldsOneTag2> q;
531 } else if (pid > 0) {
533 EXPECT_EQ(pid, waitpid(pid, &status, 0));
534 EXPECT_TRUE(WIFEXITED(status));
535 EXPECT_EQ(0, WEXITSTATUS(status));
537 EXPECT_TRUE(false) << "fork failed";
541 // clang is unable to compile this code unless in c++14 mode.
542 #if __cplusplus >= 201402L
544 // This will fail to compile unless ThreadLocal{Ptr} has a constexpr
545 // default constructor. This ensures that ThreadLocal is safe to use in
546 // static constructors without worrying about initialization order
547 class ConstexprThreadLocalCompile {
549 ThreadLocalPtr<int> b_;
551 constexpr ConstexprThreadLocalCompile() {}
556 // Simple reference implementation using pthread_get_specific
558 class PThreadGetSpecific {
560 PThreadGetSpecific() : key_(0) {
561 pthread_key_create(&key_, OnThreadExit);
565 return static_cast<T*>(pthread_getspecific(key_));
570 pthread_setspecific(key_, t);
572 static void OnThreadExit(void* obj) {
573 delete static_cast<T*>(obj);
579 DEFINE_int32(numThreads, 8, "Number simultaneous threads for benchmarks.");
582 BENCHMARK(FB_CONCATENATE(BM_mt_, var), iters) { \
583 const int itersPerThread = iters / FLAGS_numThreads; \
584 std::vector<std::thread> threads; \
585 for (int i = 0; i < FLAGS_numThreads; ++i) { \
586 threads.push_back(std::thread([&]() { \
587 var.reset(new int(0)); \
588 for (int i = 0; i < itersPerThread; ++i) { \
593 for (auto& t : threads) { \
598 ThreadLocalPtr<int> tlp;
600 PThreadGetSpecific<int> pthread_get_specific;
601 REG(pthread_get_specific);
602 boost::thread_specific_ptr<int> boost_tsp;
604 BENCHMARK_DRAW_LINE();
606 int main(int argc, char** argv) {
607 testing::InitGoogleTest(&argc, argv);
608 gflags::ParseCommandLineFlags(&argc, &argv, true);
609 gflags::SetCommandLineOptionWithMode(
610 "bm_max_iters", "100000000", gflags::SET_FLAG_IF_DEFAULT
612 if (FLAGS_benchmark) {
613 folly::runBenchmarks();
615 return RUN_ALL_TESTS();
619 Ran with 24 threads on dual 12-core Xeon(R) X5650 @ 2.67GHz with 12-MB caches
621 Benchmark Iters Total t t/iter iter/sec
622 ------------------------------------------------------------------------------
623 * BM_mt_tlp 100000000 39.88 ms 398.8 ps 2.335 G
624 +5.91% BM_mt_pthread_get_specific 100000000 42.23 ms 422.3 ps 2.205 G
625 + 295% BM_mt_boost_tsp 100000000 157.8 ms 1.578 ns 604.5 M
626 ------------------------------------------------------------------------------