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