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 22namespace OHOS { 23namespace MiscServices { 24template<typename T> 25class BlockQueue { 26public: 27 explicit BlockQueue(uint32_t timeout) : timeout_(timeout) 28 { 29 } 30 31 ~BlockQueue() = default; 32 33 void Pop() 34 { 35 std::unique_lock<std::mutex> lock(queuesMutex_); 36 queues_.pop(); 37 cv_.notify_all(); 38 } 39 40 void Push(const T &data) 41 { 42 std::unique_lock<std::mutex> lock(queuesMutex_); 43 queues_.push(data); 44 } 45 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 52 bool IsReady(const T &data) 53 { 54 std::unique_lock<std::mutex> lock(queuesMutex_); 55 return data == queues_.front(); 56 } 57 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 68private: 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