Properly add RWMutex

This commit is contained in:
Lion Kortlepel 2020-11-08 22:39:20 +01:00
parent 747e948339
commit 7ab37b7fe9
3 changed files with 23 additions and 8 deletions

20
include/RWMutex.h Normal file
View File

@ -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 <shared_mutex>
// 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<RWMutex>;
// 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<RWMutex>;

View File

@ -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() {

View File

@ -7,14 +7,10 @@
#include <chrono>
#include <fstream>
#include <mutex>
#include <shared_mutex>
#include <sstream>
#include <thread>
#include <unordered_map>
using RWMutex = std::shared_mutex;
using ReadLock = std::shared_lock<RWMutex>;
using WriteLock = std::unique_lock<RWMutex>;
#include "RWMutex.h"
static RWMutex ThreadNameMapMutex;
static std::unordered_map<std::thread::id, std::string> 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() {