2 * Copyright 2014 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 deleting the ThreadLocalPtr object
105 TEST(ThreadLocalPtr, CustomDeleter2) {
106 Widget::totalVal_ = 0;
109 std::condition_variable cv;
115 State state = State::START;
117 ThreadLocalPtr<Widget> w;
118 t = std::thread([&]() {
119 w.reset(new Widget(), Widget::customDeleter);
122 // Notify main thread that we're done
124 std::unique_lock<std::mutex> lock(mutex);
129 // Wait for main thread to allow us to exit
131 std::unique_lock<std::mutex> lock(mutex);
132 while (state != State::EXIT) {
138 // Wait for main thread to start (and set w.get()->val_)
140 std::unique_lock<std::mutex> lock(mutex);
141 while (state != State::DONE) {
146 // Thread started but hasn't exited yet
147 EXPECT_EQ(0, Widget::totalVal_);
149 // Destroy ThreadLocalPtr<Widget> (by letting it go out of scope)
152 EXPECT_EQ(1010, Widget::totalVal_);
154 // Allow thread to exit
156 std::unique_lock<std::mutex> lock(mutex);
162 EXPECT_EQ(1010, Widget::totalVal_);
165 TEST(ThreadLocal, BasicDestructor) {
166 Widget::totalVal_ = 0;
167 ThreadLocal<Widget> w;
168 std::thread([&w]() { w->val_ += 10; }).join();
169 EXPECT_EQ(10, Widget::totalVal_);
172 TEST(ThreadLocal, SimpleRepeatDestructor) {
173 Widget::totalVal_ = 0;
175 ThreadLocal<Widget> w;
179 ThreadLocal<Widget> w;
182 EXPECT_EQ(20, Widget::totalVal_);
185 TEST(ThreadLocal, InterleavedDestructors) {
186 Widget::totalVal_ = 0;
187 ThreadLocal<Widget>* w = nullptr;
189 const int wVersionMax = 2;
192 auto th = std::thread([&]() {
193 int wVersionPrev = 0;
196 std::lock_guard<std::mutex> g(lock);
197 if (wVersion > wVersionMax) {
200 if (wVersion > wVersionPrev) {
201 // We have a new version of w, so it should be initialized to zero
202 EXPECT_EQ((*w)->val_, 0);
206 std::lock_guard<std::mutex> g(lock);
207 wVersionPrev = wVersion;
212 FOR_EACH_RANGE(i, 0, wVersionMax) {
215 std::lock_guard<std::mutex> g(lock);
218 w = new ThreadLocal<Widget>();
222 std::lock_guard<std::mutex> g(lock);
223 if (thIter > thIterPrev) {
229 std::lock_guard<std::mutex> g(lock);
230 wVersion = wVersionMax + 1;
233 EXPECT_EQ(wVersionMax * 10, Widget::totalVal_);
236 class SimpleThreadCachedInt {
239 ThreadLocal<int,NewTag> val_;
248 for (const auto& i : val_.accessAllThreads()) {
255 TEST(ThreadLocalPtr, AccessAllThreadsCounter) {
256 const int kNumThreads = 10;
257 SimpleThreadCachedInt stci;
258 std::atomic<bool> run(true);
259 std::atomic<int> totalAtomic(0);
260 std::vector<std::thread> threads;
261 for (int i = 0; i < kNumThreads; ++i) {
262 threads.push_back(std::thread([&,i]() {
264 totalAtomic.fetch_add(1);
265 while (run.load()) { usleep(100); }
268 while (totalAtomic.load() != kNumThreads) { usleep(100); }
269 EXPECT_EQ(kNumThreads, stci.read());
271 for (auto& t : threads) {
276 TEST(ThreadLocal, resetNull) {
278 tl.reset(new int(4));
279 EXPECT_EQ(*tl.get(), 4);
281 EXPECT_EQ(*tl.get(), 0);
282 tl.reset(new int(5));
283 EXPECT_EQ(*tl.get(), 5);
290 folly::ThreadLocal<int, Tag> tl;
294 TEST(ThreadLocal, Movable1) {
297 EXPECT_TRUE(a.tl.get() != b.tl.get());
301 EXPECT_TRUE(a.tl.get() != b.tl.get());
304 TEST(ThreadLocal, Movable2) {
305 std::map<int, Foo> map;
313 for (auto& m : map) {
314 tls.insert(m.second.tl.get());
317 // Make sure that we have 4 different instances of *tl
318 EXPECT_EQ(4, tls.size());
323 constexpr size_t kFillObjectSize = 300;
325 std::atomic<uint64_t> gDestroyed;
328 * Fill a chunk of memory with a unique-ish pattern that includes the thread id
329 * (so deleting one of these from another thread would cause a failure)
331 * Verify it explicitly and on destruction.
335 explicit FillObject(uint64_t idx) : idx_(idx) {
337 for (size_t i = 0; i < kFillObjectSize; ++i) {
344 for (size_t i = 0; i < kFillObjectSize; ++i) {
345 CHECK_EQ(v, data_[i]);
354 uint64_t val() const {
355 return (idx_ << 40) | uint64_t(pthread_self());
359 uint64_t data_[kFillObjectSize];
364 #if FOLLY_HAVE_STD__THIS_THREAD__SLEEP_FOR
365 TEST(ThreadLocal, Stress) {
366 constexpr size_t numFillObjects = 250;
367 std::array<ThreadLocalPtr<FillObject>, numFillObjects> objects;
369 constexpr size_t numThreads = 32;
370 constexpr size_t numReps = 20;
372 std::vector<std::thread> threads;
373 threads.reserve(numThreads);
375 for (size_t i = 0; i < numThreads; ++i) {
376 threads.emplace_back([&objects] {
377 for (size_t rep = 0; rep < numReps; ++rep) {
378 for (size_t i = 0; i < objects.size(); ++i) {
379 objects[i].reset(new FillObject(rep * objects.size() + i));
380 std::this_thread::sleep_for(std::chrono::microseconds(100));
382 for (size_t i = 0; i < objects.size(); ++i) {
389 for (auto& t : threads) {
393 EXPECT_EQ(numFillObjects * numThreads * numReps, gDestroyed);
397 // Yes, threads and fork don't mix
398 // (http://cppwisdom.quora.com/Why-threads-and-fork-dont-mix) but if you're
399 // stupid or desperate enough to try, we shouldn't stand in your way.
403 HoldsOne() : value_(1) { }
404 // Do an actual access to catch the buggy case where this == nullptr
405 int value() const { return value_; }
410 struct HoldsOneTag {};
412 ThreadLocal<HoldsOne, HoldsOneTag> ptr;
416 for (auto& p : ptr.accessAllThreads()) {
424 TEST(ThreadLocal, Fork) {
425 EXPECT_EQ(1, ptr->value()); // ensure created
426 EXPECT_EQ(1, totalValue());
427 // Spawn a new thread
430 bool started = false;
431 std::condition_variable startedCond;
432 bool stopped = false;
433 std::condition_variable stoppedCond;
435 std::thread t([&] () {
436 EXPECT_EQ(1, ptr->value()); // ensure created
438 std::unique_lock<std::mutex> lock(mutex);
440 startedCond.notify_all();
443 std::unique_lock<std::mutex> lock(mutex);
445 stoppedCond.wait(lock);
451 std::unique_lock<std::mutex> lock(mutex);
453 startedCond.wait(lock);
457 EXPECT_EQ(2, totalValue());
462 int v = totalValue();
464 // exit successfully if v == 1 (one thread)
465 // diagnostic error code otherwise :)
471 } else if (pid > 0) {
474 EXPECT_EQ(pid, waitpid(pid, &status, 0));
475 EXPECT_TRUE(WIFEXITED(status));
476 EXPECT_EQ(0, WEXITSTATUS(status));
478 EXPECT_TRUE(false) << "fork failed";
481 EXPECT_EQ(2, totalValue());
484 std::unique_lock<std::mutex> lock(mutex);
486 stoppedCond.notify_all();
491 EXPECT_EQ(1, totalValue());
494 struct HoldsOneTag2 {};
496 TEST(ThreadLocal, Fork2) {
497 // A thread-local tag that was used in the parent from a *different* thread
498 // (but not the forking thread) would cause the child to hang in a
499 // ThreadLocalPtr's object destructor. Yeah.
500 ThreadLocal<HoldsOne, HoldsOneTag2> p;
502 // use tag in different thread
503 std::thread t([&p] { p.get(); });
509 ThreadLocal<HoldsOne, HoldsOneTag2> q;
513 } else if (pid > 0) {
515 EXPECT_EQ(pid, waitpid(pid, &status, 0));
516 EXPECT_TRUE(WIFEXITED(status));
517 EXPECT_EQ(0, WEXITSTATUS(status));
519 EXPECT_TRUE(false) << "fork failed";
523 // Simple reference implementation using pthread_get_specific
525 class PThreadGetSpecific {
527 PThreadGetSpecific() : key_(0) {
528 pthread_key_create(&key_, OnThreadExit);
532 return static_cast<T*>(pthread_getspecific(key_));
537 pthread_setspecific(key_, t);
539 static void OnThreadExit(void* obj) {
540 delete static_cast<T*>(obj);
546 DEFINE_int32(numThreads, 8, "Number simultaneous threads for benchmarks.");
549 BENCHMARK(FB_CONCATENATE(BM_mt_, var), iters) { \
550 const int itersPerThread = iters / FLAGS_numThreads; \
551 std::vector<std::thread> threads; \
552 for (int i = 0; i < FLAGS_numThreads; ++i) { \
553 threads.push_back(std::thread([&]() { \
554 var.reset(new int(0)); \
555 for (int i = 0; i < itersPerThread; ++i) { \
560 for (auto& t : threads) { \
565 ThreadLocalPtr<int> tlp;
567 PThreadGetSpecific<int> pthread_get_specific;
568 REG(pthread_get_specific);
569 boost::thread_specific_ptr<int> boost_tsp;
571 BENCHMARK_DRAW_LINE();
573 int main(int argc, char** argv) {
574 testing::InitGoogleTest(&argc, argv);
575 gflags::ParseCommandLineFlags(&argc, &argv, true);
576 gflags::SetCommandLineOptionWithMode(
577 "bm_max_iters", "100000000", gflags::SET_FLAG_IF_DEFAULT
579 if (FLAGS_benchmark) {
580 folly::runBenchmarks();
582 return RUN_ALL_TESTS();
586 Ran with 24 threads on dual 12-core Xeon(R) X5650 @ 2.67GHz with 12-MB caches
588 Benchmark Iters Total t t/iter iter/sec
589 ------------------------------------------------------------------------------
590 * BM_mt_tlp 100000000 39.88 ms 398.8 ps 2.335 G
591 +5.91% BM_mt_pthread_get_specific 100000000 42.23 ms 422.3 ps 2.205 G
592 + 295% BM_mt_boost_tsp 100000000 157.8 ms 1.578 ns 604.5 M
593 ------------------------------------------------------------------------------