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.
19 #include <folly/ThreadLocal.h>
20 #include <folly/Singleton.h>
24 template <typename T, typename Tag = detail::DefaultTag>
25 class SingletonThreadLocal {
27 using CreateFunc = std::function<T*(void)>;
29 SingletonThreadLocal() : SingletonThreadLocal([]() { return new T(); }) {}
31 explicit SingletonThreadLocal(CreateFunc createFunc)
32 : singleton_([createFunc = std::move(createFunc)]() mutable {
33 return new ThreadLocalT([createFunc =
34 std::move(createFunc)]() mutable {
35 return new Wrapper(std::unique_ptr<T>(createFunc()));
41 if (UNLIKELY(*localPtr() == nullptr)) {
42 *localPtr() = &(**SingletonT::get());
47 return **SingletonT::get();
53 static T** localPtr() {
54 static FOLLY_TLS T* localPtr = nullptr;
61 explicit Wrapper(std::unique_ptr<T> t) : t_(std::move(t)) {}
65 *localPtr() = nullptr;
69 T& operator*() { return *t_; }
72 std::unique_ptr<T> t_;
75 using ThreadLocalT = ThreadLocal<Wrapper>;
76 using SingletonT = LeakySingleton<ThreadLocalT, Tag>;
78 SingletonT singleton_;