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