• 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 #ifndef SEMAPHORE_EX_H
16 #define SEMAPHORE_EX_H
17 
18 #include "nocopyable.h"
19 
20 #include <iostream>
21 #include <thread>
22 #include <mutex>
23 #include <condition_variable>
24 #include <string>
25 #include <time.h> // timespec since c11
26 
27 namespace OHOS {
28 
29 const int INVALID_SEMA_VALUE = -1;
30 
31 class NamedSemaphore : public NoCopyable {
32 public:
33     NamedSemaphore(size_t);
34     NamedSemaphore(const std::string&, size_t);
35     ~NamedSemaphore();
36 
37     bool Create();
38     bool Unlink();
39 
40     bool Open();
41     bool Close();
42 
43     bool Wait();
44     bool TryWait();
45     bool TimedWait(const struct timespec& ts);
46     bool Post();
47 
48     int GetValue() const;
49 
50 private:
51     std::string name_;
52     int maxCount_;
53     void* sema_;
54     bool named_;
55 };
56 
57 class Semaphore : public NoCopyable {
58 public:
count_(value)59     Semaphore(int value = 1) : count_(value) {}
60     ~Semaphore() = default;
61 
62     void Wait();
63     void Post();
64 
65 private:
66     int count_;
67     std::mutex mutex_;
68     std::condition_variable cv_;
69 };
70 
71 } // OHOS
72 
73 #endif
74 
75