Queue.hpp 910 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #ifndef QUEUE_H
  2. #define QUEUE_H
  3. #include <mutex>
  4. #include <queue>
  5. #include <condition_variable>
  6. namespace Util {
  7. using std::queue;
  8. template< class T >
  9. class Queue
  10. {
  11. public:
  12. Queue() {}
  13. virtual ~Queue() {}
  14. void push(T message)
  15. {
  16. std::lock_guard< std::mutex > lock(mutex_);
  17. itsQueue_.push(message);
  18. notifier_.notify_one();
  19. }
  20. void pop(T& message)
  21. {
  22. std::unique_lock< std::mutex > lock(mutex_);
  23. //predicate which returns ​false if the waiting should be continued.
  24. //So waiting for something to be added to the queue..
  25. notifier_.wait(lock, [this](){ return !itsQueue_.empty(); });
  26. message = itsQueue_.front();
  27. itsQueue_.pop();
  28. }
  29. private:
  30. queue<T> itsQueue_;
  31. mutable std::mutex mutex_;
  32. std::condition_variable notifier_;
  33. };
  34. } // Util
  35. #endif /* QUEUE_H */