Fix folly::ThreadLocal to have unique singleton in dev builds
[folly.git] / folly / detail / StaticSingletonManager.h
1 /*
2  * Copyright 2016 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 #pragma once
18
19 #include <mutex>
20 #include <typeindex>
21 #include <unordered_map>
22
23 namespace folly {
24 namespace detail {
25
26 // This internal-use-only class is used to create all leaked Meyers singletons.
27 // It guarantees that only one instance of every such singleton will ever be
28 // created, even when requested from different compilation units linked
29 // dynamically.
30 class StaticSingletonManager {
31  public:
32   static StaticSingletonManager& instance();
33
34   template <typename T, typename Tag, typename F>
35   inline T* create(F&& creator) {
36     auto& entry = [&]() mutable -> Entry<T>& {
37       std::lock_guard<std::mutex> lg(mutex_);
38
39       auto& id = typeid(TypePair<T, Tag>);
40       auto& entryPtr = map_[id];
41       if (!entryPtr) {
42         entryPtr = new Entry<T>();
43       }
44       assert(dynamic_cast<Entry<T>*>(entryPtr) != nullptr);
45       return *static_cast<Entry<T>*>(entryPtr);
46     }();
47
48     std::lock_guard<std::mutex> lg(entry.mutex);
49
50     if (!entry.ptr) {
51       entry.ptr = creator();
52     }
53     return entry.ptr;
54   }
55
56  private:
57   template <typename A, typename B>
58   class TypePair {};
59
60   StaticSingletonManager() {}
61
62   struct EntryIf {
63     virtual ~EntryIf() {}
64   };
65
66   template <typename T>
67   struct Entry : public EntryIf {
68     T* ptr{nullptr};
69     std::mutex mutex;
70   };
71
72   std::unordered_map<std::type_index, EntryIf*> map_;
73   std::mutex mutex_;
74 };
75
76 template <typename T, typename Tag, typename F>
77 inline T* createGlobal(F&& creator) {
78   return StaticSingletonManager::instance().create<T, Tag>(
79       std::forward<F>(creator));
80 }
81
82 template <typename T, typename Tag>
83 inline T* createGlobal() {
84   return createGlobal<T, Tag>([]() { return new T(); });
85 }
86 }
87 }