Browse Source

Made the data storred in a log counter a shared pointer

Staz M 4 years ago
parent
commit
1facc8a02f
2 changed files with 21 additions and 24 deletions
  1. 14 16
      src/logcounter.cpp
  2. 7 8
      src/logcounter.hpp

+ 14 - 16
src/logcounter.cpp

@@ -18,25 +18,23 @@
 
 #include "logcounter.hpp"
 
-rtc::LogCounter::LogCounter(plog::Severity severity, const std::string &text, std::chrono::seconds duration) :
-        mSeverity(severity), mText(text), mDuration(duration), mIsValidMutex(std::make_shared<std::mutex>()), mIsValid(std::make_shared<bool>(true)) {}
+rtc::LogCounter::LogCounter(plog::Severity severity, const std::string &text, std::chrono::seconds duration) {
+    mData = std::make_shared<LogData>();
+    mData->mDuration  =duration;
+    mData->mSeverity = severity;
+    mData->mText = text;
+}
 
 rtc::LogCounter& rtc::LogCounter::operator++(int) {
-    if (mCount++ == 1) {
-        ThreadPool::Instance().schedule(mDuration, [this, isValidMutex = mIsValidMutex, isValid = mIsValid]() {
-            std::lock_guard lock(*isValidMutex);
-            if (*isValid) {
+    if (mData->mCount++ == 0) {
+        ThreadPool::Instance().schedule(mData->mDuration, [](std::weak_ptr<LogData> data) {
+            if (auto ptr = data.lock()) {
                 int countCopy;
-                countCopy = mCount.exchange(0);
-                PLOG(mSeverity) << mText << ": " << countCopy << " (over "
-                               << std::chrono::duration_cast<std::chrono::seconds>(mDuration).count() << " seconds)";
+                countCopy = ptr->mCount.exchange(0);
+                PLOG(ptr->mSeverity) << ptr->mText << ": " << countCopy << " (over "
+                               << std::chrono::duration_cast<std::chrono::seconds>(ptr->mDuration).count() << " seconds)";
             }
-        });
+        }, mData);
     }
     return *this;
-}
-
-rtc::LogCounter::~LogCounter() {
-    std::lock_guard lock(*mIsValidMutex);
-    *mIsValid = false;
-}
+}

+ 7 - 8
src/logcounter.hpp

@@ -25,21 +25,20 @@
 namespace rtc {
 class LogCounter {
 private:
-    plog::Severity mSeverity;
-    std::string mText;
-    std::chrono::steady_clock::duration mDuration;
+    struct LogData {
+        plog::Severity mSeverity;
+        std::string mText;
+        std::chrono::steady_clock::duration mDuration;
 
-    std::atomic<int> mCount = 0;
+        std::atomic<int> mCount = 0;
+    };
 
-    std::shared_ptr<std::mutex> mIsValidMutex;
-    std::shared_ptr<bool> mIsValid;
+    std::shared_ptr<LogData> mData;
 
 public:
 
     LogCounter(plog::Severity severity, const std::string& text, std::chrono::seconds duration=std::chrono::seconds(1));
 
-    ~LogCounter();
-
     LogCounter& operator++(int);
 };
 }