CppCommon  1.0.4.1
C++ Common Library
latch.cpp
Go to the documentation of this file.
1 
9 #include "threads/latch.h"
10 
11 namespace CppCommon {
12 
13 void Latch::Reset(int threads) noexcept
14 {
15  assert((threads > 0) && "Latch threads counter must be greater than zero!");
16 
17  std::scoped_lock lock(_mutex);
18 
19  // Reset the latch threads counter with a new value
20  _threads = threads;
21 }
22 
23 bool Latch::CountDown(std::unique_lock<std::mutex>& lock) noexcept
24 {
25  // Count down the latch threads counter and check its value
26  if (--_threads == 0)
27  {
28  // Increase the current latch generation
29  ++_generation;
30 
31  // Notify all waiting threads
32  _cond.notify_all();
33 
34  // Wait for the next latch generation
35  return true;
36  }
37 
38  // Notify each of remaining threads
39  return false;
40 }
41 
42 void Latch::CountDown() noexcept
43 {
44  std::unique_lock<std::mutex> lock(_mutex);
45 
46  // Count down the latch threads counter
47  CountDown(lock);
48 }
49 
50 void Latch::CountDownAndWait() noexcept
51 {
52  std::unique_lock<std::mutex> lock(_mutex);
53 
54  // Remember the current latch generation
55  int generation = _generation;
56 
57  // Count down the latch threads counter
58  if (CountDown(lock))
59  return;
60 
61  // Wait for the next latch generation
62  _cond.wait(lock, [&, this]() { return generation != _generation; });
63 }
64 
65 void Latch::Wait() noexcept
66 {
67  std::unique_lock<std::mutex> lock(_mutex);
68 
69  // Check the latch threads counter value
70  if (_threads == 0)
71  return;
72 
73  // Remember the current latch generation
74  int generation = _generation;
75 
76  // Wait for the next latch generation
77  _cond.wait(lock, [&, this]() { return generation != _generation; });
78 }
79 
80 bool Latch::TryWait() noexcept
81 {
82  std::unique_lock<std::mutex> lock(_mutex);
83 
84  // Check the latch threads counter value
85  return (_threads == 0);
86 }
87 
88 } // namespace CppCommon
void Reset(int threads) noexcept
Reset the latch with a new threads counter value.
Definition: latch.cpp:13
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
void CountDownAndWait() noexcept
Countdown the latch.
Definition: latch.cpp:50
void Wait() noexcept
Wait for the latch.
Definition: latch.cpp:65
Latch synchronization primitive definition.
C++ Common project definitions.
Definition: token_bucket.h:15