1 /*
2  * Copyright (C) 2024 Google, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17 
18 #ifndef PH_MESSAGEQUEUE_H
19 #define PH_MESSAGEQUEUE_H
20 
21 #include <condition_variable>
22 #include <memory>
23 #include <mutex>
24 #include <queue>
25 #include <string>
26 
27 #include "phNxpLog.h"
28 
29 template <typename T>
30 class MessageQueue
31 {
32 public:
MessageQueue(const std::string name)33   MessageQueue(const std::string name) : name_(name) {
34   }
~MessageQueue()35   virtual ~MessageQueue() {
36     clear();
37     NXPLOG_TML_D("MessageQueue %s destroyed", name_.c_str());
38   }
send(std::shared_ptr<T> data)39   void send(std::shared_ptr<T> data) {
40     std::lock_guard<std::mutex> lk(lock_);
41     items_.push(data);
42     cond_.notify_one();
43   }
recv()44   std::shared_ptr<T> recv() {
45     std::unique_lock<std::mutex> lk(lock_);
46     cond_.wait(lk, [this] { return !items_.empty(); });
47     auto ret = items_.front();
48     items_.pop();
49     return ret;
50   }
clear()51   void clear() {
52     cond_.notify_all();
53     std::lock_guard<std::mutex> lk(lock_);
54     items_ = std::queue<std::shared_ptr<T>> ();
55   }
56 private:
57   std::string name_;
58   std::queue<std::shared_ptr<T>> items_;
59   std::mutex lock_;
60   std::condition_variable cond_;
61 };
62 
63 #endif  // _NXP_UWB_MESSAGEQUEUE_H
64