1 /*
2  * Copyright (C) 2024-2024 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 #ifndef NET_MANAGER_BASE_TINY_COUNT_DOWN_LATCH_H
17 #define NET_MANAGER_BASE_TINY_COUNT_DOWN_LATCH_H
18 
19 #include <mutex>
20 #include <condition_variable>
21 #include <chrono>
22 
23 namespace OHOS {
24 namespace NetManagerStandard {
25 
26 class TinyCountDownLatch {
27 public:
28     explicit TinyCountDownLatch(int32_t count);
29     void CountDown();
30     int32_t GetCount();
31     void Await();
32     template<class Rep, class Period>
Await(const std::chrono::duration<Rep,Period> & time)33     bool Await(const std::chrono::duration<Rep, Period>& time)
34     {
35         std::unique_lock<std::mutex> lk(mtx_);
36         if (count_ > 0) {
37             return conditionVar_.wait_for(lk, time, [this] { return count_ == 0; });
38         }
39         return true;
40     }
41 
42 private:
43     std::mutex mtx_;
44     std::condition_variable conditionVar_;
45     int32_t count_ = 0;
46 };
47 } // NetManagerStandard
48 } // OHOS
49 #endif