实现这么一个缓存:
(1)缓存的对象是固定大小
(2)只能从该缓存中分配内存
(3)释放内存要回到缓存中
(4)读写缓存中的数据符合FIFO规则
用途:
(1)接受固定大小的数据块,然后写入缓存中,工作线程从缓存中读取数据块进行处理.
代码:
/**
* FIFO_Pool.h
*/
#ifndef __FIFO_POOL_H
#define __FIFO_POOL_H
#include <boost/noncopyable.hpp>
#include <boost/pool/object_pool.hpp>
#include <boost/thread.hpp>
#include <boost/assert.hpp>
#include <queue>
namespace ikud {
template <typename T>
class FIFO_Pool : boost::noncopyable
{
public:
FIFO_Pool(int size);
virtual ~FIFO_Pool(void) { /*no-op*/ }
T* malloc(void);
void free(T* ptr);
int read(T** ptr);
int write(T* ptr);
private:
int capacity_;
int total_;
boost::object_pool<T> pool_;
boost::mutex pool_mutex_;
std::queue<T*> fifo_;
boost::mutex fifo_mutex_;
boost::condition fifo_cond_;
};
template <typename T>
FIFO_Pool<T>::FIFO_Pool(int size) : capacity_(size), total_(0)
{
BOOST_ASSERT(size > 0);
}
template <typename T>
T* FIFO_Pool<T>::malloc()
{
boost::mutex::scoped_lock lock(pool_mutex_);
T* ptr = NULL;
if (total_ < capacity_)
{
ptr = pool_.malloc();
if (ptr != NULL)
++ total_;
}
return ptr;
}
template <typename T>
void FIFO_Pool<T>::free(T* ptr)
{
BOOST_ASSERT(pool_.is_from(ptr));
boost::mutex::scoped_lock lock(pool_mutex_);
pool_.free(ptr);
-- total_;
}
template <typename T>
int FIFO_Pool<T>::read(T** ptr)
{
boost::mutex::scoped_lock lock(fifo_mutex_);
while (fifo_.size() == 0)
{
fifo_cond_.wait(lock);
}
*ptr = fifo_.front();
fifo_.pop();
return 0;
}
template <typename T>
int FIFO_Pool<T>::write(T* ptr)
{
BOOST_ASSERT(pool_.is_from(ptr));
boost::mutex::scoped_lock lock(fifo_mutex_);
fifo_.push(ptr);
fifo_cond_.notify_one();
return 0;
}
} // namespace ikud
#endif // __FIFO_POOL_H