boost.asio源码剖析(五)

时间:2022-06-10 05:08:35

      有人说C++是带类的C;有人说C++是面向对象编程语言;有人说C++是面向过程与面向对象结合的语言。类似的评论网上有很多,虽然正确,却片面,是断章取义之言。

      C++是实践的产物,C++并没有为了成为某某类型的语言而设计,而是一切以工程实践为目的,一切以提升语言能力为目的。

      1983年C++诞生之时,由于兼容C语言而天生拥有了面向过程编程的能力;
      1989年推出的2.0版,C++完善了对面向对象编程范式的支持;
      1993年的3.0版,C++中引入了模板(template),有了泛型编程的雏形;
      1998年的C++第一次标准化,为支持著名的C++标准库中的STL,对泛型编程有了更完善的支持,并且发现了模板元编程;
      2011年9月的C++第三次标准化(C++11),进一步加强了泛型编程、模板元编程和并发编程的能力,也进一步加强了直接对硬件的操作能力,并且由于lambda的出现和早就出现在boost库中的bind/function等C++自扩展的组件,C++也拥有了一定程度上的函数式编程能力。

      模板技术给C++带来了强大至极的自扩展能力,在不修改编译器和语言核心功能的前提下依然可以使用语言自身模拟出各种各样的编程范式;这各种模拟又为C++语言的前进指引了方向,提供了工程实践的检验机会。经过三十年的实践,C++已逐渐发展为一门多范式编程语言,集面向过程、面向对象、泛型编程、模板元编程、函数式编程等多种范式于一身。随着广大C++er的不断实践与探索,C++会从中汲取经验与教训,越来越强大!

      本章中你将看到asio中对泛型编程和面向对象编程两种范式的结合使用,为你打开多范式混合编程的大门。在这里,泛型编程和面向对象编程两种编程范式相辅相成、取长补短,发挥出了单一编程范式无法比拟的强大威力,堪称多范式编程语言的应用典范。

 

* Service Concept

      Service,与basic_io_object结合时是一种泛型Concept,与io_service和service_registry结合时是面向对象思想中service_base的泛化类型。

Service作为泛型Concept时,其约束摘要如下:

1 class Service
2 {
3 public:
4 typedef ... implementation_type;
5
6 void construct(implementation_type& );
7 void destroy(implementation_type& );
8 io_service& get_io_service();
9 };

      其中,implementation_type是Service对应的I/O对象持有的句柄类型,basic_io_object在构造/析构时会调用construct/destroy接口注册/注销到Service中。

Service与io_service和service_registry结合时,要求其必须继承于service_base。
service_base及其基类io_service::service的类摘要如下:

 1 class io_service::service
2 : private noncopyable
3 {
4 public:
5 boost::asio::io_service& get_io_service();
6
7 protected:
8 service(boost::asio::io_service& owner);
9 virtual ~service();
10
11 private:
12 virtual void shutdown_service() = 0;
13
14 virtual void fork_service(boost::asio::io_service::fork_event event);
15
16 friend class boost::asio::detail::service_registry;
17 struct key
18 {
19 key() : type_info_(0), id_(0) {}
20 const std::type_info* type_info_;
21 const boost::asio::io_service::id* id_;
22 } key_;
23
24 boost::asio::io_service& owner_;
25 service * next_;
26 };
27
28 template <typename Type>
29 class service_base : public io_service::service
30 {
31 public:
32 static boost::asio::detail::service_id<Type> id;
33
34 service_base(boost::asio::io_service& io_service) : io_service::service(io_service) {}
35 };

      其中,Service在service_registry中是以侵入式的单链表存储的,io_service::service中成员next_即是指向下一个Service的指针。service_base类的模板参数Type即是Service的类型,Service在继承service_base时的写法大致如下:

1 class Service
2 : public service_base<Service>
3 {
4 };

 

将两种约束结合,得到一个最简单的可以与I/O对象搭配使用的Service的写法如下:

 1 class Service
2 : public service_base<Service>
3 {
4 public:
5 typedef ... implementation_type;
6
7 void construct(implementation_type&);
8 void destroy(implementation_type&);
9 io_service& get_io_service();
10 };

 


* CSU(Core-Service-User架构)

      第一章中单纯从面向对象的角度介绍过Asio的核心架构,本节不再局限于单一编程范式,从源码分析开始剖析Asio的核心架构。
      Asio的核心架构是由三大组件构成,其分别是:
            让用户直接使用,为用户提供接口的组件,暂且称之为User;
            无需用户感知的,为User的接口提供实现的服务组件,称为Service;
            负责组合多个Service,并辅助User对象的实例化的核心组件,称为Core;
      这种由Core-Service-User三部分组成的架构,为行文方便暂且简称为CSU。

      在Asio的CSU架构中,io_service以及几个关联类和内部类扮演了Core的角色;之前提到的ServiceConcept约定了Service的扩展方式;本节以一个Service及其对应的I/O对象为例介绍CSU的实现。为了易于理解,将源码中用于实现CSU的部分摘要出来,忽略与CSU无关的代码,并做一些小幅度修改。

Core相关代码摘要:

 1 class io_service
2 {
3 // 持有一个service_registry对象
4 service_registry * service_registry_;
5 };
6
7 // 返回ios中服务类型是Service的服务的引用
8 template <typename Service> Service& use_service(io_service& ios);
9
10 // 给ios添加服务svc
11 template <typename Service> void add_service(io_service& ios, Service* svc);
12
13 // 判断ios中是否有服务类型是Service的服务
14 template <typename Service> bool has_service(io_service& ios);
15
16 // 所有Service的根基类
17 class io_service::service
18 {
19 };
20
21 // 用于组合多个Service
22 class service_registry
23 {
24 io_service::service * service_list_;
25
26 private:
27 /// 以下三个函数是同名*函数的真正实现
28 template <typename Service> Service& use_service();
29 template <typename Service> void add_service(Service* svc);
30 template <typename Service> bool has_service();
31 };
32
33 // 所有Service的直接父类,Type必须为Service自身类型。
34 template <typename Type>
35 class service_base
36 {
37 static service_id<Type> id;
38 };

 

Service,以deadline_timer_service为例:

  1 // 定时器服务
2 template <typename TimeType,
3 typename TimeTraits = boost::asio::time_traits<TimeType> >
4 class deadline_timer_service
5 {
6 private:
7 typedef detail::deadline_timer_service<traits_type> service_impl_type;
8
9 public:
10 typedef typename service_impl_type::implementation_type implementation_type;
11
12 /// Construct a new timer service for the specified io_service.
13 explicit deadline_timer_service(boost::asio::io_service& io_service)
14 : boost::asio::detail::service_base<
15 deadline_timer_service<TimeType, TimeTraits> >(io_service),
16 service_impl_(io_service)
17 {
18 }
19
20 /// Construct a new timer implementation.
21 void construct(implementation_type& impl)
22 {
23 service_impl_.construct(impl);
24 }
25
26 /// Destroy a timer implementation.
27 void destroy(implementation_type& impl)
28 {
29 service_impl_.destroy(impl);
30 }
31
32 /// Cancel any asynchronous wait operations associated with the timer.
33 std::size_t cancel(implementation_type& impl, boost::system::error_code& ec)
34 {
35 return service_impl_.cancel(impl, ec);
36 }
37
38 /// Cancels one asynchronous wait operation associated with the timer.
39 std::size_t cancel_one(implementation_type& impl,
40 boost::system::error_code& ec)
41 {
42 return service_impl_.cancel_one(impl, ec);
43 }
44
45 /// Get the expiry time for the timer as an absolute time.
46 time_type expires_at(const implementation_type& impl) const
47 {
48 return service_impl_.expires_at(impl);
49 }
50
51 /// Set the expiry time for the timer as an absolute time.
52 std::size_t expires_at(implementation_type& impl,
53 const time_type& expiry_time, boost::system::error_code& ec)
54 {
55 return service_impl_.expires_at(impl, expiry_time, ec);
56 }
57
58 /// Get the expiry time for the timer relative to now.
59 duration_type expires_from_now(const implementation_type& impl) const
60 {
61 return service_impl_.expires_from_now(impl);
62 }
63
64 /// Set the expiry time for the timer relative to now.
65 std::size_t expires_from_now(implementation_type& impl,
66 const duration_type& expiry_time, boost::system::error_code& ec)
67 {
68 return service_impl_.expires_from_now(impl, expiry_time, ec);
69 }
70
71 // Perform a blocking wait on the timer.
72 void wait(implementation_type& impl, boost::system::error_code& ec)
73 {
74 service_impl_.wait(impl, ec);
75 }
76
77 // Start an asynchronous wait on the timer.
78 template <typename WaitHandler>
79 BOOST_ASIO_INITFN_RESULT_TYPE(WaitHandler,
80 void (boost::system::error_code))
81 async_wait(implementation_type& impl,
82 BOOST_ASIO_MOVE_ARG(WaitHandler) handler)
83 {
84 detail::async_result_init<
85 WaitHandler, void (boost::system::error_code)> init(
86 BOOST_ASIO_MOVE_CAST(WaitHandler)(handler));
87
88 service_impl_.async_wait(impl, init.handler);
89
90 return init.result.get();
91 }
92
93 private:
94 // Destroy all user-defined handler objects owned by the service.
95 void shutdown_service()
96 {
97 service_impl_.shutdown_service();
98 }
99
100 // The platform-specific implementation.
101 service_impl_type service_impl_;
102 };

 

User相关代码,以basic_deadline_timer为例:

 1 template <typename IoObjectService>
2 class basic_io_object
3 {
4 public:
5 typedef IoObjectService service_type;
6 typedef typename service_type::implementation_type implementation_type;
7
8 boost::asio::io_service& get_io_service();
9
10 protected:
11 explicit basic_io_object(boost::asio::io_service& io_service)
12 : service_(&boost::asio::use_service<IoObjectService>(io_service))
13 {
14 service_->construct(implementation);
15 }
16
17 ~basic_io_object()
18 {
19 service_->destroy(implementation);
20 }
21
22 service_type& get_service()
23 {
24 return *service_;
25 }
26
27 const service_type& get_service() const
28 {
29 return *service_;
30 }
31
32 implementation_type& get_implementation()
33 {
34 return implementation;
35 }
36
37 const implementation_type& get_implementation() const
38 {
39 return implementation;
40 }
41
42 implementation_type implementation;
43
44 private:
45 basic_io_object(const basic_io_object&);
46 void operator=(const basic_io_object&);
47
48 IoObjectService* service_;
49 };
50
51 template <typename Time,
52 typename TimeTraits = boost::asio::time_traits<Time>,
53 typename TimerService = deadline_timer_service<Time, TimeTraits> >
54 class basic_deadline_timer
55 : public basic_io_object<TimerService>
56 {
57 public:
58 /// 三个构造函数均需要io_service&
59 explicit basic_deadline_timer(boost::asio::io_service& io_service);
60 basic_deadline_timer(boost::asio::io_service& io_service, const time_type& expiry_time);
61 basic_deadline_timer(boost::asio::io_service& io_service, const duration_type& expiry_time);
62
63 ////////////////////////////////////////////////////
64 /// @{ 功能性接口
65 std::size_t cancel();
66 std::size_t cancel(boost::system::error_code& ec);
67 std::size_t cancel_one();
68 std::size_t cancel_one(boost::system::error_code& ec);
69
70 time_type expires_at() const;
71 std::size_t expires_at(const time_type& expiry_time);
72 std::size_t expires_at(const time_type& expiry_time, boost::system::error_code& ec);
73
74 duration_type expires_from_now() const;
75 std::size_t expires_from_now(const duration_type& expiry_time);
76 std::size_t expires_from_now(const duration_type& expiry_time, boost::system::error_code& ec);
77
78 void wait();
79 void wait(boost::system::error_code& ec);
80
81 template <typename WaitHandler>
82 BOOST_ASIO_INITFN_RESULT_TYPE(WaitHandler, void (boost::system::error_code))
83 async_wait(BOOST_ASIO_MOVE_ARG(WaitHandler) handler);
84 /// @}
85 /////////////////////////////////////////////////////
86 };

      在basic_deadline_timer和其对应服务deadline_timer_service的源码中可以很清晰的看到,他们都有名为cancel/cancel_one/expires_at/expires_from_now/wait/async_wait的函数,这些是deadline_timer对外提供的功能接口;basic_deadline_timer类中的这些接口只是对deadline_timer_service中同名接口的封装。

      在Asio的CSU架构中,用泛型编程的方式约束Service和User,使他们拥有极强的扩展性;用面向对象的手段联结Core-Service-User三大组件,从用户的角度看,产生类似于“高内聚”的效果,让用户可以以简单而统一的接口使用asio,不必自行处理高难度的泛型组件的组装工作。

 

由于本文会实时根据读者反馈的宝贵意见更新,为防其他读者看到过时的文章,因此本系列专题谢绝转载!