Gaia-ECS
v1.0.0
A simple and powerful entity component system
Loading...
Searching...
No Matches
spinlock.h
1
#pragma once
2
#include "gaia/config/config.h"
3
4
#include <atomic>
5
6
namespace
gaia {
7
namespace
mt {
9
class
GAIA_API
SpinLock
final {
10
std::atomic_int32_t m_value{};
11
12
public
:
13
SpinLock
() =
default
;
14
~SpinLock
() =
default
;
15
SpinLock
(
const
SpinLock
&) =
delete
;
16
SpinLock
& operator=(
const
SpinLock
&) =
delete
;
17
20
bool
try_lock
() {
21
// Attempt to acquire the lock without waiting
22
return
0 == m_value.exchange(1, std::memory_order_acquire);
23
}
24
26
void
lock
() {
27
while
(
true
) {
28
// The value has been changed, we successfully entered the lock
29
if
(0 == m_value.exchange(1, std::memory_order_acquire))
30
break
;
31
32
// Yield until unlocked
33
while
(m_value.load(std::memory_order_relaxed) != 0)
34
GAIA_YIELD_CPU;
35
}
36
}
37
39
void
unlock
() {
40
// Release the lock
41
m_value.store(0, std::memory_order_release);
42
}
43
};
44
}
// namespace mt
45
}
// namespace gaia
gaia::mt::SpinLock
Non-recursive spin lock backed by an atomic flag.
Definition
spinlock.h:9
gaia::mt::SpinLock::lock
void lock()
Spins until the lock is acquired.
Definition
spinlock.h:26
gaia::mt::SpinLock::unlock
void unlock()
Releases the lock.
Definition
spinlock.h:39
gaia::mt::SpinLock::try_lock
bool try_lock()
Attempts to acquire the lock without waiting.
Definition
spinlock.h:20
include
gaia
mt
spinlock.h
Generated by
1.9.8