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 #include "std_semaphore.h" 16 StdSemaphore(unsigned int value)17StdSemaphore::StdSemaphore(unsigned int value) : value_(value) {} 18 ~StdSemaphore()19StdSemaphore::~StdSemaphore() {} 20 Wait()21bool StdSemaphore::Wait() 22 { 23 std::unique_lock<std::mutex> lock(mutex_); 24 while (value_ == 0) { 25 condVar_.wait(lock); 26 } 27 --value_; 28 return true; 29 } 30 TryWait()31bool StdSemaphore::TryWait() 32 { 33 std::unique_lock<std::mutex> lock(mutex_); 34 return TryWaitLocked(); 35 } 36 TryWaitLocked()37bool StdSemaphore::TryWaitLocked() 38 { 39 if (value_ == 0) { 40 return false; 41 } 42 --value_; 43 return true; 44 } 45 TimedWait(int seconds,int nanoSeconds)46bool StdSemaphore::TimedWait(int seconds, int nanoSeconds) 47 { 48 std::unique_lock<std::mutex> lock(mutex_); 49 if (value_ == 0) { 50 auto timePoint = std::chrono::steady_clock::now(); 51 timePoint += std::chrono::seconds(seconds); 52 timePoint += std::chrono::nanoseconds(nanoSeconds); 53 condVar_.wait_until(lock, timePoint); 54 } 55 return TryWaitLocked(); 56 } 57 Post()58bool StdSemaphore::Post() 59 { 60 { 61 std::unique_lock<std::mutex> lock(mutex_); 62 ++value_; 63 } 64 condVar_.notify_all(); 65 return true; 66 } 67 Value() const68unsigned StdSemaphore::Value() const 69 { 70 return value_; 71 } 72 Create(unsigned int value)73SemaphorePtr StdSemaphoreFactory::Create(unsigned int value) 74 { 75 return std::make_shared<StdSemaphore>(value); 76 } 77