1 /* 2 * Copyright (C) 2022 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef SEMAPHORE_UTILS_H 17 #define SEMAPHORE_UTILS_H 18 19 #include <condition_variable> 20 #include <mutex> 21 #include "base_def.h" 22 23 namespace utility { 24 class Semaphore { 25 public: 26 /** 27 * @brief Construct a new Semaphore object. 28 * 29 * @param val Initial value of the Semaphore. 30 * @since 6 31 */ 32 explicit Semaphore(int val = 1) : count_(val){}; 33 34 /** 35 * @brief Destroy the Semaphore object. 36 * 37 * @since 6 38 */ 39 ~Semaphore() = default; 40 41 /** 42 * @brief Semaphore val reduce 1. 43 * If val after reduce operation is less than 0, 44 * block waiting until other call Post() to increase Semaphore val greater or equal to 0. 45 * 46 * @since 6 47 */ 48 void Wait(); 49 50 /** 51 * @brief Semaphore val try reduce 1. 52 * If val after reduce operation is less than 0, 53 * discard execution, return false. 54 * 55 * @return Success reduce Semaphore val return true, else return false. 56 * @since 6 57 */ 58 bool TryWait(); 59 60 /** 61 * @brief Semaphore val increase 1. 62 * 63 * @since 6 64 */ 65 void Post(); 66 67 private: 68 int count_ {1}; 69 int wakeupnum_ {0}; 70 std::mutex mutex_ {}; 71 std::condition_variable condVar_ {}; 72 73 BT_DISALLOW_COPY_AND_ASSIGN(Semaphore); 74 }; 75 } // namespace utility 76 77 #endif // SEMAPHORE_UTILS_H