#pragma once #include #include #include #include // A object which can be stored and taken from atomically. template struct AtomicObject { void Set(std::unique_ptr t) { std::lock_guard lock(mutex_); value_ = std::move(t); cv_.notify_one(); } void SetIfEmpty(std::unique_ptr t) { std::lock_guard lock(mutex_); if (value_) return; value_ = std::move(t); cv_.notify_one(); } std::unique_ptr Take() { std::unique_lock lock(mutex_); while (!value_) { // release lock as long as the wait and reaquire it afterwards. cv_.wait(lock); } return std::move(value_); } private: std::unique_ptr value_; mutable std::mutex mutex_; std::condition_variable cv_; };