fork download
  1. #ifndef SYNC_H
  2. #define SYNC_H
  3.  
  4. #include <basic/queue.h>
  5. #include <boost/thread.hpp>
  6.  
  7. namespace af {
  8. namespace sync {
  9.  
  10. template<typename T>
  11. struct queue
  12. {
  13. // for convenient
  14. typedef typename af::basic::queue<T> container;
  15.  
  16. struct monitor_t
  17. {
  18. monitor_t() : q_(0) {};
  19. monitor_t(monitor_t& m) : q_(m.q_) {}
  20. ~monitor_t() {}
  21.  
  22. template<typename F>
  23. void operator()(F& f) const
  24. {
  25. boost::lock_guard<boost::mutex> lock(q_->m_);
  26. q_->c_.notify_one();
  27. f(q_->q_);
  28. }
  29.  
  30. private:
  31. queue* q_;
  32. // for setting reference
  33. friend monitor_t queue::monitor();
  34.  
  35. };
  36.  
  37. queue() : q_() {}
  38.  
  39. bool empty() const
  40. {
  41. boost::lock_guard<boost::mutex> lock(m_);
  42. return q_.empty();
  43. }
  44.  
  45. size_t size() const
  46. {
  47. boost::lock_guard<boost::mutex> lock(m_);
  48. return q_.size();
  49. }
  50.  
  51. bool pop(T& msg, unsigned int ms)
  52. {
  53. boost::system_time const timeout
  54. = boost::get_system_time()
  55. + boost::posix_time::milliseconds(ms);
  56. boost::unique_lock<boost::mutex> lock(m_);
  57. while( q_.empty())
  58. {
  59. if (!c_.timed_wait(lock, timeout))
  60. return false;
  61. }
  62.  
  63. q_.pop(msg);
  64. return true;
  65. }
  66.  
  67. // consumes msg and moves it into the queue
  68. void push(T& msg)
  69. {
  70. boost::lock_guard<boost::mutex> lock(m_);
  71. q_.push(msg);
  72. c_.notify_one();
  73. }
  74.  
  75. void clear()
  76. {
  77. boost::lock_guard<boost::mutex> lock(m_);
  78. q_.clear();
  79. }
  80.  
  81. monitor_t monitor()
  82. {
  83. monitor_t tmp;
  84. tmp.q_ = this;
  85. return tmp;
  86. }
  87.  
  88. ~queue()
  89. {
  90. clear();
  91. }
  92.  
  93. private:
  94.  
  95. // do not copy
  96. queue(queue const&);
  97. queue& operator=(queue const&);
  98.  
  99. af::basic::queue<T> q_;
  100. mutable boost::mutex m_;
  101. boost::condition_variable c_;
  102. };
  103.  
  104. }
  105. }
  106.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty