libdoip  0.1.0
DoIP (Diagnostics over Internet Protocol) ISO 13400 C++17 Library
ThreadSafeQueue.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include <queue>
4 #include <mutex>
5 #include <condition_variable>
6 #include <chrono>
7 
8 template<typename T>
10 private:
11  std::queue<T> queue_;
12  mutable std::mutex mutex_;
13  std::condition_variable cv_;
14  bool stopped_ = false;
15 
16 public:
17  void push(T item) {
18  {
19  std::lock_guard<std::mutex> lock(mutex_);
20  if (stopped_) return;
21  queue_.push(std::move(item));
22  }
23  cv_.notify_one();
24  }
25 
26  bool pop(T& item, std::chrono::milliseconds timeout = std::chrono::milliseconds(100)) {
27  std::unique_lock<std::mutex> lock(mutex_);
28 
29  if (!cv_.wait_for(lock, timeout, [this] {
30  return !queue_.empty() || stopped_;
31  })) {
32  return false; // Timeout
33  }
34 
35  if (stopped_ && queue_.empty()) {
36  return false;
37  }
38 
39  item = std::move(queue_.front());
40  queue_.pop();
41  return true;
42  }
43 
44  void stop() {
45  {
46  std::lock_guard<std::mutex> lock(mutex_);
47  stopped_ = true;
48  }
49  cv_.notify_all();
50  }
51 
52  size_t size() const {
53  std::lock_guard<std::mutex> lock(mutex_);
54  return queue_.size();
55  }
56 };
void push(T item)
bool pop(T &item, std::chrono::milliseconds timeout=std::chrono::milliseconds(100))
size_t size() const