CUBRID Engine  latest
semaphore.hpp
Go to the documentation of this file.
1 /*
2  * Copyright 2008 Search Solution Corporation
3  * Copyright 2016 CUBRID Corporation
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18 
19 /*
20  * semaphore.hpp - interface of file & line location
21  */
22 
23 #ifndef _SEMAPHORE_HPP_
24 #define _SEMAPHORE_HPP_
25 
26 #include <condition_variable>
27 #include <mutex>
28 
29 namespace cubsync
30 {
31  /*
32  *
33  * Usage :
34  * semaphore<boolean> s (false);
35  * s.signal (true);
36  * s.wait (true);
37  *
38  * semaphore<int> s (0);
39  * s.signal (2);
40  * s.wait (2);
41  *
42  */
43  template <typename T>
44  class semaphore
45  {
46  private:
47  T value;
48 
50  std::condition_variable m_cond_var;
51 
52  public:
53  semaphore (const T &init_value)
54  {
55  value = init_value;
56  }
57 
58  void signal (const T &new_value)
59  {
60  std::unique_lock<std::mutex> ulock (m_mutex);
61  value = new_value;
62  ulock.unlock ();
63  m_cond_var.notify_all ();
64  }
65 
66  void wait (const T &required_value)
67  {
68  if (value == required_value)
69  {
70  return;
71  }
72 
73  std::unique_lock<std::mutex> ulock (m_mutex);
74  m_cond_var.wait (ulock, [this, required_value] { return value == required_value;});
75  }
76  };
77 
79  {
80  private:
82 
83  public:
84 
86  m_semaphore (false)
87  {
88  }
89 
90  void set ()
91  {
92  m_semaphore.signal (true);
93  }
94 
95  void clear ()
96  {
97  m_semaphore.signal (false);
98  }
99 
100  void wait ()
101  {
102  m_semaphore.wait (true);
103  }
104  };
105 
106 } // namespace cubsync
107 
108 #endif // _SEMAPHORE_HPP_
semaphore< bool > m_semaphore
Definition: semaphore.hpp:81
static API_MUTEX mutex
Definition: api_util.c:72
std::mutex m_mutex
Definition: semaphore.hpp:49
semaphore(const T &init_value)
Definition: semaphore.hpp:53
void signal(const T &new_value)
Definition: semaphore.hpp:58
void wait(const T &required_value)
Definition: semaphore.hpp:66
std::condition_variable m_cond_var
Definition: semaphore.hpp:50