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:
BlockData(uint32_t interval, const T &invalid = T())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 
GetValue(T &data)51     bool GetValue(T &data)
52     {
53         std::unique_lock<std::mutex> lock(mutex_);
54         cv_.wait_for(lock, std::chrono::milliseconds(INTERVAL), [this]() { return isSet_; });
55         data = data_;
56         return isSet_;
57     }
58 
Clear(const T &invalid = T())59     void Clear(const T &invalid = T())
60     {
61         std::lock_guard<std::mutex> lock(mutex_);
62         isSet_ = false;
63         data_ = invalid;
64     }
65 
66 private:
67     bool isSet_ = false;
68     const uint32_t INTERVAL;
69     T data_;
70     std::mutex mutex_;
71     std::condition_variable cv_;
72 };
73 } // namespace MiscServices
74 } // namespace OHOS
75 #endif // OHOS_INPUTMETHOD_IMF_FRAMEWORKS_BLOCK_DATA_H
76