Pteros  2.0
Molecular modeling library for human beings!
buffer.h
1 // Copyright Maarten L. Hekkelman, Radboud University 2008-2011.
2 // Distributed under the Boost Software License, Version 1.0.
3 // (See accompanying file LICENSE_1_0.txt or copy at
4 // http://www.boost.org/LICENSE_1_0.txt)
5 //
6 // buffer is a thread safe queue
7 
8 #pragma once
9 
10 #include <deque>
11 #include <boost/thread/mutex.hpp>
12 #include <boost/thread/condition.hpp>
13 
14 template<class T, uint32 N = 100>
15 class buffer
16 {
17  public:
18 
19  buffer() {}
20 
21  void put(T inValue);
22  T get();
23 
24  private:
25  buffer(const buffer&);
26  buffer& operator=(const buffer&);
27 
28  std::deque<T> m_queue;
29  boost::mutex m_mutex;
30  boost::condition m_empty, m_full;
31 };
32 
33 template<class T, uint32 N>
34 void buffer<T,N>::put(T inValue)
35 {
36  boost::mutex::scoped_lock lock(m_mutex);
37 
38  while (m_queue.size() >= N)
39  m_full.wait(lock);
40 
41  m_queue.push_back(inValue);
42 
43  m_empty.notify_one();
44 }
45 
46 template<class T, uint32 N>
47 T buffer<T,N>::get()
48 {
49  boost::mutex::scoped_lock lock(m_mutex);
50 
51  while (m_queue.empty())
52  m_empty.wait(lock);
53 
54  T result = m_queue.front();
55  m_queue.pop_front();
56 
57  m_full.notify_one();
58 
59  return result;
60 }