2 * Copyright 2017 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 // SingletonThreadLocal
26 // This class can help you implement a per-thread leaky-singleton model within
27 // your application. Please read the usage block at the top of Singleton.h as
28 // the recommendations there are also generally applicable to this class.
30 // When we say this is "leaky" we mean that the T instances held by a
31 // SingletonThreadLocal<T> will survive until their owning thread exits,
32 // regardless of the lifetime of the singleton object holding them. That
33 // means that they can be safely used during process shutdown, and
34 // that they can also be safely used in an application that spawns many
35 // temporary threads throughout its life.
37 // Keywords to help people find this class in search:
38 // Thread Local Singleton ThreadLocalSingleton
39 template <typename T, typename Tag = detail::DefaultTag>
40 class SingletonThreadLocal {
42 using CreateFunc = std::function<T*(void)>;
44 SingletonThreadLocal() : SingletonThreadLocal([]() { return new T(); }) {}
46 explicit SingletonThreadLocal(CreateFunc createFunc)
47 : singleton_([createFunc = std::move(createFunc)]() mutable {
48 return new ThreadLocalT([createFunc =
49 std::move(createFunc)]() mutable {
50 return new Wrapper(std::unique_ptr<T>(createFunc()));
56 if (UNLIKELY(*localPtr() == nullptr)) {
57 *localPtr() = &(**SingletonT::get());
62 return **SingletonT::get();
68 static T** localPtr() {
69 static FOLLY_TLS T* localPtr = nullptr;
76 explicit Wrapper(std::unique_ptr<T> t) : t_(std::move(t)) {}
80 *localPtr() = nullptr;
84 T& operator*() { return *t_; }
87 std::unique_ptr<T> t_;
90 using ThreadLocalT = ThreadLocal<Wrapper>;
91 using SingletonT = LeakySingleton<ThreadLocalT, Tag>;
93 SingletonT singleton_;