60699a54fa08a53251788ad965532e92a210dfba
[folly.git] / folly / test / SingletonThreadLocalTest.cpp
1 /*
2  * Copyright 2016-present Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include <thread>
18 #include <unordered_set>
19 #include <vector>
20
21 #include <folly/SingletonThreadLocal.h>
22 #include <folly/Synchronized.h>
23 #include <folly/portability/GTest.h>
24
25 using namespace folly;
26
27 namespace {
28 static std::atomic<std::size_t> fooCreatedCount{0};
29 static std::atomic<std::size_t> fooDeletedCount{0};
30 struct Foo {
31   Foo() {
32     ++fooCreatedCount;
33   }
34   ~Foo() {
35     ++fooDeletedCount;
36   }
37 };
38 using FooSingletonTL = SingletonThreadLocal<Foo>;
39 FooSingletonTL theFooSingleton;
40 } // namespace
41
42 TEST(SingletonThreadLocalTest, OneSingletonPerThread) {
43   static constexpr std::size_t targetThreadCount{64};
44   std::atomic<std::size_t> completedThreadCount{0};
45   Synchronized<std::unordered_set<Foo*>> fooAddresses{};
46   std::vector<std::thread> threads{};
47   auto threadFunction = [&fooAddresses, &completedThreadCount] {
48     fooAddresses.wlock()->emplace(&FooSingletonTL::get());
49     ++completedThreadCount;
50     while (completedThreadCount < targetThreadCount) {
51       std::this_thread::yield();
52     }
53   };
54   {
55     for (std::size_t threadCount{0}; threadCount < targetThreadCount;
56          ++threadCount) {
57       threads.emplace_back(threadFunction);
58     }
59   }
60   for (auto& thread : threads) {
61     thread.join();
62   }
63   EXPECT_EQ(threads.size(), fooAddresses.rlock()->size());
64   EXPECT_EQ(threads.size(), fooCreatedCount);
65   EXPECT_EQ(threads.size(), fooDeletedCount);
66 }