From 7ab37b7fe9d03cd858b29a4e7b1a5ff933784a86 Mon Sep 17 00:00:00 2001 From: Lion Kortlepel Date: Sun, 8 Nov 2020 22:39:20 +0100 Subject: [PATCH] Properly add RWMutex --- include/RWMutex.h | 20 ++++++++++++++++++++ src/Console.cpp | 3 ++- src/logger.cpp | 8 +------- 3 files changed, 23 insertions(+), 8 deletions(-) create mode 100644 include/RWMutex.h diff --git a/include/RWMutex.h b/include/RWMutex.h new file mode 100644 index 0000000..4ff2de0 --- /dev/null +++ b/include/RWMutex.h @@ -0,0 +1,20 @@ +// Author: lionkor +#pragma once + +/* + * An RWMutex allows multiple simultaneous readlocks but only one writelock at a time, + * and write locks and read locks are mutually exclusive. + */ + +#include + +// Use ReadLock(m) and WriteLock(m) to lock it. +using RWMutex = std::shared_mutex; +// Construct with an RWMutex as a non-const reference. +// locks the mutex in lock_shared mode (for reading). Locking in a thread that already owns a lock +// i.e. locking multiple times successively is UB. Construction may be blocking. Destruction is guaranteed to release the lock. +using ReadLock = std::shared_lock; +// Construct with an RWMutex as a non-const reference. +// locks the mutex for writing. Construction may be blocking. Destruction is guaranteed to release the lock. +using WriteLock = std::unique_lock; + diff --git a/src/Console.cpp b/src/Console.cpp index 75c5cfe..202e421 100644 --- a/src/Console.cpp +++ b/src/Console.cpp @@ -27,8 +27,9 @@ void HandleInput(const std::string& cmd) { std::cout << std::endl; if (cmd == "exit") { _Exit(0); - } else + } else { LuaConsole->Execute(cmd); + } } void ProcessOut() { diff --git a/src/logger.cpp b/src/logger.cpp index cf7b70b..169c49c 100644 --- a/src/logger.cpp +++ b/src/logger.cpp @@ -7,14 +7,10 @@ #include #include #include -#include #include #include #include - -using RWMutex = std::shared_mutex; -using ReadLock = std::shared_lock; -using WriteLock = std::unique_lock; +#include "RWMutex.h" static RWMutex ThreadNameMapMutex; static std::unordered_map ThreadNameMap; @@ -29,7 +25,6 @@ std::string ThreadName() { ss << std::this_thread::get_id(); Name = ss.str(); } - lock.unlock(); return Name; } @@ -38,7 +33,6 @@ void SetThreadName(const std::string& Name, bool overwrite) { if (overwrite || ThreadNameMap.find(std::this_thread::get_id()) == ThreadNameMap.end()) { ThreadNameMap[std::this_thread::get_id()] = Name; } - lock.unlock(); } std::string getDate() {