Common: Add AtomicMutex and SpinMutex classes as faster alternatives to std::mutex.
This commit is contained in:
@@ -111,6 +111,7 @@ add_library(common
|
||||
MinizipUtil.h
|
||||
MsgHandler.cpp
|
||||
MsgHandler.h
|
||||
Mutex.h
|
||||
NandPaths.cpp
|
||||
NandPaths.h
|
||||
Network.cpp
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
// Copyright 2025 Dolphin Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
|
||||
namespace Common
|
||||
{
|
||||
namespace detail
|
||||
{
|
||||
template <bool UseAtomicWait>
|
||||
class AtomicMutexBase
|
||||
{
|
||||
public:
|
||||
void lock()
|
||||
{
|
||||
while (m_lock.exchange(true, std::memory_order_acquire))
|
||||
{
|
||||
if constexpr (UseAtomicWait)
|
||||
m_lock.wait(true, std::memory_order_relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
bool try_lock()
|
||||
{
|
||||
bool expected = false;
|
||||
return m_lock.compare_exchange_weak(expected, true, std::memory_order_acquire,
|
||||
std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
// Unlike with std::mutex, this call may come from any thread.
|
||||
void unlock()
|
||||
{
|
||||
m_lock.store(false, std::memory_order_release);
|
||||
if constexpr (UseAtomicWait)
|
||||
m_lock.notify_one();
|
||||
}
|
||||
|
||||
private:
|
||||
std::atomic_bool m_lock{};
|
||||
};
|
||||
} // namespace detail
|
||||
|
||||
// Sometimes faster than std::mutex.
|
||||
using AtomicMutex = detail::AtomicMutexBase<true>;
|
||||
|
||||
// Very fast to lock and unlock when uncontested (~3x faster than std::mutex).
|
||||
using SpinMutex = detail::AtomicMutexBase<false>;
|
||||
|
||||
} // namespace Common
|
||||
@@ -145,6 +145,7 @@
|
||||
<ClInclude Include="Common\MemoryUtil.h" />
|
||||
<ClInclude Include="Common\MinizipUtil.h" />
|
||||
<ClInclude Include="Common\MsgHandler.h" />
|
||||
<ClInclude Include="Common\Mutex.h" />
|
||||
<ClInclude Include="Common\NandPaths.h" />
|
||||
<ClInclude Include="Common\Network.h" />
|
||||
<ClInclude Include="Common\PcapFile.h" />
|
||||
|
||||
Reference in New Issue
Block a user