链表和锁实现的队列,锁的代码请看其他文章
#pragma once
#include <list>
#include "AutoLock.h"
namespace Extralib
{
namespace SafeQueue
{
using namespace Thread;
template<typename Data>
class safe_queue
{
private:
std::list<Data> the_queue;
pthread_mutex_t m_locker;
public:
safe_queue()
{
pthread_mutex_init(&m_locker,NULL);
}
~safe_queue()
{
pthread_mutex_destroy(&m_locker);
}
void push_front(const Data& data)
{
AutoLock locker(m_locker);
the_queue.push_front(data);
}
void push(const Data& data)
{
AutoLock locker(m_locker);
the_queue.push_back(data);
}
bool empty()
{
AutoLock locker(m_locker);
return the_queue.empty();
}
Data& front()
{
AutoLock locker(m_locker);
return the_queue.front();
}
Data const& front() const
{
AutoLock locker(m_locker);
return the_queue.front();
}
Data& back()
{
AutoLock locker(m_locker);
return the_queue.back();
}
bool try_pop(Data& data)
{
AutoLock locker(m_locker);
if(!the_queue.empty())
{
data = the_queue.front();
the_queue.pop_front();
return true;
}
else
{
return false;
}
}
void exchange(std::list<Data>& result_queue)
{
AutoLock locker(m_locker);
result_queue.swap(the_queue);
}
void pop()
{
AutoLock locker(m_locker);
the_queue.pop_front();
}
void clear()
{
AutoLock locker(m_locker);
the_queue.clear();
}
int size()
{
AutoLock locker(m_locker);
return the_queue.size();
}
};
}
}