vsg  1.1.0
VulkanSceneGraph library
Latch.h
1 #pragma once
2 
3 /* <editor-fold desc="MIT License">
4 
5 Copyright(c) 2018 Robert Osfield
6 
7 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
8 
9 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
10 
11 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 
13 </editor-fold> */
14 
15 #include <vsg/core/Inherit.h>
16 
17 #include <condition_variable>
18 #include <mutex>
19 
20 namespace vsg
21 {
22 
24  class Latch : public Inherit<Object, Latch>
25  {
26  public:
27  explicit Latch(int num) :
28  _count(num) {}
29 
30  explicit Latch(size_t num) :
31  Latch(static_cast<int>(num)) {}
32 
33  void set(int num)
34  {
35  if (num == 0)
36  {
37  if (_count.exchange(0) != 0)
38  release();
39  }
40  else
41  {
42  _count = num;
43  }
44  }
45 
46  void count_up()
47  {
48  ++_count;
49  }
50 
51  bool count_down()
52  {
53  if (_count.fetch_sub(1) <= 1)
54  {
55  release();
56  return true;
57  }
58  else
59  {
60  return false;
61  }
62  }
63 
64  bool is_ready() const
65  {
66  return (_count <= 0);
67  }
68 
69  void wait()
70  {
71  std::unique_lock lock(_mutex);
72  while (_count > 0)
73  {
74  _cv.wait(lock);
75  }
76  }
77 
78  virtual void release()
79  {
80  std::unique_lock lock(_mutex);
81  _cv.notify_all();
82  }
83 
84  int count() const { return _count.load(); }
85 
86  protected:
87  virtual ~Latch() {}
88 
89  std::atomic_int _count;
90  std::mutex _mutex;
91  std::condition_variable _cv;
92  };
93  VSG_type_name(vsg::Latch)
94 
95 } // namespace vsg
Definition: Inherit.h:28
Latch provides a means for synchronizing multiple threads that waits for the latch count to be decrem...
Definition: Latch.h:25