CppCommon  1.0.4.1
C++ Common Library
named_semaphore.h
Go to the documentation of this file.
1 
9 #ifndef CPPCOMMON_THREADS_NAMED_SEMAPHORE_H
10 #define CPPCOMMON_THREADS_NAMED_SEMAPHORE_H
11 
12 #include "threads/locker.h"
13 #include "time/timestamp.h"
14 
15 #include <memory>
16 #include <string>
17 
18 namespace CppCommon {
19 
21 
30 {
31 public:
33 
37  explicit NamedSemaphore(const std::string& name, int resources);
38  NamedSemaphore(const NamedSemaphore&) = delete;
39  NamedSemaphore(NamedSemaphore&& semaphore) = delete;
41 
43  NamedSemaphore& operator=(NamedSemaphore&& semaphore) = delete;
44 
46  const std::string& name() const;
48  int resources() const noexcept;
49 
51 
56  bool TryLock();
57 
59 
65  bool TryLockFor(const Timespan& timespan);
67 
73  bool TryLockUntil(const UtcTimestamp& timestamp)
74  { return TryLockFor(timestamp - UtcTimestamp()); }
75 
77 
80  void Lock();
81 
83 
86  void Unlock();
87 
88 private:
89  class Impl;
90 
91  Impl& impl() noexcept { return reinterpret_cast<Impl&>(_storage); }
92  const Impl& impl() const noexcept { return reinterpret_cast<Impl const&>(_storage); }
93 
94  static const size_t StorageSize = 56;
95  static const size_t StorageAlign = 8;
96  alignas(StorageAlign) std::byte _storage[StorageSize];
97 };
98 
101 } // namespace CppCommon
102 
103 #endif // CPPCOMMON_THREADS_NAMED_SEMAPHORE_H
Named semaphore synchronization primitive.
NamedSemaphore & operator=(NamedSemaphore &&semaphore)=delete
NamedSemaphore(const std::string &name, int resources)
Default class constructor.
NamedSemaphore & operator=(const NamedSemaphore &)=delete
NamedSemaphore(NamedSemaphore &&semaphore)=delete
int resources() const noexcept
Get the semaphore resources counter.
bool TryLockFor(const Timespan &timespan)
Try to acquire semaphore for the given timespan.
void Unlock()
Release semaphore.
const std::string & name() const
Get the semaphore name.
bool TryLockUntil(const UtcTimestamp &timestamp)
Try to acquire semaphore until the given timestamp.
void Lock()
Acquire semaphore with block.
bool TryLock()
Try to acquire semaphore without block.
NamedSemaphore(const NamedSemaphore &)=delete
UTC timestamp.
Definition: timestamp.h:248
Locker synchronization primitive definition.
C++ Common project definitions.
Definition: token_bucket.h:15
Timestamp definition.