aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/yt/threading/atomic_object.h
blob: e986f872a083b05cd4d6e2c40da73415ffc35872 (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
#pragma once

#include <library/cpp/yt/threading/rw_spin_lock.h>

#include <concepts>

namespace NYT {

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

//! A synchronization object to load and store nontrivial object.
//! It looks like atomics but for objects.
template <class T>
class TAtomicObject
{
public:
    TAtomicObject() = default;

    template <class U>
    TAtomicObject(U&& u);

    template <class U>
    void Store(U&& u);

    //! Atomically replaces the old value with the new one and returns the old value.
    template <class U>
    T Exchange(U&& u);

    //! Atomically checks if then current value equals #expected.
    //! If so, replaces it with #desired and returns |true|.
    //! Otherwise, copies it into #expected and returns |false|.
    bool CompareExchange(T& expected, const T& desired);

    //! Atomically transforms the value with function #func.
    template <std::invocable<T&> F>
    std::invoke_result_t<F, T&> Transform(const F& func);

    //! Atomicaly reads the value with function #func.
    template <std::invocable<const T&> F>
    std::invoke_result_t<F, const T&> Read(const F& func) const;

    T Load() const;

private:
    T Object_;
    YT_DECLARE_SPIN_LOCK(NThreading::TReaderWriterSpinLock, Spinlock_);
};

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

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

template <class TOriginal, class TSerialized>
void FromProto(TAtomicObject<TOriginal>* original, const TSerialized& serialized);

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

} // namespace NYT

#define ATOMIC_OBJECT_INL_H_
#include "atomic_object-inl.h"
#undef ATOMIC_OBJECT_INL_H_