Debian Codegraph @

Source/Core/Common/Mutex.h

raw symbols SCIP
1 // Copyright 2025 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #pragma once
5
6 #include <atomic>
7
8 namespace Common
9 {
10 namespace detail
11 {
12 template <bool UseAtomicWait>
13 class AtomicMutexBase
14 {
15 public:
16 void lock()
17 {
18 while (m_lock.exchange(true, std::memory_order_acquire))
19 {
20 if constexpr (UseAtomicWait)
21 m_lock.wait(true, std::memory_order_relaxed);
22 }
23 }
24
25 bool try_lock()
26 {
27 bool expected = false;
28 return m_lock.compare_exchange_weak(expected, true, std::memory_order_acquire,
29 std::memory_order_relaxed);
30 }
31
32 // Unlike with std::mutex, this call may come from any thread.
33 void unlock()
34 {
35 m_lock.store(false, std::memory_order_release);
36 if constexpr (UseAtomicWait)
37 m_lock.notify_one();
38 }
39
40 private:
41 std::atomic_bool m_lock{};
42 };
43 } // namespace detail
44
45 // Sometimes faster than std::mutex.
46 using AtomicMutex = detail::AtomicMutexBase<true>;
47
48 // Very fast to lock and unlock when uncontested (~3x faster than std::mutex).
49 using SpinMutex = detail::AtomicMutexBase<false>;
50
51 } // namespace Common