Android-cuttlefish cvd tool
semaphore.h
Go to the documentation of this file.
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 <mutex>
21
22namespace cuttlefish {
23class Semaphore {
24 public:
25 Semaphore(const unsigned int init_val = 0, const unsigned int cap = 30000)
26 : count_{init_val}, capacity_{cap} {}
27
28 void SemWait() {
29 std::unique_lock<std::mutex> lock(mtx_);
30 resoure_cv_.wait(lock, [this]() -> bool { return count_ > 0; });
31 --count_;
32 room_cv_.notify_one();
33 }
34
35 void SemPost() {
36 std::unique_lock<std::mutex> lock(mtx_);
37 room_cv_.wait(lock, [this]() -> bool { return count_ < capacity_; });
38 ++count_;
39 resoure_cv_.notify_one();
40 }
41
42 private:
43 std::mutex mtx_;
44 std::condition_variable resoure_cv_;
45 std::condition_variable room_cv_;
46 unsigned int count_;
47 const unsigned int capacity_; // inclusive upper limit
48};
49
50} // namespace cuttlefish
Definition: semaphore.h:23
const unsigned int capacity_
Definition: semaphore.h:47
void SemPost()
Definition: semaphore.h:35
void SemWait()
Definition: semaphore.h:28
std::condition_variable room_cv_
Definition: semaphore.h:45
unsigned int count_
Definition: semaphore.h:46
std::mutex mtx_
Definition: semaphore.h:43
std::condition_variable resoure_cv_
Definition: semaphore.h:44
Semaphore(const unsigned int init_val=0, const unsigned int cap=30000)
Definition: semaphore.h:25
Definition: alloc_utils.cpp:23