• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "posix_semaphore.h"
16 #include <memory>
17 #include <ctime>
18 
19 namespace {
20 constexpr int NS_PER_SEC = 1000 * 1000 * 1000;
21 }
22 
PosixSemaphore(unsigned int value)23 PosixSemaphore::PosixSemaphore(unsigned int value)
24 {
25     sem_init(&sem_, 0, value);
26 }
27 
~PosixSemaphore()28 PosixSemaphore::~PosixSemaphore()
29 {
30     sem_destroy(&sem_);
31 }
32 
Wait()33 bool PosixSemaphore::Wait()
34 {
35     return sem_wait(&sem_) == 0;
36 }
37 
TryWait()38 bool PosixSemaphore::TryWait()
39 {
40     return sem_trywait(&sem_) == 0;
41 }
42 
TimedWait(int seconds,int nanoSeconds)43 bool PosixSemaphore::TimedWait(int seconds, int nanoSeconds)
44 {
45     struct timespec ts = { 0, 0 };
46     clock_gettime(CLOCK_REALTIME, &ts);
47     ts.tv_sec += seconds;
48     ts.tv_nsec += nanoSeconds;
49     ts.tv_sec += ts.tv_nsec / NS_PER_SEC;
50     ts.tv_nsec %= NS_PER_SEC;
51     return sem_timedwait(&sem_, &ts) == 0;
52 }
53 
Post()54 bool PosixSemaphore::Post()
55 {
56     return sem_post(&sem_) == 0;
57 }
58 
Value() const59 unsigned PosixSemaphore::Value() const
60 {
61     int value = 0;
62     sem_getvalue(&sem_, &value);
63     return value;
64 }
65 
Create(unsigned int value)66 SemaphorePtr PosixSemaphoreFactory::Create(unsigned int value)
67 {
68     return std::make_shared<PosixSemaphore>(value);
69 }
70