1 /* 2 * Copyright (c) 2021 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 #include <functional> 19 20 namespace DistributedDB { 21 using std::unique_lock; 22 using std::lock_guard; 23 using std::mutex; 24 using std::condition_variable; 25 SemaphoreUtils(int count)26SemaphoreUtils::SemaphoreUtils(int count) 27 : count_(count) 28 {} 29 ~SemaphoreUtils()30SemaphoreUtils::~SemaphoreUtils() 31 {} 32 WaitSemaphore(int waitSecond)33bool SemaphoreUtils::WaitSemaphore(int waitSecond) 34 { 35 unique_lock<mutex> lock(lockMutex_); 36 bool result = cv_.wait_for(lock, std::chrono::seconds(waitSecond), 37 [this] { return CompareCount(); }); 38 if (result == true) { 39 --count_; 40 } 41 return result; 42 } 43 WaitSemaphore()44void SemaphoreUtils::WaitSemaphore() 45 { 46 unique_lock<mutex> lock(lockMutex_); 47 cv_.wait(lock, [this] { return CompareCount(); }); 48 --count_; 49 } 50 SendSemaphore()51void SemaphoreUtils::SendSemaphore() 52 { 53 lock_guard<std::mutex> lock(lockMutex_); 54 count_++; 55 cv_.notify_one(); 56 } 57 CompareCount() const58bool SemaphoreUtils::CompareCount() const 59 { 60 return count_ > 0; 61 } 62 } // namespace DistributedDB 63