Browse Source

Made the destruction of LogCounter safe.

Staz M 5 years ago
parent
commit
09818c4ab8
2 changed files with 25 additions and 20 deletions
  1. 14 14
      src/logcounter.cpp
  2. 11 6
      src/logcounter.hpp

+ 14 - 14
src/logcounter.cpp

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

+ 11 - 6
src/logcounter.hpp

@@ -23,18 +23,23 @@
 #include "include.hpp"
 
 namespace rtc {
-class LogCounter: public std::enable_shared_from_this<LogCounter> {
+class LogCounter {
 private:
-    plog::Severity severity;
-    std::string text;
-    std::chrono::steady_clock::duration duration;
+    plog::Severity mSeverity;
+    std::string mText;
+    std::chrono::steady_clock::duration mDuration;
+
+    std::atomic<int> mCount = 0;
+
+    std::shared_ptr<std::mutex> mIsValidMutex;
+    std::shared_ptr<bool> mIsValid;
 
-    int count = 0;
-    std::mutex mutex;
 public:
 
     LogCounter(plog::Severity severity, const std::string& text, std::chrono::seconds duration=std::chrono::seconds(1));
 
+    ~LogCounter();
+
     LogCounter& operator++(int);
 };
 }