summaryrefslogtreecommitdiff
path: root/Source/Core/Common/Mutex.h
blob: 22aebd08b1b072890a1cfce61232e665375b70fa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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