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 namespace OHOS { 20 template<typename T> 21 class BlockObject { 22 public: 23 explicit BlockObject(uint32_t interval, const T &invalid = T()) : interval_(interval), data_(invalid) 24 { 25 } 26 ~BlockObject() = default; 27 SetValue(T data)28 void SetValue(T data) 29 { 30 std::lock_guard<std::mutex> lock(mutex_); 31 data_ = std::move(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, std::chrono::milliseconds(interval_), [this]() { return isSet_; }); 40 isSet_ = false; 41 T data = std::move(data_); 42 cv_.notify_one(); 43 return data; 44 } 45 SetInterval(uint32_t interval)46 void SetInterval(uint32_t interval) 47 { 48 interval_ = interval; 49 } 50 51 private: 52 uint32_t interval_; 53 bool isSet_ = false; 54 std::mutex mutex_; 55 std::condition_variable cv_; 56 T data_; 57 }; 58 } // namespace OHOS 59 60 #endif // OHOS_DISTRIBUTED_FRAMEWORK_COMMON_BLOCK_OBJECT_H 61