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