Bites
A small library of miscellaneous C++ codes.
 All Classes Namespaces Functions Friends Pages
ConcurrentQueue.hpp
1 #ifndef BITES_CONCURRENTQUEUE_HPP_INCLUDED
2 #define BITES_CONCURRENTQUEUE_HPP_INCLUDED
3 
4 #include <queue>
5 #include <boost/thread/mutex.hpp>
6 #include <boost/thread/condition_variable.hpp>
7 
8 namespace bites {
9 
15 template<typename Data>
17 {
18 private:
19  std::queue<Data> the_queue;
20  mutable boost::mutex the_mutex;
21  boost::condition_variable the_condition_variable;
22 public:
25  void push(Data const& data)
26  {
27  boost::mutex::scoped_lock lock(the_mutex);
28  the_queue.push(data);
29  lock.unlock();
30  the_condition_variable.notify_one();
31  }
32 
35  bool empty() const
36  {
37  boost::mutex::scoped_lock lock(the_mutex);
38  return the_queue.empty();
39  }
40 
43  bool try_pop(Data& popped_value)
44  {
45  boost::mutex::scoped_lock lock(the_mutex);
46  if(the_queue.empty())
47  {
48  return false;
49  }
50 
51  popped_value=the_queue.front();
52  the_queue.pop();
53  return true;
54  }
55 
58  void wait_and_pop(Data& popped_value)
59  {
60  boost::mutex::scoped_lock lock(the_mutex);
61  while(the_queue.empty())
62  {
63  the_condition_variable.wait(lock);
64  }
65 
66  popped_value=the_queue.front();
67  the_queue.pop();
68  }
69 
72  typename std::queue<Data>::size_type size()
73  {
74  boost::mutex::scoped_lock lock(the_mutex);
75  return the_queue.size();
76  }
77 
78 };
79 
80 } // namespace bites.
81 
82 #endif // BITES_CONCURRENTQUEUE_HPP_INCLUDED
std::queue< Data >::size_type size()
Definition: ConcurrentQueue.hpp:72
Definition: ConcurrentQueue.hpp:16
bool try_pop(Data &popped_value)
Definition: ConcurrentQueue.hpp:43
bool empty() const
Definition: ConcurrentQueue.hpp:35
void push(Data const &data)
Definition: ConcurrentQueue.hpp:25
void wait_and_pop(Data &popped_value)
Definition: ConcurrentQueue.hpp:58