allocation演示了自定义异步操作的内存分配策略,因为asio在执行异步IO操作时会使用系统函数来动态分配内存,使用完后便立即释放掉;在IO操作密集的应用中,这种内存动态分配策略会较大地影响程序的整体性能。为了避免这个问题,可以在在应用程序中创建一个内存块供asio异步IO操作使用,异步IO操作通过自定义接口 asio_handler_allocate 和 asio_handler_deallocate 来使用该内存块。该例子中使用到了 boost::aligned_storage<1024> storage_ 来管理原始内存。

cpp03

 //
// server.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// #include <cstdlib>
#include <iostream>
#include <boost/aligned_storage.hpp>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp> using boost::asio::ip::tcp; // Class to manage the memory to be used for handler-based custom allocation.
// It contains a single block of memory which may be returned for allocation
// requests. If the memory is in use when an allocation request is made, the
// allocator delegates allocation to the global heap.
class handler_allocator
: private boost::noncopyable
{
public:
handler_allocator()
: in_use_(false)
{
} void* allocate(std::size_t size)
{
if (!in_use_ && size < storage_.size)
{
in_use_ = true;
return storage_.address();
}
else
{
return ::operator new(size);
}
} void deallocate(void* pointer)
{
if (pointer == storage_.address())
{
in_use_ = false;
}
else
{
::operator delete(pointer);
}
} private:
// Storage space used for handler-based custom memory allocation.
boost::aligned_storage<> storage_; // Whether the handler-based custom allocation storage has been used.
bool in_use_;
}; // Wrapper class template for handler objects to allow handler memory
// allocation to be customised. Calls to operator() are forwarded to the
// encapsulated handler.
template <typename Handler>
class custom_alloc_handler
{
public:
custom_alloc_handler(handler_allocator& a, Handler h)
: allocator_(a),
handler_(h)
{
} template <typename Arg1>
void operator()(Arg1 arg1)
{
handler_(arg1);
} template <typename Arg1, typename Arg2>
void operator()(Arg1 arg1, Arg2 arg2)
{
handler_(arg1, arg2);
} friend void* asio_handler_allocate(std::size_t size,
custom_alloc_handler<Handler>* this_handler)
{
return this_handler->allocator_.allocate(size);
} friend void asio_handler_deallocate(void* pointer, std::size_t /*size*/,
custom_alloc_handler<Handler>* this_handler)
{
this_handler->allocator_.deallocate(pointer);
}
private:
handler_allocator& allocator_;
Handler handler_;
};
// Helper function to wrap a handler object to add custom allocation.
template <typename Handler>
inline custom_alloc_handler<Handler> make_custom_alloc_handler(
handler_allocator& a, Handler h)
{
return custom_alloc_handler<Handler>(a, h);
} class session
: public boost::enable_shared_from_this<session>
{
public:
session(boost::asio::io_service& io_service)
: socket_(io_service)
{
}
tcp::socket& socket()
{
return socket_;
}
void start()
{
socket_.async_read_some(boost::asio::buffer(data_),
make_custom_alloc_handler(allocator_,
boost::bind(&session::handle_read,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred)));
}
void handle_read(const boost::system::error_code& error,
size_t bytes_transferred)
{
if (!error)
{
boost::asio::async_write(socket_,
boost::asio::buffer(data_, bytes_transferred),
make_custom_alloc_handler(allocator_,
boost::bind(&session::handle_write,
shared_from_this(),
boost::asio::placeholders::error)));
}
}
void handle_write(const boost::system::error_code& error)
{
if (!error)
{
socket_.async_read_some(boost::asio::buffer(data_),
make_custom_alloc_handler(allocator_,
boost::bind(&session::handle_read,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred)));
}
}
private:
// The socket used to communicate with the client.
tcp::socket socket_;
// Buffer used to store data received from the client.
boost::array<char, > data_;
// The allocator to use for handler-based custom memory allocation.
handler_allocator allocator_;
}; typedef boost::shared_ptr<session> session_ptr;
class server
{
public:
server(boost::asio::io_service& io_service, short port)
: io_service_(io_service),
acceptor_(io_service, tcp::endpoint(tcp::v4(), port))
{
session_ptr new_session(new session(io_service_));
acceptor_.async_accept(new_session->socket(),
boost::bind(&server::handle_accept, this, new_session,
boost::asio::placeholders::error));
}
void handle_accept(session_ptr new_session,
const boost::system::error_code& error)
{
if (!error)
{
new_session->start();
} new_session.reset(new session(io_service_));
acceptor_.async_accept(new_session->socket(),
boost::bind(&server::handle_accept, this, new_session,
boost::asio::placeholders::error));
}
private:
boost::asio::io_service& io_service_;
tcp::acceptor acceptor_;
}; int main(int argc, char* argv[])
{
try
{
boost::asio::io_service io_service;
using namespace std; // For atoi.
server s(io_service, );
io_service.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
} return ;
}

cpp11

 //
// server.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// #include <array>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <type_traits>
#include <utility>
#include "asio.hpp" using asio::ip::tcp; // Class to manage the memory to be used for handler-based custom allocation.
// It contains a single block of memory which may be returned for allocation
// requests. If the memory is in use when an allocation request is made, the
// allocator delegates allocation to the global heap.
class handler_allocator
{
public:
handler_allocator()
: in_use_(false)
{
} handler_allocator(const handler_allocator&) = delete;
handler_allocator& operator=(const handler_allocator&) = delete; void* allocate(std::size_t size)
{
if (!in_use_ && size < sizeof(storage_))
{
in_use_ = true;
return &storage_;
}
else
{
return ::operator new(size);
}
} void deallocate(void* pointer)
{
if (pointer == &storage_)
{
in_use_ = false;
}
else
{
::operator delete(pointer);
}
} private:
// Storage space used for handler-based custom memory allocation.
typename std::aligned_storage<>::type storage_; // Whether the handler-based custom allocation storage has been used.
bool in_use_;
}; // Wrapper class template for handler objects to allow handler memory
// allocation to be customised. Calls to operator() are forwarded to the
// encapsulated handler.
template <typename Handler>
class custom_alloc_handler
{
public:
custom_alloc_handler(handler_allocator& a, Handler h)
: allocator_(a),
handler_(h)
{
} template <typename ...Args>
void operator()(Args&&... args)
{
handler_(std::forward<Args>(args)...);
} friend void* asio_handler_allocate(std::size_t size,
custom_alloc_handler<Handler>* this_handler)
{
return this_handler->allocator_.allocate(size);
} friend void asio_handler_deallocate(void* pointer, std::size_t /*size*/,
custom_alloc_handler<Handler>* this_handler)
{
this_handler->allocator_.deallocate(pointer);
} private:
handler_allocator& allocator_;
Handler handler_;
}; // Helper function to wrap a handler object to add custom allocation.
template <typename Handler>
inline custom_alloc_handler<Handler> make_custom_alloc_handler(
handler_allocator& a, Handler h)
{
return custom_alloc_handler<Handler>(a, h);
} class session
: public std::enable_shared_from_this<session>
{
public:
session(tcp::socket socket)
: socket_(std::move(socket))
{
} void start()
{
do_read();
} private:
void do_read()
{
auto self(shared_from_this());
socket_.async_read_some(asio::buffer(data_),
make_custom_alloc_handler(allocator_,
[this, self](std::error_code ec, std::size_t length)
{
if (!ec)
{
do_write(length);
}
}));
} void do_write(std::size_t length)
{
auto self(shared_from_this());
asio::async_write(socket_, asio::buffer(data_, length),
make_custom_alloc_handler(allocator_,
[this, self](std::error_code ec, std::size_t /*length*/)
{
if (!ec)
{
do_read();
}
}));
} // The socket used to communicate with the client.
tcp::socket socket_; // Buffer used to store data received from the client.
std::array<char, > data_; // The allocator to use for handler-based custom memory allocation.
handler_allocator allocator_;
}; class server
{
public:
server(asio::io_service& io_service, short port)
: acceptor_(io_service, tcp::endpoint(tcp::v4(), port)),
socket_(io_service)
{
do_accept();
} private:
void do_accept()
{
acceptor_.async_accept(socket_,
[this](std::error_code ec)
{
if (!ec)
{
std::make_shared<session>(std::move(socket_))->start();
} do_accept();
});
} tcp::acceptor acceptor_;
tcp::socket socket_;
}; int main(int argc, char* argv[])
{
try
{
if (argc != )
{
std::cerr << "Usage: server <port>\n";
return ;
} asio::io_service io_service;
server s(io_service, std::atoi(argv[]));
io_service.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
} return ;
}

boost asio allocation的更多相关文章

  1. BOOST.Asio——Overview

    =================================版权声明================================= 版权声明:原创文章 谢绝转载  啥说的,鄙视那些无视版权随 ...

  2. boost::asio译文

        Christopher Kohlhoff Copyright © 2003-2012 Christopher M. Kohlhoff 以Boost1.0的软件授权进行发布(见附带的LICENS ...

  3. Boost.Asio技术文档

    Christopher Kohlhoff Copyright © 2003-2012 Christopher M. Kohlhoff 以Boost1.0的软件授权进行发布(见附带的LICENSE_1_ ...

  4. BOOST ASIO 学习专贴

    本文已于20170903更新完毕,所有boost asio 代码均为本人手抄.编译器为vs2013,并且所有代码已经上传,本文下方可下载源码 为了学习boost asio库,我是从boost的官方bo ...

  5. boost asio one client one thread

    总结了一个简单的boost asio的tcp服务器端与客户端通信流程.模型是一个client对应一个线程.先做一个记录,后续再对此进行优化. 环境:VS2017  + Boost 1.67 serve ...

  6. c++ boost asio库初学习

    前些日子研究了一个c++的一个socket库,留下范例代码给以后自己参考. 同步server: // asio_server.cpp : コンソール アプリケーションのエントリ ポイントを定義します. ...

  7. 如何在多线程leader-follower模式下正确的使用boost::asio。

    #include <assert.h> #include <signal.h> #include <unistd.h> #include <iostream& ...

  8. BOOST.Asio——Tutorial

    =================================版权声明================================= 版权声明:原创文章 谢绝转载  啥说的,鄙视那些无视版权随 ...

  9. boost asio sync

    Service: #include<boost/asio.hpp> #include<boost/thread.hpp> #include<iostream> #i ...

随机推荐

  1. appium+python环境搭建

    一.环境 1.安装python. 2.安装appium. 3.安装pip 4.安装selenium 5.安装Appium-Python-Client       #cmd->cd setupto ...

  2. BZOJ 3926: [Zjoi2015]诸神眷顾的幻想乡 [广义后缀自动机 Trie]

    3926: [Zjoi2015]诸神眷顾的幻想乡 Time Limit: 10 Sec  Memory Limit: 512 MBSubmit: 1124  Solved: 660[Submit][S ...

  3. request、response的setCharacterEncoding与response的setContentType

    一.request中的setCharacterEncoding方法:作用是用指定的编码集去覆盖request对象中的默认的"ISO-8859-1"编码集,如"UTF-8& ...

  4. Spring Mybatis-分页插件使用

    Mybatis分页切入点 Mybatis内部有个plugins(插件)概念,本质上属于拦截器的思想.具体的解析可见外文MyBatis拦截器原理探究.本文将在此基础上直接展示实现代码和其他的相关解析 分 ...

  5. WEB-INF目录下文件复制的几种方式

    2018年1月31日 10:42:55 工作完写点博客记录下. 需求:从web-inf下拷贝文件到指定目录. 目录结构 直接贴代码 第一种方式,字节流读取 try { int index = 0; S ...

  6. XAMPP的配置与使用

    XAMPP的配置与使用 一.起因 一开始,我在本地手动DIY安装了WAMPP环境,其中经历了很长时间的折腾,原因是独立安装Apache和MySQL,以及PHP的时候,屡次遇到版本兼容问题,我主要的时间 ...

  7. NSData所有API学习

      www.MyException.Cn  网友分享于:2015-04-24  浏览:0次   NSData全部API学习. 学习NSData,在网上找资料竟然都是拷贝的纯代码,没人去解释.在这种网上 ...

  8. NDK开发,如何配置 debug环境

    刚开始做NDK 开发的时候,Android Studio 还没提供了 native C/C++ 设置断点 调试,我们都是通过输出 日志来调试,这样费时耗力.Android Studio 应该是在 2. ...

  9. Java并发系列[6]----Semaphore源码分析

    Semaphore(信号量)是JUC包中比较常用到的一个类,它是AQS共享模式的一个应用,可以允许多个线程同时对共享资源进行操作,并且可以有效的控制并发数,利用它可以很好的实现流量控制.Semapho ...

  10. Python自动化--语言基础5--面向对象、迭代器、range和切片的区分

    面向对象 一.面向对象代码示例: 1 class Test(): #类的定义 2 car = "buick" #类变量,定义在类里方法外,可被对象直接调用,具有全局效果 3 def ...