Make mutex not deadlock when a thread double locks it

This commit is contained in:
offtkp 2023-09-29 12:11:57 +03:00
parent 7df6903cf8
commit 7d5ce2fc83
2 changed files with 24 additions and 3 deletions

View file

@ -56,11 +56,31 @@ Lib::Mutex::Mutex() { m_mutex = new MutexStructInternal(); }
Lib::Mutex::~Mutex() { delete m_mutex; }
void Lib::Mutex::LockMutex() { m_mutex->m_cs.lock(); }
void Lib::Mutex::LockMutex() {
if (m_mutex->m_owner == std::this_thread::get_id()) {
return;
}
void Lib::Mutex::UnlockMutex() { m_mutex->m_cs.unlock(); }
m_mutex->m_cs.lock();
m_mutex->m_owner = std::this_thread::get_id();
}
bool Lib::Mutex::TryLockMutex() { return m_mutex->m_cs.try_lock(); }
void Lib::Mutex::UnlockMutex() {
m_mutex->m_owner = std::thread::id();
m_mutex->m_cs.unlock();
}
bool Lib::Mutex::TryLockMutex() {
if (m_mutex->m_owner == std::this_thread::get_id()) {
return false;
}
if (m_mutex->m_cs.try_lock()) {
m_mutex->m_owner = std::this_thread::get_id();
return true;
}
return false;
}
Lib::ConditionVariable::ConditionVariable() { m_cond_var = new ConditionVariableStructInternal(); }

View file

@ -91,6 +91,7 @@ struct MutexStructInternal {
MutexStructInternal() = default;
~MutexStructInternal() = default;
std::mutex m_cs{};
std::atomic<std::thread::id> m_owner{};
};
class ConditionVariable {
public: