proxygen
StaticSingletonManager.cpp
Go to the documentation of this file.
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 
18 
19 #include <mutex>
20 #include <typeindex>
21 #include <unordered_map>
22 
23 namespace folly {
24 namespace detail {
25 
26 namespace {
27 
28 class StaticSingletonManagerImpl {
29  public:
30  void* create(std::type_info const& key, void* (*make)(void*), void* ctx) {
31  auto& e = entry(key);
32  std::lock_guard<std::mutex> lock(e.mutex);
33  return e.ptr ? e.ptr : (e.ptr = make(ctx));
34  }
35 
36  private:
37  struct Entry {
38  void* ptr{};
40  };
41 
42  Entry& entry(std::type_info const& key) {
43  std::lock_guard<std::mutex> lock(mutex_);
44  auto& e = map_[key];
45  return e ? *e : *(e = new Entry());
46  }
47 
48  std::unordered_map<std::type_index, Entry*> map_;
50 };
51 
52 } // namespace
53 
54 void* StaticSingletonManager::create_(Key const& key, Make* make, void* ctx) {
55  // This Leaky Meyers Singleton must always live in the .cpp file.
56  static auto& instance = *new StaticSingletonManagerImpl();
57  return instance.create(key, make, ctx);
58 }
59 
60 } // namespace detail
61 } // namespace folly
void * ptr
—— Concurrent Priority Queue Implementation ——
Definition: AtomicBitSet.h:29
std::mutex mutex_
std::unordered_map< std::type_index, Entry * > map_
auto lock(SynchronizedLocker...lockersIn) -> std::tuple< typename SynchronizedLocker::LockedPtr... >
Definition: Synchronized.h:871
FOLLY_ALWAYS_INLINE static FOLLY_ATTR_VISIBILITY_HIDDEN void * create_(F &creator)
std::mutex mutex