您的位置:首页 > 其它

模板队列-支持多线程

2017-01-24 00:12 405 查看
Queue.h:

// 用于缓存数据包的队列容器

#pragma once

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

#include <list>
#define DEFAULTMAXSIZE 1000000

template<class T>
class Queue
{
public:
Queue(int nMaxLength = DEFAULTMAXSIZE);
virtual ~Queue();

public:
bool IsEmpty(); // 是否为空
int Length(); // 获取当前队列大小
const T& Pop(); // 队列出列
bool push(const T& inElement); // 入列
int SetMaxLength(int nMaxLength);// 设置最大容量

private:
int Lock(); // 获得互斥量
int Unlock(); // 释放互斥量
HANDLE m_hMutex;

int m_nMaxLength; // 最大大小
std::list<T> m_list; // 元素
};

#include "Queue.cpp"

Queue.cpp:
#include "Queue.h"
#include <process.h>

// 默认最大为100
template<class T> Queue<T>::Queue(int nMaxLength)
{
m_nMaxLength = nMaxLength;

// 创建互斥量
m_hMutex = CreateMutex(
NULL, // 使用默认的安全属性
FALSE,// 默认未获得拥有权
NULL);// 匿名
}

template<class T> Queue<T>::~Queue()
{
CloseHandle(m_hMutex);
}

// 是否为空
template<class T> bool Queue<T>::IsEmpty()
{
Lock();
bool bTemp = m_list.empty();
Unlock();

return bTemp;
}

// 获取当前队列大小
template<class T> int Queue<T>::Length()
{
Lock();
int nTemp = m_list.size();
Unlock();

return nTemp;
}

// 出列
template<class T> const T& Queue<T>::Pop()
{
Lock();

T Temp;
if (!m_list.empty())
{
Temp = m_list.front();
m_list.pop_front();
}

Unlock();

return Temp;
}

// 是否加入成功
template<class T> bool Queue<T>::push(const T& inElement)
{
Lock();
// 当前达到最大容量
if (m_list.size() > m_nMaxLength)
{
Unlock();
return false;
}

m_list.push_back(inElement);
Unlock();

return true;
}

// 设置最大容量
template<class T> int Queue<T>::SetMaxLength(int nMaxLength)
{
m_nMaxLength = nMaxLength;
return 0;
}

// 获得互斥量
template<class T> int Queue<T>::Lock()
{
// 等待其它线程释放互斥量
WaitForSingleObject(m_hMutex, INFINITE); // no time-out interval

return 0;
}

// 释放互斥量
template<class T> int Queue<T>::Unlock()
{
ReleaseMutex(m_hMutex);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: