Motorcortex Core  version: 2.7.6
utl_tsqueue.h
1 /*
2  * Developer : Alexey Zakharov (alexey.zakharov@vectioneer.com)
3  * All rights reserved. Copyright (c) 2020 VECTIONEER.
4  */
5 
6 #ifndef MOTORCORTEX_CORE_UTL_TSQUEUE_H
7 #define MOTORCORTEX_CORE_UTL_TSQUEUE_H
8 
9 #include <condition_variable>
10 #include <mutex>
11 #include <queue>
12 
13 template <typename T>
15 public:
16  ThreadSafeQueue() = default;
17 
18  void push(T new_value) {
19  std::lock_guard<std::mutex> lk(mut_);
20  data_queue_.push(std::move(new_value));
21  data_cond_.notify_one();
22  }
23 
24  void waitAndPop(T& value) {
25  std::unique_lock<std::mutex> lk(mut_);
26  data_cond_.wait(lk, [this] { return !data_queue_.empty() || destroy_; });
27  if (!destroy_) {
28  value = std::move(data_queue_.front());
29  data_queue_.pop();
30  }
31  }
32 
33  std::shared_ptr<T> waitAndPop() {
34  std::unique_lock<std::mutex> lk(mut_);
35  data_cond_.wait(lk, [this] { return !data_queue_.empty() || destroy_; });
36  if (!destroy_) {
37  std::shared_ptr<T> res(std::make_shared<T>(std::move(data_queue_.front())));
38  data_queue_.pop();
39  return res;
40  }
41  return nullptr;
42  }
43 
44  bool tryPop(T& value) {
45  std::lock_guard<std::mutex> lk(mut_);
46  if (data_queue_.empty()) {
47  return false;
48  }
49  value = std::move(data_queue_.front());
50  data_queue_.pop();
51  return true;
52  }
53 
54  std::shared_ptr<T> tryPop() {
55  std::lock_guard<std::mutex> lk(mut_);
56  if (data_queue_.empty()) {
57  return std::shared_ptr<T>();
58  }
59  std::shared_ptr<T> res(std::make_shared<T>(std::move(data_queue_.front())));
60  data_queue_.pop();
61  return res;
62  }
63 
64  bool empty() const {
65  std::lock_guard<std::mutex> lk(mut_);
66  return data_queue_.empty();
67  }
68 
69  void destroy() {
70  std::lock_guard<std::mutex> lk(mut_);
71  destroy_ = true;
72  data_cond_.notify_all();
73  }
74 
75 private:
76  mutable std::mutex mut_;
77  std::queue<T> data_queue_;
78  std::condition_variable data_cond_;
79  bool destroy_{false};
80 };
81 
82 #endif // MOTORCORTEX_CORE_UTL_TSQUEUE_H
ThreadSafeQueue
Definition: utl_tsqueue.h:14