I'm developing a multi-threaded C++ project and have a variable that should be accessed atomically for reading and writing. I use this simple self-written wrapper to avoid race conditions:
template<typename T>
class Locker final {
std::mutex mutex;
T value{};
public:
explicit Locker(const T& value_) : value(value_) {};
inline T get() { std::lock_guard<std::mutex> guard(mutex); return value; }
inline void set(const T& value_) { std::lock_guard<std::mutex> guard(mutex); value = value_; }
};
I've read that the std::atomic class does similar things, but it only works for TriviallyCopyable types and I want to store different non-TriviallyCopyable types. Does modern C++ provide built-in alternatives for this purpose?
I want for some data to be updated asynchronously on timeout, and non-updatable threads have safe access to it.