1 /*
2  * Copyright (C) 2021 The Android Open Source Project
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 <condition_variable>
20 #include <functional>
21 #include <memory>
22 #include <mutex>
23 
24 namespace cuttlefish {
25 class Semaphore {
26  public:
27   Semaphore(const unsigned int init_val = 0, const unsigned int cap = 30000)
28       : count_{init_val}, capacity_{cap} {}
29 
SemWait()30   void SemWait() {
31     std::unique_lock<std::mutex> lock(mtx_);
32     resoure_cv_.wait(lock, [this]() -> bool { return count_ > 0; });
33     --count_;
34     room_cv_.notify_one();
35   }
36 
SemPost()37   void SemPost() {
38     std::unique_lock<std::mutex> lock(mtx_);
39     room_cv_.wait(lock, [this]() -> bool { return count_ < capacity_; });
40     ++count_;
41     resoure_cv_.notify_one();
42   }
43 
44  private:
45   std::mutex mtx_;
46   std::condition_variable resoure_cv_;
47   std::condition_variable room_cv_;
48   unsigned int count_;
49   const unsigned int capacity_;  // inclusive upper limit
50 };
51 
52 }  // namespace cuttlefish
53