CppCommon  1.0.4.1
C++ Common Library
latch.h
Go to the documentation of this file.
1 
9 #ifndef CPPCOMMON_THREADS_LATCH_H
10 #define CPPCOMMON_THREADS_LATCH_H
11 
12 #include "time/timestamp.h"
13 
14 #include <cassert>
15 #include <condition_variable>
16 #include <memory>
17 #include <mutex>
18 
19 namespace CppCommon {
20 
22 
28 class Latch
29 {
30 public:
32 
35  explicit Latch(int threads) noexcept;
36  Latch(const Latch&) = delete;
37  Latch(Latch&&) = delete;
38  ~Latch() = default;
39 
40  Latch& operator=(const Latch&) = delete;
41  Latch& operator=(Latch&&) = delete;
42 
44  int threads() const noexcept { return _threads; }
45 
47 
55  void Reset(int threads) noexcept;
56 
58 
64  void CountDown() noexcept;
65 
67 
74  void CountDownAndWait() noexcept;
75 
77 
82  void Wait() noexcept;
83 
85 
90  bool TryWait() noexcept;
91 
93 
99  bool TryWaitFor(const Timespan& timespan) noexcept;
101 
107  bool TryWaitUntil(const Timestamp& timestamp) noexcept;
108 
109 private:
110  std::mutex _mutex;
111  std::condition_variable _cond;
112  int _generation;
113  int _threads;
114 
115  bool CountDown(std::unique_lock<std::mutex>& lock) noexcept;
116 };
117 
121 } // namespace CppCommon
122 
123 #include "latch.inl"
124 
125 #endif // CPPCOMMON_THREADS_LATCH_H
Latch synchronization primitive.
Definition: latch.h:29
void Reset(int threads) noexcept
Reset the latch with a new threads counter value.
Definition: latch.cpp:13
Latch & operator=(const Latch &)=delete
int threads() const noexcept
Get the count of threads to wait for the latch.
Definition: latch.h:44
bool TryWaitUntil(const Timestamp &timestamp) noexcept
Try to wait for the latch until the given timestamp.
Definition: latch.inl:31
Latch(int threads) noexcept
Default class constructor.
Definition: latch.inl:11
bool TryWait() noexcept
Try to wait for the latch without block.
Definition: latch.cpp:80
void CountDown() noexcept
Countdown the latch.
Definition: latch.cpp:42
Latch & operator=(Latch &&)=delete
bool TryWaitFor(const Timespan &timespan) noexcept
Try to wait for the latch for the given timespan.
Definition: latch.inl:16
~Latch()=default
void CountDownAndWait() noexcept
Countdown the latch.
Definition: latch.cpp:50
Latch(Latch &&)=delete
Latch(const Latch &)=delete
void Wait() noexcept
Wait for the latch.
Definition: latch.cpp:65
C++ Common project definitions.
Definition: token_bucket.h:15
Timestamp definition.