CppCommon  1.0.4.1
C++ Common Library
semaphore.h
Go to the documentation of this file.
1 
9 #ifndef CPPCOMMON_THREADS_SEMAPHORE_H
10 #define CPPCOMMON_THREADS_SEMAPHORE_H
11 
12 #include "threads/locker.h"
13 #include "time/timestamp.h"
14 
15 #include <memory>
16 
17 namespace CppCommon {
18 
20 
29 class Semaphore
30 {
31 public:
33 
36  explicit Semaphore(int resources);
37  Semaphore(const Semaphore&) = delete;
38  Semaphore(Semaphore&& semaphore) = delete;
39  ~Semaphore();
40 
41  Semaphore& operator=(const Semaphore&) = delete;
42  Semaphore& operator=(Semaphore&& semaphore) = delete;
43 
45  int resources() const noexcept;
46 
48 
53  bool TryLock();
54 
56 
62  bool TryLockFor(const Timespan& timespan);
64 
70  bool TryLockUntil(const UtcTimestamp& timestamp)
71  { return TryLockFor(timestamp - UtcTimestamp()); }
72 
74 
77  void Lock();
78 
80 
83  void Unlock();
84 
85 private:
86  class Impl;
87 
88  Impl& impl() noexcept { return reinterpret_cast<Impl&>(_storage); }
89  const Impl& impl() const noexcept { return reinterpret_cast<Impl const&>(_storage); }
90 
91  static const size_t StorageSize = 40;
92  static const size_t StorageAlign = 8;
93  alignas(StorageAlign) std::byte _storage[StorageSize];
94 };
95 
98 } // namespace CppCommon
99 
100 #endif // CPPCOMMON_THREADS_SEMAPHORE_H
Semaphore synchronization primitive.
Definition: semaphore.h:30
Semaphore(int resources)
Default class constructor.
Definition: semaphore.cpp:156
bool TryLock()
Try to acquire semaphore without block.
Definition: semaphore.cpp:175
Semaphore(const Semaphore &)=delete
Semaphore & operator=(const Semaphore &)=delete
bool TryLockFor(const Timespan &timespan)
Try to acquire semaphore for the given timespan.
Definition: semaphore.cpp:176
int resources() const noexcept
Get the semaphore resources counter.
Definition: semaphore.cpp:173
Semaphore & operator=(Semaphore &&semaphore)=delete
Semaphore(Semaphore &&semaphore)=delete
bool TryLockUntil(const UtcTimestamp &timestamp)
Try to acquire semaphore until the given timestamp.
Definition: semaphore.h:70
void Unlock()
Release semaphore.
Definition: semaphore.cpp:179
void Lock()
Acquire semaphore with block.
Definition: semaphore.cpp:178
UTC timestamp.
Definition: timestamp.h:248
Locker synchronization primitive definition.
C++ Common project definitions.
Definition: token_bucket.h:15
Timestamp definition.