CppCommon  1.0.4.1
C++ Common Library
spin_lock.h
Go to the documentation of this file.
1 
9 #ifndef CPPCOMMON_THREADS_SPIN_LOCK_H
10 #define CPPCOMMON_THREADS_SPIN_LOCK_H
11 
12 #include "threads/locker.h"
13 #include "time/timestamp.h"
14 
15 #include <atomic>
16 
17 namespace CppCommon {
18 
20 
29 class SpinLock
30 {
31 public:
32  SpinLock() noexcept : _lock(false) {}
33  SpinLock(const SpinLock&) = delete;
34  SpinLock(SpinLock&&) = delete;
35  ~SpinLock() = default;
36 
37  SpinLock& operator=(const SpinLock&) = delete;
38  SpinLock& operator=(SpinLock&&) = delete;
39 
41 
46  bool IsLocked() noexcept;
47 
49 
54  bool TryLock() noexcept;
55 
57 
63  bool TryLockSpin(int64_t spin) noexcept;
64 
66 
72  bool TryLockFor(const Timespan& timespan) noexcept;
74 
80  bool TryLockUntil(const UtcTimestamp& timestamp) noexcept
81  { return TryLockFor(timestamp - UtcTimestamp()); }
82 
84 
87  void Lock() noexcept;
88 
90 
93  void Unlock() noexcept;
94 
95 private:
96  std::atomic<bool> _lock;
97 };
98 
101 } // namespace CppCommon
102 
103 #include "spin_lock.inl"
104 
105 #endif // CPPCOMMON_THREADS_SPIN_LOCK_H
Spin-lock synchronization primitive.
Definition: spin_lock.h:30
SpinLock & operator=(SpinLock &&)=delete
void Unlock() noexcept
Release spin-lock.
Definition: spin_lock.inl:55
SpinLock() noexcept
Definition: spin_lock.h:32
bool TryLockUntil(const UtcTimestamp &timestamp) noexcept
Try to acquire spin-lock until the given timestamp.
Definition: spin_lock.h:80
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
SpinLock(const SpinLock &)=delete
SpinLock & operator=(const SpinLock &)=delete
SpinLock(SpinLock &&)=delete
bool TryLockFor(const Timespan &timespan) noexcept
Try to acquire spin-lock for the given timespan.
Definition: spin_lock.inl:34
UTC timestamp.
Definition: timestamp.h:248
Locker synchronization primitive definition.
C++ Common project definitions.
Definition: token_bucket.h:15
Timestamp definition.