fork download
  1. template<typename T>
  2. class msg_queue
  3. {
  4. public:
  5. // preventing implicit generation of move constructor
  6. ~msg_queue() {}
  7.  
  8. void post(T&& msg)
  9. {
  10. std::lock_guard<std::mutex> lock(mtx);
  11. queue.push_front(std::move(msg));
  12. cond.notify_one();
  13. }
  14.  
  15. bool wait_for(T& msg, std::chrono::milliseconds time)
  16. {
  17. std::unique_lock<std::mutex> lock(mtx);
  18. bool b = cond.wait_for(lock, time, [this]{return !queue.empty(); });
  19. if (b)
  20. {
  21. msg = std::move(queue.back());
  22. queue.pop_back();
  23. return true;
  24. }
  25. else
  26. {
  27. return false;
  28. }
  29. }
  30.  
  31. unsigned int size()
  32. {
  33. std::lock_guard<std::mutex> lock(mtx);
  34. return queue.size();
  35. }
  36.  
  37. void clear()
  38. {
  39. std::lock_guard<std::mutex> lock(mtx);
  40. queue.clear();
  41. }
  42.  
  43. private:
  44. std::deque<T> queue;
  45. std::condition_variable cond;
  46. std::mutex mtx;
  47. };
  48.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty