C++ 不用std::queue 实现读取网络字节缓冲去的队列

想必你也和我一样听说了C++ STL 容器的std::queue 貌似有性能问题,内存会持续增加。我并没有深究解决办法,而是暴力自己重写了一个读取字节缓冲区的队列类

废话不多说直接看实现。利用这个这个缓冲机制下一篇将直接实现一个VC++的聊天室的客户端,并贴出源码。

#ifndef  PB_CSOCKETQUEUE_H_
#define PB_CSOCKETQUEUE_H_

#include <iostream>
#include <mutex>

class PB_CSocketQueue
{

private:
	std::mutex m_buff_mutex;

	struct queue_block
	{
		char c;
		queue_block *next;
		queue_block(const char &_c)
		{
			c = _c;
			next = NULL;
		}
	};

	queue_block *first, *last;

	int _size;
public:

	PB_CSocketQueue()
	{
		first = last = NULL;
		_size = 0;
	}

	~PB_CSocketQueue()
	{
		queue_block * p = first;
		while (p != NULL)
		{
			queue_block *tmp = p;
			p = p->next;
			delete tmp;
		}
	}

	void push(const char& data)
	{
	

		if (_size == 0)
		{
			queue_block * tmp = new queue_block(data);

			first = last = tmp;
		}

		else
		{
			queue_block * cur = last;
			queue_block * tmp = new queue_block(data);

			last = tmp;
			cur->next = tmp;
		}
		_size++;
	}

	bool pop(char& data)
	{
		if (_size == 0) return false;
		if (_size == 1)
		{
			char c = first->c;
			delete first;
			first = last = NULL;
			data = c;
		}
		else
		{
			queue_block * cur = first->next;
			char c = first->c;
			delete first;
			first = cur;
			data = c;
		}
		_size--;
		return true;
	}

	int indexof(const char& data)
	{
		int index = 0;
		queue_block * p = first;
		while (p != NULL)
		{
			queue_block *tmp = p;
			p = p->next;
			if (data == tmp->c) return index;
			index++;
		}
		return index;
	}

	int removeTop(int len){
		std::lock_guard<std::mutex> locker(m_buff_mutex);
		char c=0;
		int count=0;
		for (size_t i = 0; i < len; i++)
		{
			if (pop(c) == false) break;
			count++;
		}
		return count;
	}

	int copyTo(char * dst, int Len)
	{
		int count=0;
		queue_block * p = first;
		while (p != NULL&&count < Len)
		{
			queue_block *tmp = p;
			p = p->next;
			*dst = tmp->c;
			count++;
			dst++;
		}
		return count;
	}

	void append(char *c, int len)
	{
		std::lock_guard<std::mutex> locker(m_buff_mutex);
		for (size_t i = 0; i < len; i++)
		{
			push(c[i]);
		}
	}

	int length() const{
		return _size;
	}

};

#endif



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值