21 SwappingSmart() =
default;
23 explicit SwappingSmart(
const std::shared_ptr<T>& ptr) { Set(ptr); }
25 std::shared_ptr<T> Get()
const {
26 const short index = current_.load(std::memory_order_relaxed);
29 void Set(
const std::shared_ptr<T>& ptr) {
30 std::shared_ptr<T> buf = ptr;
32 while (write_lock_.test_and_set(std::memory_order_acquire)) {
35 const short index = current_.load(std::memory_order_relaxed);
37 const short new_index = 1 - index;
39 std::swap(ptrs_[new_index], buf);
41 current_.store(new_index, std::memory_order_relaxed);
43 write_lock_.clear(std::memory_order_release);
46 void Set(T&& obj) { Set(std::make_shared<T>(std::move(obj))); }
48 Set(std::make_shared<T>());
49 Set(std::make_shared<T>());
53 std::atomic<
short> current_{0};
54 std::atomic_flag write_lock_ ATOMIC_FLAG_INIT;
55 std::shared_ptr<T> ptrs_[2];