aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/yt/threading/atomic_object-inl.h
blob: fc8238cc83c69a4214dfa054f8bf22b3cffdcf0f (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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#ifndef ATOMIC_OBJECT_INL_H_
#error "Direct inclusion of this file is not allowed, include atomic_object.h"
// For the sake of sane code completion.
#include "atomic_object.h"
#endif

namespace NYT::NThreading {

////////////////////////////////////////////////////////////////////////////////

template <class T>
template <class U>
TAtomicObject<T>::TAtomicObject(U&& u)
    : Object_(std::forward<U>(u))
{ }

template <class T>
template <class U>
void TAtomicObject<T>::Store(U&& u)
{
    // NB: Using exchange to avoid destructing the old object while holding the lock.
    std::ignore = Exchange(std::forward<U>(u));
}

template <class T>
template <class U>
T TAtomicObject<T>::Exchange(U&& u)
{
    T tmpObject = std::forward<U>(u);
    {
        auto guard = WriterGuard(Spinlock_);
        std::swap(Object_, tmpObject);
    }
    return tmpObject;
}

template <class T>
bool TAtomicObject<T>::CompareExchange(T& expected, const T& desired)
{
    auto guard = WriterGuard(Spinlock_);
    if (Object_ == expected) {
        auto oldObject = std::move(Object_);
        Y_UNUSED(oldObject);
        Object_ = desired;
        guard.Release();
        return true;
    } else {
        auto oldExpected = std::move(expected);
        Y_UNUSED(oldExpected);
        expected = Object_;
        guard.Release();
        return false;
    }
}

template <class T>
template <std::invocable<T&> F>
std::invoke_result_t<F, T&> TAtomicObject<T>::Transform(const F& func)
{
    auto guard = WriterGuard(Spinlock_);
    return func(Object_);
}

template <class T>
template <std::invocable<const T&> F>
std::invoke_result_t<F, const T&> TAtomicObject<T>::Read(const F& func) const
{
    auto guard = ReaderGuard(Spinlock_);
    return func(Object_);
}

template <class T>
T TAtomicObject<T>::Load() const
{
    auto guard = ReaderGuard(Spinlock_);
    return Object_;
}

////////////////////////////////////////////////////////////////////////////////

template <class TOriginal, class TSerialized>
void ToProto(TSerialized* serialized, const TAtomicObject<TOriginal>& original)
{
    ToProto(serialized, original.Load());
}

template <class TOriginal, class TSerialized>
void FromProto(TAtomicObject<TOriginal>* original, const TSerialized& serialized)
{
    TOriginal data;
    FromProto(&data, serialized);
    original->Store(std::move(data));
}

////////////////////////////////////////////////////////////////////////////////

} // namespace NYT::NThreading