DynamicCounter.h 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #pragma once
  2. #include <functional>
  3. #include <memory>
  4. #include <string_view>
  5. #include <c10/macros/Macros.h>
  6. namespace c10::monitor {
  7. class C10_API DynamicCounter {
  8. public:
  9. using Callback = std::function<int64_t()>;
  10. // Creates a dynamic counter that can be queried at any point in time by
  11. // multiple backends. Only one counter with a given key can exist at any point
  12. // in time.
  13. //
  14. // The callback is invoked every time the counter is queried.
  15. // The callback must be thread-safe.
  16. // The callback must not throw.
  17. // The callback must not block.
  18. DynamicCounter(std::string_view key, Callback getCounterCallback);
  19. // Unregisters the callback.
  20. // Waits for all ongoing callback invocations to finish.
  21. ~DynamicCounter();
  22. private:
  23. struct Guard;
  24. std::unique_ptr<Guard> guard_;
  25. };
  26. namespace detail {
  27. class DynamicCounterBackendIf {
  28. public:
  29. virtual ~DynamicCounterBackendIf() = default;
  30. virtual void registerCounter(
  31. std::string_view key,
  32. DynamicCounter::Callback getCounterCallback) = 0;
  33. // MUST wait for all ongoing callback invocations to finish
  34. virtual void unregisterCounter(std::string_view key) = 0;
  35. };
  36. void C10_API
  37. registerDynamicCounterBackend(std::unique_ptr<DynamicCounterBackendIf>);
  38. } // namespace detail
  39. } // namespace c10::monitor