OmniSciDB  72c90bc290
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
BinarySemaphore.h
Go to the documentation of this file.
1 /*
2  * Copyright 2022 HEAVY.AI, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include <chrono>
20 #include <condition_variable>
21 #include <mutex>
22 
23 namespace SemaphoreShim_Namespace {
24 
33  public:
42  inline void try_acquire() {
43  std::unique_lock<std::mutex> state_lock(state_mutex_);
44  condition_.wait(state_lock, [&is_ready = is_ready_] { return is_ready; });
45  }
46 
62  inline bool try_acquire_for(const size_t max_wait_in_ms) {
63  std::unique_lock<std::mutex> state_lock(state_mutex_);
64  return condition_.wait_for(state_lock,
65  std::chrono::milliseconds(max_wait_in_ms),
66  [&is_ready = is_ready_]() { return is_ready; });
67  }
68 
74  inline void release() {
75  std::unique_lock<std::mutex> state_lock(state_mutex_);
76  is_ready_ = true;
77  // notify the waiting thread
78  condition_.notify_one();
79  }
80 
86  inline void reset() {
87  std::unique_lock<std::mutex> state_lock(state_mutex_);
88  is_ready_ = false;
89  }
90 
91  inline void set_ready() {
92  std::unique_lock<std::mutex> state_lock(state_mutex_);
93  is_ready_ = true;
94  }
95 
96  private:
97  bool is_ready_{false};
98  std::mutex state_mutex_;
99  std::condition_variable condition_;
100 };
101 
102 } // namespace SemaphoreShim_Namespace
void try_acquire()
Blocks calling thread until it can acquire the semaphore, i.e. release is called by another thread...
bool try_acquire_for(const size_t max_wait_in_ms)
Blocks calling thread until it can acquire the semaphore, i.e. release is called by another thread...
void release()
Sets internal is_ready variable to true, allowing another thread waiting for the semaphore to proceed...
void reset()
Resets the semaphore&#39;s ready condition to false.
Utility type that implemnts behavior of a blocking binary semaphore, with an optional timeout...