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 #ifndef WIFI_DIRECT_EVENT_QUEUE_H
16 #define WIFI_DIRECT_EVENT_QUEUE_H
17 
18 #include <queue>
19 #include <mutex>
20 #include <memory>
21 #include <condition_variable>
22 #include "wifi_direct_event_base.h"
23 #include "wifi_direct_event_wrapper.h"
24 
25 namespace OHOS::SoftBus {
26 class WifiDirectEventQueue {
27 public:
28     template<typename Content>
Push(const Content & content)29     void Push(const Content &content)
30     {
31         std::lock_guard<std::mutex> lk(m_);
32         queue_.push_back(std::make_shared<WifiDirectEventWrapper<Content>>(content));
33         c_.notify_all();
34     }
35 
WaitAndPop()36     std::shared_ptr<WifiDirectEventBase> WaitAndPop()
37     {
38         std::unique_lock<std::mutex> lk(m_);
39         c_.wait(lk, [&] { return !queue_.empty(); });
40         auto res = queue_.front();
41         queue_.pop_front();
42         return res;
43     }
44 
45     using Handler = std::function<void(std::shared_ptr<WifiDirectEventBase> &)>;
Process(const Handler & handler)46     void Process(const Handler &handler)
47     {
48         std::lock_guard<std::mutex> lk(m_);
49         for (auto it = queue_.rbegin(); it != queue_.rend(); it++) {
50             handler(*it);
51         }
52     }
53 
Clear()54     void Clear()
55     {
56         std::lock_guard<std::mutex> lk(m_);
57         queue_.clear();
58     }
59 
60 private:
61     std::mutex m_;
62     std::condition_variable c_;
63     std::deque<std::shared_ptr<WifiDirectEventBase>> queue_;
64 };
65 }
66 #endif
67