CppCommon  1.0.4.1
C++ Common Library
spin_lock.inl
Go to the documentation of this file.
1 
9 namespace CppCommon {
10 
11 inline bool SpinLock::IsLocked() noexcept
12 {
13  return _lock.load(std::memory_order_acquire);
14 }
15 
16 inline bool SpinLock::TryLock() noexcept
17 {
18  return !_lock.exchange(true, std::memory_order_acquire);
19 }
20 
21 inline 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 
34 inline 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 
50 inline void SpinLock::Lock() noexcept
51 {
52  while (_lock.exchange(true, std::memory_order_acquire));
53 }
54 
55 inline 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.
Definition: token_bucket.h:15