1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
|
/*
* Buffer.h
* RpcDriver
*
* Created by Mikael Gransell on 1/31/06.
* Copyright 2006 __MyCompanyName__. All rights reserved.
*
*/
#ifndef _BUFFER_H_
#define _BUFFER_H_
#include <boost/thread/mutex.hpp>
#include <queue>
#include <stdexcept>
namespace rpc {
/**
* Class that synchronizes access to a queue of items.
*/
template<class T>
class ProtectedBuffer
{
public:
/**
* Adds an item to the end of the buffer.
* @param item Item to be added.
*/
void enqueue( const T& item ) throw()
{
// Lock the mutex
boost::mutex::scoped_lock lock( m_mutex );
// Add item
m_queue.push( item );
}
/**
* Remove the first item in the buffer and return it to the caller.
* @return The first item in the buffer.
*/
T dequeue() throw()
{
// Lock mutex
boost::mutex::scoped_lock lock( m_mutex );
// Check that the list is not empty
if( m_queue.empty() ) {
// Throw an exception
throw std::out_of_range( "Queue is empty" );
}
// Get the first item
T item = m_queue.front();
// Remove the first item
m_queue.pop();
return item;
}
/**
* Check if the buffer is empty.
* @return true if the buffer is empty.
*/
bool empty() throw()
{
// Lock mutex
boost::mutex::scoped_lock lock( m_mutex );
// Fetch size of inner queue
bool empty = m_queue.empty();
return empty;
}
private:
/// Mutex to synchronize access
boost::mutex m_mutex;
/// The queue of items
std::queue<T> m_queue;
};
}
#endif
|