27 SwappingSmart() =
default;
29 explicit SwappingSmart(
const std::shared_ptr<T>& ptr) { Set(ptr); }
31 std::shared_ptr<T> Get()
const {
32 const short index = current_.load(std::memory_order_relaxed);
35 void Set(
const std::shared_ptr<T>& ptr) {
36 std::shared_ptr<T> buf = ptr;
38 while (write_lock_.test_and_set(std::memory_order_acquire)) {
41 const short index = current_.load(std::memory_order_relaxed);
43 const short new_index = 1 - index;
45 std::swap(ptrs_[new_index], buf);
47 current_.store(new_index, std::memory_order_relaxed);
49 write_lock_.clear(std::memory_order_release);
52 void Set(T&& obj) { Set(std::make_shared<T>(std::move(obj))); }
54 Set(std::make_shared<T>());
55 Set(std::make_shared<T>());
59 std::atomic<
short> current_{0};
60 std::atomic_flag write_lock_ ATOMIC_FLAG_INIT;
61 std::shared_ptr<T> ptrs_[2];