• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 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 CONDITION_LOCK_H
17 #define CONDITION_LOCK_H
18 
19 #include <mutex>
20 #include <condition_variable>
21 
22 namespace OHOS::ObjectStore {
23 template <typename T>
24 class ConditionLock {
25 public:
ConditionLock()26     explicit ConditionLock() {}
~ConditionLock()27     ~ConditionLock() {}
28 public:
Notify(const T & data)29     void Notify(const T &data)
30     {
31         std::lock_guard<std::mutex> lock(mutex_);
32         data_ = data;
33         isSet_ = true;
34         cv_.notify_one();
35     }
36 
Wait()37     T Wait()
38     {
39         std::unique_lock<std::mutex> lock(mutex_);
40         cv_.wait_for(lock, std::chrono::seconds(INTERVAL), [this]() { return isSet_; });
41         T data = data_;
42         cv_.notify_one();
43         return data;
44     }
45 
Clear()46     void Clear()
47     {
48         std::lock_guard<std::mutex> lock(mutex_);
49         isSet_ = false;
50         cv_.notify_one();
51     }
52 
53 private:
54     bool isSet_ = false;
55     T data_;
56     std::mutex mutex_;
57     std::condition_variable cv_;
58     static constexpr int64_t INTERVAL = 5;
59 };
60 } // namespace OHOS::ObjectStore
61 
62 #endif // CONDITION_LOCK_H
63