aboutsummaryrefslogtreecommitdiff
path: root/libs/kstd/src/mutex.cpp
blob: d66cb984b6af35c12aaf125fa3d50df2256325a8 (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
#include "kstd/mutex"

#include "kstd/os/error.hpp"

#include <atomic>

namespace kstd
{

  mutex::mutex() = default;

  mutex::~mutex()
  {
    if (m_locked.test(std::memory_order_relaxed))
    {
      os::panic("[KSTD] Tried to destroy a locked mutex.");
    }
  }

  auto mutex::lock() -> void
  {
    while (!try_lock())
    {
      asm volatile("nop");
    }
  }

  auto mutex::try_lock() -> bool
  {
    return !m_locked.test_and_set(std::memory_order_acquire);
  }

  auto mutex::unlock() -> void
  {
    m_locked.clear(std::memory_order_release);
  }

}  // namespace kstd