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_BLOCK_QUEUE_H
17 #define OHOS_INPUTMETHOD_BLOCK_QUEUE_H
18 #include <condition_variable>
19 #include <mutex>
20 #include <queue>
21 
22 namespace OHOS {
23 namespace MiscServices {
24 template<typename T> class BlockQueue {
25 public:
BlockQueue(uint32_t timeout)26     explicit BlockQueue(uint32_t timeout) : timeout_(timeout)
27     {
28     }
29 
30     ~BlockQueue() = default;
31 
Pop()32     void Pop()
33     {
34         std::unique_lock<std::mutex> lock(queuesMutex_);
35         queues_.pop();
36         cv_.notify_all();
37     }
38 
Push(const T & data)39     void Push(const T &data)
40     {
41         std::unique_lock<std::mutex> lock(queuesMutex_);
42         queues_.push(data);
43     }
44 
Wait(const T & data)45     void Wait(const T &data)
46     {
47         std::unique_lock<std::mutex> lock(queuesMutex_);
48         cv_.wait_for(lock, std::chrono::milliseconds(timeout_), [&data, this]() { return data == queues_.front(); });
49     }
50 
IsReady(const T & data)51     bool IsReady(const T &data)
52     {
53         std::unique_lock<std::mutex> lock(queuesMutex_);
54         return data == queues_.front();
55     }
56 
GetFront(T & data)57     bool GetFront(T &data)
58     {
59         std::unique_lock<std::mutex> lock(queuesMutex_);
60         if (queues_.empty()) {
61             return false;
62         }
63         data = queues_.front();
64         return true;
65     }
66 
67 private:
68     const uint32_t timeout_;
69     std::mutex queuesMutex_;
70     std::queue<T> queues_;
71     std::condition_variable cv_;
72 };
73 } // namespace MiscServices
74 } // namespace OHOS
75 #endif // OHOS_INPUTMETHOD_BLOCK_QUEUE_H
76