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 
16 #include "platform/semaphore/include/i_semaphore.h"
17 
18 #include <condition_variable>
19 #include <mutex>
20 
21 #include "utils/constants/constants.h"
22 #include "utils/inf_cast_impl.h"
23 
24 namespace OHOS {
25 namespace AI {
26 class Semaphore {
27 public:
Semaphore(unsigned int count)28     explicit Semaphore(unsigned int count): count_(count)
29     {
30     }
31 
~Semaphore()32     ~Semaphore()
33     {
34     }
35 
Wait()36     inline void Wait()
37     {
38         std::unique_lock<std::mutex> lock(mutex_);
39         condition_.wait(lock, [&]()->bool { return count_ > 0; });
40         --count_;
41     }
42 
Wait(const int milliSeconds)43     bool Wait(const int milliSeconds)
44     {
45         using milliseconds_type = std::chrono::duration<int, std::milli>;
46         std::unique_lock<std::mutex> lock(mutex_);
47         if (!condition_.wait_for(lock, milliseconds_type(milliSeconds), [&]()->bool { return count_ > 0; })) {
48             return false;
49         }
50         --count_;
51         return true;
52     }
53 
Signal()54     inline void Signal()
55     {
56         std::unique_lock<std::mutex> lock(mutex_);
57         ++count_;
58         condition_.notify_one();
59     }
60 
61 private:
62     unsigned int count_;
63     std::mutex mutex_;
64     std::condition_variable condition_;
65 };
66 
67 DEFINE_IMPL_CLASS_CAST(SemaphoreCast, ISemaphore, Semaphore);
68 
69 class SemaphoreDeleter {
70 public:
operator ()(ISemaphore * p) const71     void operator ()(ISemaphore *p) const
72     {
73         SemaphoreCast::Destroy(p);
74     }
75 };
76 
MakeShared(unsigned int count)77 std::shared_ptr<ISemaphore> ISemaphore::MakeShared(unsigned int count)
78 {
79     std::shared_ptr<ISemaphore> sp(SemaphoreCast::Create(count), SemaphoreDeleter());
80     return sp;
81 }
82 
Wait(const int milliSeconds)83 bool ISemaphore::Wait(const int milliSeconds)
84 {
85     if (milliSeconds <= 0) {
86         SemaphoreCast::Ref(this).Wait();
87         return true;
88     }
89     return SemaphoreCast::Ref(this).Wait(milliSeconds);
90 }
91 
Signal()92 void ISemaphore::Signal()
93 {
94     SemaphoreCast::Ref(this).Signal();
95 }
96 } // namespace AI
97 } // namespace OHOS
98