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 "pthread_semaphore.h"
16 #include <memory>
17 #include <ctime>
18
19 namespace {
20 constexpr int NS_PER_SEC = 1000 * 1000 * 1000;
21 }
22
PthreadSemaphore(unsigned int value)23 PthreadSemaphore::PthreadSemaphore(unsigned int value) : value_(value)
24 {
25 pthread_mutex_init(&mutex_, nullptr);
26 pthread_cond_init(&cond_, nullptr);
27 }
28
~PthreadSemaphore()29 PthreadSemaphore::~PthreadSemaphore()
30 {
31 pthread_cond_destroy(&cond_);
32 pthread_mutex_destroy(&mutex_);
33 }
34
Wait()35 bool PthreadSemaphore::Wait()
36 {
37 pthread_mutex_lock(&mutex_);
38 while (value_ == 0) {
39 pthread_cond_wait(&cond_, &mutex_);
40 }
41 --value_;
42 pthread_mutex_unlock(&mutex_);
43 return true;
44 }
45
TryWait()46 bool PthreadSemaphore::TryWait()
47 {
48 pthread_mutex_lock(&mutex_);
49 bool retval = TryWaitLocked();
50 pthread_mutex_unlock(&mutex_);
51 return retval;
52 }
53
TimedWait(int seconds,int nanoSeconds)54 bool PthreadSemaphore::TimedWait(int seconds, int nanoSeconds)
55 {
56 pthread_mutex_lock(&mutex_);
57 if (value_) {
58 struct timespec ts = { 0, 0 };
59 clock_gettime(CLOCK_REALTIME, &ts);
60 ts.tv_sec += seconds;
61 ts.tv_nsec += nanoSeconds;
62 ts.tv_sec += ts.tv_nsec / NS_PER_SEC;
63 ts.tv_nsec %= NS_PER_SEC;
64 pthread_cond_timedwait(&cond_, &mutex_, &ts);
65 }
66 bool retval = TryWaitLocked();
67 pthread_mutex_unlock(&mutex_);
68 return retval;
69 }
70
TryWaitLocked()71 bool PthreadSemaphore::TryWaitLocked()
72 {
73 if (value_ == 0) {
74 return false;
75 }
76 --value_;
77 return true;
78 }
79
Post()80 bool PthreadSemaphore::Post()
81 {
82 pthread_mutex_lock(&mutex_);
83 ++value_;
84 pthread_mutex_unlock(&mutex_);
85 pthread_cond_broadcast(&cond_);
86 return true;
87 }
88
Value() const89 unsigned int PthreadSemaphore::Value() const
90 {
91 pthread_mutex_lock(&mutex_);
92 unsigned int val = value_;
93 pthread_mutex_unlock(&mutex_);
94 return val;
95 }
96
Create(unsigned int value)97 SemaphorePtr PthreadSemaphoreFactory::Create(unsigned int value)
98 {
99 return std::make_shared<PthreadSemaphore>(value);
100 }
101