2 * Copyright 2016 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.
18 #include <unordered_set>
21 #include <folly/SingletonThreadLocal.h>
22 #include <folly/Synchronized.h>
24 #include <gtest/gtest.h>
26 using namespace folly;
29 static std::atomic<std::size_t> fooCreatedCount{0};
30 static std::atomic<std::size_t> fooDeletedCount{0};
39 using FooSingletonTL = SingletonThreadLocal<Foo>;
40 FooSingletonTL theFooSingleton;
43 TEST(SingletonThreadLocalTest, OneSingletonPerThread) {
44 const std::size_t targetThreadCount{64};
45 std::atomic<std::size_t> completedThreadCount{0};
46 Synchronized<std::unordered_set<Foo*>> fooAddresses{};
47 std::vector<std::thread> threads{};
49 [&fooAddresses, targetThreadCount, &completedThreadCount] {
50 fooAddresses.wlock()->emplace(&FooSingletonTL::get());
51 ++completedThreadCount;
52 while (completedThreadCount < targetThreadCount) {
53 std::this_thread::yield();
57 for (std::size_t threadCount{0}; threadCount < targetThreadCount;
59 threads.emplace_back(threadFunction);
62 for (auto& thread : threads) {
65 EXPECT_EQ(threads.size(), fooAddresses.rlock()->size());
66 EXPECT_EQ(threads.size(), fooCreatedCount);
67 EXPECT_EQ(threads.size(), fooDeletedCount);