From e922d47197a292a24aea2204d9771c8ed8c1fc7d Mon Sep 17 00:00:00 2001 From: Henry Winkel Date: Thu, 10 Aug 2023 17:18:36 +0200 Subject: [PATCH] ADD: made data threadsafe --- include/SimCore/data.hpp | 56 ++++++++++++++++++++++++++++++++++------ 1 file changed, 48 insertions(+), 8 deletions(-) diff --git a/include/SimCore/data.hpp b/include/SimCore/data.hpp index 9c52a99..eee9e22 100644 --- a/include/SimCore/data.hpp +++ b/include/SimCore/data.hpp @@ -1,29 +1,57 @@ #pragma once #include +#include namespace SimCore { template class Data{ - private: - - T data_; - - bool valid_; - - std::uint64_t writeTime_; public: - Data():valid_(false),writeTime_(std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count()) + Data():mx(),valid_(false),writeTime_(std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count()) { } + Data (const Data &other) + { + std::lock_guard guard(other.mx); + if (typeid(other.data_) == typeid(data_)) + { + data_ = other.data_; + valid_ = true; + writeTime_ = other.writeTime_; + }else + { + valid_ = false; + } + + + } + + + Data& operator=(const Data other) + { + std::lock_guard lock(other.mx); + if (typeid(other.data_) == typeid(data_)) + { + this->data_ = other.data_; + this->valid_ = other.valid_; + this->writeTime_ = other.writeTime_; + }else + { + this->valid_ = false; + } + + return *this; + } + void setValue(T value) { + std::lock_guard guard(mx); data_ = value; valid_ = true; writeTime_ = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); @@ -31,6 +59,7 @@ namespace SimCore T getValue() { + std::lock_guard guard(mx); return data_; } @@ -42,14 +71,25 @@ namespace SimCore bool isValid() { + std::lock_guard guard(mx); return valid_; } std::uint64_t getWriteTime() { + std::lock_guard guard(mx); return writeTime_; } + private: + + T data_; + + bool valid_; + + std::uint64_t writeTime_; + mutable std::mutex mx; +