vsg  1.1.0
VulkanSceneGraph library
Barrier.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 
19 namespace vsg
20 {
21 
23  class Barrier : public Inherit<Object, Barrier>
24  {
25  public:
26  explicit Barrier(uint32_t num_thread) :
27  _num_threads(num_thread),
28  _num_arrived(0),
29  _phase(0) {}
30 
31  Barrier(const Barrier&) = delete;
32  Barrier& operator=(const Barrier&) = delete;
33 
36  {
37  std::unique_lock lock(_mutex);
38  if (++_num_arrived == _num_threads)
39  {
40  _release();
41  }
42  else
43  {
44  auto my_phase = _phase;
45  _cv.wait(lock, [this, my_phase]() { return this->_phase != my_phase; });
46  }
47  }
48 
51  {
52  std::unique_lock lock(_mutex);
53  if (++_num_arrived == _num_threads)
54  {
55  _release();
56  }
57  }
58 
59  protected:
60  virtual ~Barrier() {}
61 
62  void _release()
63  {
64  _num_arrived = 0;
65  ++_phase;
66  _cv.notify_all();
67  }
68 
69  const uint32_t _num_threads;
70  uint32_t _num_arrived;
71  uint32_t _phase;
72 
73  std::mutex _mutex;
74  std::condition_variable _cv;
75  };
76  VSG_type_name(vsg::Barrier);
77 
78 } // namespace vsg
Barrier provides a means for synchronizing multiple threads that all release together once specified ...
Definition: Barrier.h:24
void arrive_and_drop()
increment the arrived count and release the barrier if count matches number of threads to arrive,...
Definition: Barrier.h:50
void arrive_and_wait()
increment the arrived count and release the barrier if count matches number of threads to arrive othe...
Definition: Barrier.h:35
Definition: Inherit.h:28