userver
C++ Async Framework
Toggle main menu visibility
Loading...
Searching...
No Matches
relaxed_counter.hpp
Go to the documentation of this file.
1
#pragma once
2
5
6
#include <atomic>
7
8
#include <
userver/utils/statistics/fwd.hpp
>
9
10
USERVER_NAMESPACE_BEGIN
11
12
namespace
utils::statistics
{
13
18
template
<
class
T>
19
class
RelaxedCounter final {
20
public
:
21
using
ValueType = T;
22
23
constexpr
RelaxedCounter()
noexcept
=
default
;
24
constexpr
RelaxedCounter(T desired) noexcept : val_(desired) {}
25
26
RelaxedCounter(
const
RelaxedCounter& other) noexcept : val_(other.Load()) {}
27
28
RelaxedCounter& operator=(
const
RelaxedCounter& other)
noexcept
{
29
if
(
this
== &other) {
30
return
*
this
;
31
}
32
33
Store(other.Load());
34
return
*
this
;
35
}
36
37
RelaxedCounter& operator=(T desired)
noexcept
{
38
Store(desired);
39
return
*
this
;
40
}
41
42
void
Store(T desired)
noexcept
{ val_.store(desired, std::memory_order_relaxed); }
43
44
T Load()
const
noexcept
{
return
val_.load(std::memory_order_relaxed); }
45
46
operator
T()
const
noexcept
{
return
Load(); }
47
48
RelaxedCounter& operator++()
noexcept
{
49
val_.fetch_add(1, std::memory_order_relaxed);
50
return
*
this
;
51
}
52
53
T operator++(
int
)
noexcept
{
return
val_.fetch_add(1, std::memory_order_relaxed); }
54
55
RelaxedCounter& operator--()
noexcept
{
56
val_.fetch_sub(1, std::memory_order_relaxed);
57
return
*
this
;
58
}
59
60
T operator--(
int
)
noexcept
{
return
val_.fetch_sub(1, std::memory_order_relaxed); }
61
62
RelaxedCounter& operator+=(T arg)
noexcept
{
63
val_.fetch_add(arg, std::memory_order_relaxed);
64
return
*
this
;
65
}
66
67
RelaxedCounter& operator-=(T arg)
noexcept
{
68
val_.fetch_sub(arg, std::memory_order_relaxed);
69
return
*
this
;
70
}
71
72
private
:
73
static_assert
(std::atomic<T>::is_always_lock_free);
74
75
std::atomic<T> val_{T{}};
76
};
77
78
template
<
typename
T>
79
void
DumpMetric
(
Writer
& writer,
const
RelaxedCounter<T>
& value) {
80
writer = value.Load();
81
}
82
83
template
<
typename
T>
84
void
ResetMetric(RelaxedCounter<T>& value) {
85
value.Store(0);
86
}
87
88
}
// namespace utils::statistics
89
90
USERVER_NAMESPACE_END
userver
utils
statistics
relaxed_counter.hpp
Generated on
for userver by
Doxygen
1.17.0