access.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #pragma once
  2. #include <library/cpp/yt/memory/erased_storage.h>
  3. #include <library/cpp/yt/misc/strong_typedef.h>
  4. #include <atomic>
  5. namespace NYT::NGlobal {
  6. ////////////////////////////////////////////////////////////////////////////////
  7. namespace NDetail {
  8. class TGlobalVariablesRegistry;
  9. } // namespace NDetail
  10. ////////////////////////////////////////////////////////////////////////////////
  11. inline constexpr size_t GlobalVariableMaxByteSize = 32;
  12. using TErasedStorage = NYT::TErasedStorage<GlobalVariableMaxByteSize>;
  13. // NB(arkady-e1ppa): Accessor must ensure thread-safety on its own.
  14. using TAccessor = TErasedStorage(*)() noexcept;
  15. ////////////////////////////////////////////////////////////////////////////////
  16. // Usage:
  17. /*
  18. * // public.h file:
  19. * // NB: It's important to mark it inline for linker to deduplicate
  20. * // addresses accross different UT's.
  21. * inline constexpr NGlobal::TVariableTag MyGlobalVarTag = {};
  22. *
  23. *
  24. *
  25. * // some_stuff.cpp file
  26. *
  27. * TErasedStorage GetMyVar()
  28. * {
  29. * // definition here
  30. * }
  31. * NGlobal::Variable<int> MyGlobalVar{MyGlobalVarTag, &GetMyVar};
  32. *
  33. *
  34. *
  35. * // other_stuff.cpp file
  36. *
  37. *
  38. * int ReadMyVar()
  39. * {
  40. * auto erased = NGlobal::GetErasedVariable(MyGlobalVarTag);
  41. * return erased->AsConcrete<int>();
  42. * }
  43. */
  44. class TVariableTag
  45. {
  46. public:
  47. TVariableTag() = default;
  48. TVariableTag(const TVariableTag& other) = delete;
  49. TVariableTag& operator=(const TVariableTag& other) = delete;
  50. private:
  51. friend class ::NYT::NGlobal::NDetail::TGlobalVariablesRegistry;
  52. mutable std::atomic<bool> Initialized_ = false;
  53. mutable std::atomic<int> Key_ = -1;
  54. };
  55. ////////////////////////////////////////////////////////////////////////////////
  56. // Defined in impl.cpp.
  57. // |std::nullopt| iff global variable with a given tag is not present.
  58. std::optional<TErasedStorage> GetErasedVariable(const TVariableTag& tag);
  59. ////////////////////////////////////////////////////////////////////////////////
  60. } // namespace NYT::NGlobal