StaticSingletonManager.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. #include <folly/detail/StaticSingletonManager.h>
  17. #include <mutex>
  18. #include <typeindex>
  19. #include <unordered_map>
  20. namespace folly {
  21. namespace detail {
  22. namespace {
  23. class StaticSingletonManagerImpl {
  24. public:
  25. void* create(std::type_info const& key, void* (*make)(void*), void* ctx) {
  26. auto& e = entry(key);
  27. std::lock_guard<std::mutex> lock(e.mutex);
  28. return e.ptr ? e.ptr : (e.ptr = make(ctx));
  29. }
  30. private:
  31. struct Entry {
  32. void* ptr{};
  33. std::mutex mutex;
  34. };
  35. Entry& entry(std::type_info const& key) {
  36. std::lock_guard<std::mutex> lock(mutex_);
  37. auto& e = map_[key];
  38. return e ? *e : *(e = new Entry());
  39. }
  40. std::unordered_map<std::type_index, Entry*> map_;
  41. std::mutex mutex_;
  42. };
  43. } // namespace
  44. void* StaticSingletonManager::create_(Key const& key, Make* make, void* ctx) {
  45. // This Leaky Meyers Singleton must always live in the .cpp file.
  46. static auto& instance = *new StaticSingletonManagerImpl();
  47. return instance.create(key, make, ctx);
  48. }
  49. } // namespace detail
  50. } // namespace folly