atomics_array.h 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #pragma once
  2. #include <util/generic/ptr.h>
  3. #include <util/generic/vector.h>
  4. #include <atomic>
  5. namespace NMonitoring {
  6. class TAtomicsArray {
  7. public:
  8. explicit TAtomicsArray(size_t size)
  9. : Values_(new std::atomic<ui64>[size])
  10. , Size_(size)
  11. {
  12. for (size_t i = 0; i < Size_; i++) {
  13. Values_[i].store(0, std::memory_order_relaxed);
  14. }
  15. }
  16. ui64 operator[](size_t index) const noexcept {
  17. Y_DEBUG_ABORT_UNLESS(index < Size_);
  18. return Values_[index].load(std::memory_order_relaxed);
  19. }
  20. size_t Size() const noexcept {
  21. return Size_;
  22. }
  23. void Add(size_t index, ui64 count) noexcept {
  24. Y_DEBUG_ABORT_UNLESS(index < Size_);
  25. Values_[index].fetch_add(count, std::memory_order_relaxed);
  26. }
  27. void Reset() noexcept {
  28. for (size_t i = 0; i < Size_; i++) {
  29. Values_[i].store(0, std::memory_order_relaxed);
  30. }
  31. }
  32. TVector<ui64> Copy() const {
  33. TVector<ui64> copy(Reserve(Size_));
  34. for (size_t i = 0; i < Size_; i++) {
  35. copy.push_back(Values_[i].load(std::memory_order_relaxed));
  36. }
  37. return copy;
  38. }
  39. private:
  40. TArrayHolder<std::atomic<ui64>> Values_;
  41. size_t Size_;
  42. };
  43. }