CppCommon 1.0.5.0
C++ Common Library
Loading...
Searching...
No Matches
spin_lock.inl
Go to the documentation of this file.
1
9namespace CppCommon {
10
11inline bool SpinLock::IsLocked() noexcept
12{
13 return _lock.load(std::memory_order_acquire);
14}
15
16inline bool SpinLock::TryLock() noexcept
17{
18 return !_lock.exchange(true, std::memory_order_acquire);
19}
20
21inline bool SpinLock::TryLockSpin(int64_t spin) noexcept
22{
23 // Try to acquire spin-lock at least one time
24 do
25 {
26 if (TryLock())
27 return true;
28 } while (spin-- > 0);
29
30 // Failed to acquire spin-lock
31 return false;
32}
33
34inline bool SpinLock::TryLockFor(const Timespan& timespan) noexcept
35{
36 // Calculate a finish timestamp
37 Timestamp finish = NanoTimestamp() + timespan;
38
39 // Try to acquire spin-lock at least one time
40 do
41 {
42 if (TryLock())
43 return true;
44 } while (NanoTimestamp() < finish);
45
46 // Failed to acquire spin-lock
47 return false;
48}
49
50inline void SpinLock::Lock() noexcept
51{
52 while (_lock.exchange(true, std::memory_order_acquire));
53}
54
55inline void SpinLock::Unlock() noexcept
56{
57 _lock.store(false, std::memory_order_release);
58}
59
60} // namespace CppCommon
High resolution timestamp.
Definition timestamp.h:272
void Unlock() noexcept
Release spin-lock.
Definition spin_lock.inl:55
bool TryLock() noexcept
Try to acquire spin-lock without block.
Definition spin_lock.inl:16
void Lock() noexcept
Acquire spin-lock with block.
Definition spin_lock.inl:50
bool TryLockSpin(int64_t spin) noexcept
Try to acquire spin-lock for the given spin count.
Definition spin_lock.inl:21
bool IsLocked() noexcept
Is already locked?
Definition spin_lock.inl:11
bool TryLockFor(const Timespan &timespan) noexcept
Try to acquire spin-lock for the given timespan.
Definition spin_lock.inl:34
C++ Common project definitions.