1 /*
2  * Copyright (c) 2024 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_FFRT_BLOCK_QUEUE_H
17 #define OHOS_INPUTMETHOD_FFRT_BLOCK_QUEUE_H
18 #include <queue>
19 
20 #include "cpp/mutex.h"
21 #include "ffrt.h"
22 
23 namespace OHOS {
24 namespace MiscServices {
25 template<typename T> class FFRTBlockQueue {
26 public:
FFRTBlockQueue(uint32_t timeout)27     explicit FFRTBlockQueue(uint32_t timeout) : timeout_(timeout)
28     {
29     }
30 
31     ~FFRTBlockQueue() = default;
32 
Pop()33     void Pop()
34     {
35         std::unique_lock<ffrt::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<ffrt::mutex> lock(queuesMutex_);
43         queues_.push(data);
44     }
45 
Wait(const T & data)46     void Wait(const T &data)
47     {
48         std::unique_lock<ffrt::mutex> lock(queuesMutex_);
49         cv_.wait_for(lock, std::chrono::milliseconds(timeout_), [&data, this]() { return data == queues_.front(); });
50     }
51 
GetFront(T & data)52     bool GetFront(T &data)
53     {
54         std::unique_lock<ffrt::mutex> lock(queuesMutex_);
55         if (queues_.empty()) {
56             return false;
57         }
58         data = queues_.front();
59         return true;
60     }
61 
62 private:
63     const uint32_t timeout_;
64     ffrt::mutex queuesMutex_;
65     std::queue<T> queues_;
66     ffrt::condition_variable cv_;
67 };
68 } // namespace MiscServices
69 } // namespace OHOS
70 #endif // OHOS_INPUTMETHOD_FFRT_BLOCK_QUEUE_H
71