模板队列-支持多线程

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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

苦逼的IT男

你的鼓励是我最大的创作动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值