• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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:
INTERVAL(interval)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(T & data)34     void SetValue(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         isTimeOut_ = !isSet_;
47         T data = data_;
48         return data;
49     }
50 
51     void Clear(const T &invalid = T())
52     {
53         std::lock_guard<std::mutex> lock(mutex_);
54         isSet_ = false;
55         data_ = invalid;
56     }
57 
IsTimeOut()58     bool IsTimeOut()
59     {
60         return isTimeOut_;
61     }
62 
63 private:
64     bool isSet_ = false;
65     const uint32_t INTERVAL;
66     T data_;
67     bool isTimeOut_{ false };
68     std::mutex mutex_;
69     std::condition_variable cv_;
70 };
71 } // namespace MiscServices
72 } // namespace OHOS
73 #endif // OHOS_INPUTMETHOD_IMF_FRAMEWORKS_BLOCK_DATA_H
74