想必你也和我一样听说了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