以下为个人学习笔记整理。
# asio 源码阅读
Boost 的 asio 库常被用于实现异步的网络 IO,在服务器开发中往往充当着非常重要的作用,是服务器开发的基础。这里主要根据个人对于 asio 库阅读后的理解和感悟,进行系统化的归纳和总结。

# service_registry 类
Service 对象的管理器,通过单链表的形式存储所有的 Service 对象。并提供了添加、查询、创建等常用接口。
fork 操作
# execution_context 类
包含一个 service_registry 对象,对 service_registry 所有接口进行了一层封装,通过 service_registry 间接管理所有的 Service 对象。
# io_context 类
继承于 execution_context ,拥有 execution_context 中管理 Service 功能以外。
还拥有一个 impl_type 类,该类在 Linux 环境下被定义为 scheduler ,在 Windows 下则是 win_iocp_io_context 。
并且对 impl_type 的基本行为进行了封装,提供给外部使用。
# scheduler_operation 类
所执行 Task 的抽象统称,记录 Task 执行结果,管理 Task 声明周期。
# op_queue 类
scheduler_operation 对象组成的队列,提供常规队列的接口。
# reactor 类
定义执行任务所用的执行策略,每种策略都是对不同平台封装了一套 io 实现,并提供了定时器功能:
select:select_reactorepoll:epoll_reactorkqueue:kqueue_reactorpoll:dev_poll_reactor
# epoll_reactor 类
对于 Linux 下的 epoll 进行的封装、并提供了 timer_queue_set 定时器逻辑。
class epoll_reactor  | |
: public execution_context_service_base<epoll_reactor>  | |
  { | |
  // The scheduler implementation used to post completions. | |
scheduler& scheduler_;  | |
  // Mutex to protect access to internal data. | |
  mutex mutex_; | |
  // The interrupter is used to break a blocking epoll_wait call. | |
  select_interrupter interrupter_; | |
  // The epoll file descriptor. | |
int epoll_fd_;  | |
  // The timer file descriptor. | |
int timer_fd_;  | |
  // The timer queues. | |
  timer_queue_set timer_queues_; | |
  // Whether the service has been shut down. | |
bool shutdown_;  | |
  // Mutex to protect access to the registered descriptors. | |
  mutex registered_descriptors_mutex_; | |
  // Keep track of all registered descriptors. | |
object_pool<descriptor_state> registered_descriptors_;  | |
  // Helper class to do post-perform_io cleanup. | |
struct perform_io_cleanup_on_block_exit;  | |
friend struct perform_io_cleanup_on_block_exit;  | |
  } | 
# timer_queue_set 类
定时器队列单链表,由多个 timer_queue 组成,队列内元素都会存储一个调用时的时间戳。
根据时间戳计算所需等待时间,并执行定时任务。
# scheduler 类
实现调度接口的基类,内部维护了一个 op_queue 类,用于管理所有的 Operation 对象,并提供基础接口:
run:执行所有Task,队列内没有一个Task的情况下会sleep自己。run_one:执行一个Task,队列内没有Task的情况下会sleep自己,直到有一个任务可以执行。poll:执行所有Task,非阻塞。poll_one:执行一个Task,没有thread的情况下会创建一个thread并执行,非阻塞。stop:暂停并中断所有线程任务。restart:取消暂停。
包含一个 reactor 对象,用于执行 Task 。
class scheduler  | |
: public execution_context_service_base<scheduler>,  | |
public thread_context  | |
{ | |
  // Mutex to protect access to internal data. | |
mutable mutex mutex_;  | |
  // Event to wake up blocked threads. | |
  event wakeup_event_; | |
  // The task to be run by this service. | |
reactor* task_;  | |
  // Operation object to represent the position of the task in the queue. | |
  // 标记形式的空任务,用来判断当前队列是否正在消费或者存在需要消费任务的标志 | |
struct task_operation : operation  | |
  { | |
task_operation() : operation(0) {}  | |
} task_operation_;  | |
  // Whether the task has been interrupted. | |
bool task_interrupted_;  | |
  // The count of unfinished work. | |
  atomic_count outstanding_work_; | |
op_queue<operation> op_queue_;  | |
};  |