singleton.h 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #pragma once
  2. #include <util/system/tls.h>
  3. #include <util/generic/singleton.h>
  4. #include <util/generic/ptr.h>
  5. namespace NPrivate {
  6. template <class T, size_t Priority>
  7. struct TFastThreadSingletonHelper {
  8. static inline T* GetSlow() {
  9. return SingletonWithPriority<NTls::TValue<T>, Priority>()->GetPtr();
  10. }
  11. static inline T* Get() {
  12. #if defined(Y_HAVE_FAST_POD_TLS)
  13. Y_POD_STATIC_THREAD(T*) fast(nullptr);
  14. if (Y_UNLIKELY(!fast)) {
  15. fast = GetSlow();
  16. }
  17. return fast;
  18. #else
  19. return GetSlow();
  20. #endif
  21. }
  22. };
  23. } // namespace NPrivate
  24. template <class T, size_t Priority>
  25. Y_RETURNS_NONNULL static inline T* FastTlsSingletonWithPriority() {
  26. return ::NPrivate::TFastThreadSingletonHelper<T, Priority>::Get();
  27. }
  28. // NB: the singleton is the same for all modules that use
  29. // FastTlsSingleton with the same type parameter. If unique singleton
  30. // required, use unique types.
  31. template <class T>
  32. Y_RETURNS_NONNULL static inline T* FastTlsSingleton() {
  33. return FastTlsSingletonWithPriority<T, TSingletonTraits<T>::Priority>();
  34. }