1 /* 2 * Copyright (c) 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 16 #ifndef OHOS_INPUTMETHOD_IMF_FRAMEWORKS_BLOCK_DATA_H 17 #define OHOS_INPUTMETHOD_IMF_FRAMEWORKS_BLOCK_DATA_H 18 #include <condition_variable> 19 #include <mutex> 20 21 namespace OHOS { 22 namespace MiscServices { 23 template<typename T> 24 class BlockData { 25 public: INTERVAL(interval)26 explicit BlockData(uint32_t interval, const T &invalid = T()) : INTERVAL(interval), data_(invalid) 27 { 28 } 29 ~BlockData()30 ~BlockData() 31 { 32 } 33 34 public: SetValue(const T & data)35 void SetValue(const T &data) 36 { 37 std::lock_guard<std::mutex> lock(mutex_); 38 data_ = data; 39 isSet_ = true; 40 cv_.notify_one(); 41 } 42 GetValue()43 T GetValue() 44 { 45 std::unique_lock<std::mutex> lock(mutex_); 46 cv_.wait_for(lock, std::chrono::milliseconds(INTERVAL), [this]() { return isSet_; }); 47 T data = data_; 48 return data; 49 } 50 GetValueWithoutTimeout()51 T GetValueWithoutTimeout() 52 { 53 std::unique_lock<std::mutex> lock(mutex_); 54 cv_.wait(lock, [this]() { return isSet_; }); 55 T data = data_; 56 return data; 57 } 58 GetValue(T & data)59 bool GetValue(T &data) 60 { 61 std::unique_lock<std::mutex> lock(mutex_); 62 cv_.wait_for(lock, std::chrono::milliseconds(INTERVAL), [this]() { return isSet_; }); 63 data = data_; 64 return isSet_; 65 } 66 67 void Clear(const T &invalid = T()) 68 { 69 std::lock_guard<std::mutex> lock(mutex_); 70 isSet_ = false; 71 data_ = invalid; 72 } 73 74 private: 75 bool isSet_ = false; 76 const uint32_t INTERVAL; 77 T data_; 78 std::mutex mutex_; 79 std::condition_variable cv_; 80 }; 81 } // namespace MiscServices 82 } // namespace OHOS 83 #endif // OHOS_INPUTMETHOD_IMF_FRAMEWORKS_BLOCK_DATA_H 84