我已经制作了一个从客户端读取数据的服务器,并且我正在使用 boost::asio async_read_some 来读取数据,并且我已经制作了一个处理函数,这里 _ioService->poll() 将运行事件处理循环来执行准备好的处理程序。在处理程序 _handleAsyncReceive 中,我正在解除分配在 receiveDataAsync 中分配的 buf。bufferSize 为 500。代码如下:
bool
TCPSocket::receiveDataAsync( unsigned int bufferSize )
{
char *buf = new char[bufferSize + 1];
try
{
_tcpSocket->async_read_some( boost::asio::buffer( (void*)buf, bufferSize ),
boost::bind(&TCPSocket::_handleAsyncReceive,
this,
buf,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred) );
_ioService->poll();
}
catch (std::exception& e)
{
LOG_ERROR("Error Receiving Data Asynchronously");
LOG_ERROR( e.what() );
delete [] buf;
return false;
}
//we dont delete buf here as it will be deleted by callback _handleAsyncReceive
return true;
}
void
TCPSocket::_handleAsyncReceive(char *buf, const boost::system::error_code& ec, size_t size)
{
if(ec)
{
LOG_ERROR ("Error occurred while sending data Asynchronously.");
LOG_ERROR ( ec.message() );
}
else if ( size > 0 )
{
buf[size] = '\0';
LOG_DEBUG("Deleting Buffer");
emit _asyncDataReceivedSignal( QString::fromLocal8Bit( buf ) );
}
delete [] buf;
}
这里的问题是与释放相比,缓冲区的分配速度要快得多,因此内存使用率将以指数速度上升,并且在某个时间点它将消耗所有内存并且系统将被卡住。CPU 使用率也将在 90% 左右。如何减少内存和 CPU 消耗?