1/*
2 * Copyright (c) Huawei Technologies Co., Ltd. 2021. All rights reserved.
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
19namespace {
20constexpr int NS_PER_SEC = 1000 * 1000 * 1000;
21}
22
23PosixSemaphore::PosixSemaphore(unsigned int value)
24{
25    sem_init(&sem_, 0, value);
26}
27
28PosixSemaphore::~PosixSemaphore()
29{
30    sem_destroy(&sem_);
31}
32
33bool PosixSemaphore::Wait()
34{
35    return sem_wait(&sem_) == 0;
36}
37
38bool PosixSemaphore::TryWait()
39{
40    return sem_trywait(&sem_) == 0;
41}
42
43bool 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
54bool PosixSemaphore::Post()
55{
56    return sem_post(&sem_) == 0;
57}
58
59unsigned PosixSemaphore::Value() const
60{
61    int value = 0;
62    sem_getvalue(&sem_, &value);
63    return value;
64}
65
66SemaphorePtr PosixSemaphoreFactory::Create(unsigned int value)
67{
68    return std::make_shared<PosixSemaphore>(value);
69}
70