Buffer实现,存放指针对象.


//Buffer.h
#include
#include
#include

template
class Buffer
{
public:
Buffer();
static const char* MODULE;

bool Init();
inline void Notify() {m_bInterrupt = true; m_NotEmpty.notify_one();}
virtual void Add(T const &val);
T Get();
volatile unsigned int GetSize() const {return m_Size;}

void Remove();//!< Removes from queue
//!< Switches Auto Removing function for queue
void SetAutoRemove(bool bVal=true) {m_AutoRemove = bVal;}

private:
boost::mutex m_Mutex;
boost::condition m_NotEmpty;
volatile bool m_bInterrupt;

volatile unsigned int m_Size;
std::queue m_Queue;
bool m_AutoRemove;
};





//Buffer.cpp
#include "Buffer.h"

template
const char* Buffer::MODULE = "Buffer";

template
Buffer::Buffer() : m_Size(0),
m_AutoRemove(true), m_bInterrupt(false)
{
}

template
bool Buffer::Init()
{
while (!m_Queue.empty()) m_Queue.pop();
m_Size = 0;
m_AutoRemove = true;
return true;
}

template
void Buffer::Add(T const &val)
{
boost::unique_lock lock(m_Mutex);
m_Queue.push(val);
++m_Size;

m_NotEmpty.notify_one();
}

template
void Buffer::Remove()
{
boost::unique_lock lock(m_Mutex);
if (!m_AutoRemove)
{
m_Queue.pop();
}
}
template
T Buffer::Get()
{
boost::unique_lock lock(m_Mutex);

if (m_Size==0)
{
while (m_bInterrupt==false && m_Size==0)
{

m_NotEmpty.wait(lock);
}
if (m_bInterrupt)
{
m_bInterrupt = false;
return NULL;
}
}

T val = m_Queue.front();
if (m_AutoRemove)
m_Queue.pop();
--m_Size;
return val;
}






#include
#include
#include
#include "Buffer.cpp"

class TestClass
{
public:
TestClass(){};
TestClass(std::string &in_name){m_name = in_name;};
void OutPutName()
{
std::cout< }
private:
std::string m_name;
};

int main()
{
Buffer buffers;
std::string name = "Cat";
TestClass *tc1 = new TestClass(name);
name = "Monkey";
TestClass *tc2 = new TestClass(name);
name = "Dog";
TestClass *tc3 = new TestClass(name);
buffers.Add(tc1);
buffers.Add(tc2);
buffers.Add(tc3);
TestClass *tc;
while((tc =buffers.Get())!= NULL)
{
tc->OutPutName();
std::cout<<"size:"< if(buffers.GetSize() == 0)
{
return 0;
}
}
return 0;
}




Result:
Cat
size:2
Monkey
size:1
Dog
size:0

你可能感兴趣的:(C++学习笔记,All,C,C++,C#)