Clio  develop
The XRP Ledger API server.
Loading...
Searching...
No Matches
Atomic.hpp
1#pragma once
2
3#include "util/Concepts.hpp"
4
5#include <atomic>
6#include <memory>
7
8namespace util {
9
13template <SomeNumberType NumberType>
14class Atomic {
15public:
16 using ValueType = NumberType;
17
18 Atomic() = default;
19
25 Atomic(ValueType const value) : value_(value)
26 {
27 }
28
29 ~Atomic() = default;
30
31 // Copy and move constructors and assignment operators are not allowed for atomics
32 Atomic(Atomic const&) = delete;
33 Atomic(Atomic&&) = delete;
34 Atomic&
35 operator=(Atomic const&) = delete;
36 Atomic&
37 operator=(Atomic&&) = delete;
38
44 void
45 add(ValueType const value)
46 {
47 if constexpr (std::is_integral_v<ValueType>) {
48 value_.fetch_add(value);
49 } else {
50#if __cpp_lib_atomic_float >= 201711L
51 value_.fetch_add(value);
52#else
53 // Workaround for atomic float not being supported by the standard library
54 // compare_exchange_weak returns false if the value is not exchanged and updates the
55 // current value
56 auto current = value_.load();
57 while (!value_.compare_exchange_weak(current, current + value)) {
58 }
59#endif
60 }
61 }
62
68 void
69 set(ValueType const value)
70 {
71 value_ = value;
72 }
73
79 [[nodiscard]] ValueType
80 value() const
81 {
82 return value_;
83 }
84
85private:
86 std::atomic<ValueType> value_{0};
87};
88
89template <SomeNumberType NumberType>
90using AtomicPtr = std::unique_ptr<Atomic<NumberType>>;
91
92} // namespace util
Atomic wrapper for integral and floating point types.
Definition Atomic.hpp:14
void set(ValueType const value)
Update the current value to the new value.
Definition Atomic.hpp:69
void add(ValueType const value)
Add a value to the current value.
Definition Atomic.hpp:45
ValueType value() const
Get the current value.
Definition Atomic.hpp:80
Atomic(ValueType const value)
Construct a new Atomic object.
Definition Atomic.hpp:25
This namespace contains various utilities.
Definition AccountUtils.hpp:11