aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/monlib/metrics/atomics_array.h
blob: f19aebf291517cf79b331b942d72e13268e1a1c7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#pragma once

#include <util/generic/ptr.h>
#include <util/generic/vector.h>

#include <atomic>

namespace NMonitoring {
    class TAtomicsArray {
    public:
        explicit TAtomicsArray(size_t size)
            : Values_(new std::atomic<ui64>[size])
            , Size_(size)
        {
            for (size_t i = 0; i < Size_; i++) {
                Values_[i].store(0, std::memory_order_relaxed);
            }
        }

        ui64 operator[](size_t index) const noexcept {
            Y_VERIFY_DEBUG(index < Size_);
            return Values_[index].load(std::memory_order_relaxed);
        }

        size_t Size() const noexcept {
            return Size_;
        }

        void Add(size_t index, ui32 count) noexcept {
            Y_VERIFY_DEBUG(index < Size_);
            Values_[index].fetch_add(count, std::memory_order_relaxed);
        }

        void Reset() noexcept {
            for (size_t i = 0; i < Size_; i++) {
                Values_[i].store(0, std::memory_order_relaxed);
            }
        }

        TVector<ui64> Copy() const {
            TVector<ui64> copy(Reserve(Size_));
            for (size_t i = 0; i < Size_; i++) {
                copy.push_back(Values_[i].load(std::memory_order_relaxed));
            }
            return copy;
        }

    private:
        TArrayHolder<std::atomic<ui64>> Values_;
        size_t Size_;
    };
}