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