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 #include "semaphore_utils.h" 17 18 namespace utility { Wait()19void Semaphore::Wait() 20 { 21 std::unique_lock<std::mutex> lock(mutex_); 22 count_--; 23 if (count_ < 0) { 24 condVar_.wait(lock, [&]() -> bool { return wakeupnum_ > 0; }); 25 wakeupnum_--; 26 } 27 } 28 TryWait()29bool Semaphore::TryWait() 30 { 31 std::unique_lock<std::mutex> lock(mutex_); 32 if (count_ <= 0) { 33 return false; 34 } else { 35 count_--; 36 return true; 37 } 38 } 39 Post()40void Semaphore::Post() 41 { 42 std::lock_guard<std::mutex> lock(mutex_); 43 count_++; 44 if (count_ <= 0) { 45 wakeupnum_++; 46 condVar_.notify_one(); 47 } 48 } 49 } // namespace utility