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