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 #ifndef OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_BLOCK_DATA_H
16 #define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_BLOCK_DATA_H
17 #include <condition_variable>
18 #include <mutex>
19 
20 namespace OHOS {
21 template<typename T>
22 class BlockData {
23 public:
24     explicit BlockData(uint32_t interval, const T &invalid = T()) : INTERVAL(interval), data_(invalid) {}
25 
~BlockData()26     ~BlockData() {}
27 
28 public:
SetValue(const T & data)29     void SetValue(const T &data)
30     {
31         std::lock_guard<std::mutex> lock(mutex_);
32         data_ = data;
33         isSet_ = true;
34         cv_.notify_one();
35     }
36 
GetValue()37     T GetValue()
38     {
39         std::unique_lock<std::mutex> lock(mutex_);
40         cv_.wait_for(lock, std::chrono::seconds(INTERVAL), [this]() {
41             return isSet_;
42         });
43         T data = data_;
44         cv_.notify_one();
45         return data;
46     }
47 
48     void Clear(const T &invalid = T())
49     {
50         std::lock_guard<std::mutex> lock(mutex_);
51         isSet_ = false;
52         data_ = invalid;
53         cv_.notify_one();
54     }
55 
56 private:
57     bool isSet_ = false;
58     const uint32_t INTERVAL;
59     T data_;
60     std::mutex mutex_;
61     std::condition_variable cv_;
62 };
63 } // namespace OHOS
64 #endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_BLOCK_DATA_H