to myself 的分类学习日志

做自己想做的事
posts - 232, comments - 6, trackbacks - 0, articles - 0

asio

Posted on 2009-03-05 15:17 kongkongzi 阅读(694) 评论(0)  编辑 收藏 引用 所属分类: c++ network library
boost::asio
boost::asio::io_service 
// This class provides access to I/O functionality.
boost::asio::io_service::run(); // Run the io_service's event processing loop. 
                                 // 在run之前已经注册了(将)要处理的Event
boost::asio::io_service::post(CompletionHandler handler); // Request the io_service to 
                                 // invoke the given handler and return immediately. 

boost::asio::ip::tcp::acceptor
boost::asio::strand 
// guarantees that, for those handlers that are dispatched through it,
   // an executing handler will be allowed to complete before the next one is started.

boost::bind // bind any argument to a specific value or route input arguments into arbitrary positions

 strand_.wrap(boost::bind(&tcp_client_jade::handle_read_type, shared_from_this(), 
            boost::asio::placeholders::error));
strand_.wrap(boost::bind(
&tcp_client_jade::handle_read_type, shared_from_this(), 
            boost::asio::placeholders::error));
strand_.wrap(boost::bind(
&session::handle_write, shared_from_this(), 
            boost::asio::placeholders::error));




使用io_service作为处理工作的work pool,可以看到,就是通过io_service.post投递一个Handler到io_service的队列,Handler在这个io_service.run内部得到执行,有可能你会发现,io_services.dispatch的接口也和io_service.post一样,但不同的是它是直接调用而不是经过push到队列然后在io_services.run中执行,而在这个示例当中,显然我们需要把工作交到另一个线程去完成,这样才不会影响网络接收线程池的工作以达到高效率的接收数据,这种设计与前面的netsever其实相同,这就是典型的Half Sync/Half Async。二者的区别就是netsever自己实现了工作队列,而不是直接使用io_service,这种设计实际上在win下是使用了iocp作为工作队列。
 不过我更倾向于前一种设计,因为那样做,代码一切都在自己的掌握中,而io_service则是经过许多封装代码,并且本身设计只是用于处理网络完成事件的。
无论如何使用,都能感觉到使用boost.asio实现服务器,不尽是一件非常轻松的事,而且代码很漂亮,逻辑也相当清晰,这点上很不同于ACE。

我觉IO_SERVICE是一个基本性的接口,基本上通常用到的类实例都需要通过它来构造功能我们可以看似socket


学习boost的使用:
1、查看源代码。boost在源码了添加了大量的注释,对于理解某个函数的功能、使用方法等都有大量的说明。
2、查看doc文档。boost在doc里提供了比较多的应用实例,可以参考。


  /// The type of the service that will be used to provide I/O operations.
  typedef IoObjectService service_type;

  /// The underlying implementation type of I/O object.
  typedef typename service_type::implementation_type implementation_type;

  // The backend service implementation.
  service_type& service;

  // The underlying native implementation.
  implementation_type implementation;
 
数据与操作的分离?
io_service associated with the object.



boost::asio::detail::task_io_service<boost::asio::detail::epoll_reactor<false> >::do_one
boost
/asio/detail/task_io_service.hpp:222




只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理