atomic_object.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #pragma once
  2. #include <library/cpp/yt/threading/rw_spin_lock.h>
  3. #include <concepts>
  4. namespace NYT::NThreading {
  5. ////////////////////////////////////////////////////////////////////////////////
  6. //! A synchronization object to load and store nontrivial object.
  7. //! It looks like atomics but for objects.
  8. template <class T>
  9. class TAtomicObject
  10. {
  11. public:
  12. TAtomicObject() = default;
  13. template <class U>
  14. TAtomicObject(U&& u);
  15. template <class U>
  16. void Store(U&& u);
  17. //! Atomically replaces the old value with the new one and returns the old value.
  18. template <class U>
  19. T Exchange(U&& u);
  20. //! Atomically checks if the current value equals to #expected.
  21. //! If so, replaces it with #desired and returns |true|.
  22. //! Otherwise, copies it into #expected and returns |false|.
  23. bool CompareExchange(T& expected, const T& desired);
  24. //! Atomically transforms the value with function #func.
  25. template <std::invocable<T&> F>
  26. std::invoke_result_t<F, T&> Transform(const F& func);
  27. //! Atomicaly reads the value with function #func.
  28. template <std::invocable<const T&> F>
  29. std::invoke_result_t<F, const T&> Read(const F& func) const;
  30. T Load() const;
  31. private:
  32. T Object_;
  33. YT_DECLARE_SPIN_LOCK(NThreading::TReaderWriterSpinLock, Spinlock_);
  34. };
  35. ////////////////////////////////////////////////////////////////////////////////
  36. template <class TOriginal, class TSerialized>
  37. void ToProto(TSerialized* serialized, const TAtomicObject<TOriginal>& original);
  38. template <class TOriginal, class TSerialized>
  39. void FromProto(TAtomicObject<TOriginal>* original, const TSerialized& serialized);
  40. ////////////////////////////////////////////////////////////////////////////////
  41. } // namespace NYT::NThreading
  42. #define ATOMIC_OBJECT_INL_H_
  43. #include "atomic_object-inl.h"
  44. #undef ATOMIC_OBJECT_INL_H_