Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reactor 模型 #8

Open
JemmyH opened this issue Jun 29, 2021 · 2 comments
Open

Reactor 模型 #8

JemmyH opened this issue Jun 29, 2021 · 2 comments
Assignees
Labels
documentation Improvements or additions to documentation done

Comments

@JemmyH
Copy link
Owner

JemmyH commented Jun 29, 2021

The reactor design_pattern is an event_handling pattern for handling service requests delivered concurrently to a service handler by one or more inputs. The service handler then demultiplexes the incoming requests and dispatches them synchronously to the associated request handlers. ----Wili--Reactor_pattern

Reator 是一种事件处理模型,并发处理请求,然后对请求进行多路分解,并将它们同步分派给关联的请求处理程序。本 issue 旨在搞清楚此模型的运作方式、高效的原因 以及 有哪些对其进行的相关改进措施。

@JemmyH
Copy link
Owner Author

JemmyH commented Jun 29, 2021

服务器线程模型

在高性能的网络 I/O 设计中,有两个著名的模型: Reactor模型Proactor模型,前者用于 同步 I/O,后者用于 异步 I/O。有一点可以明确,不管是哪个模型,其目的都是提高服务端程序的并发能力。

对于支持多连接的服务器,一般情况下可以总结为 2种fd3种事件
流程图
2种fd

  • listen fd: 一般情况下只有一个,用来监听特定的端口,代表服务器程序;
  • connect fd:每当客户端和服务器建立连接,就会产生一个 connect fd,此后客户端的所有操作如收发数据都是通过这个 connect fd

3种事件

  • listen fd 进行 Accept 监听客户端的连接,创建新的 connect fd
  • 用户态/内核态 拷贝数据,每个 connect fd 都有两个缓冲区 read bufferwrite buffer
  • 处理 connect fd 发来的数据,进行对应的逻辑处理后,将数据发送到对应的 write buffer 中。

@JemmyH
Copy link
Owner Author

JemmyH commented Jun 29, 2021

Reactor 模型

在这个模型中,有三种角色:

  • Reactor:将 I/O事件 分配给对应的 handler 处理;
  • Acceptor:处理客户端的连接事件;
  • Handler:进行的具体的业务逻辑处理

从上面的定义以及这里的角色我们可以有一个大概的轮廓:

  1. 事件驱动;
  2. 可以处理一个或者多个输入源;
  3. 通过多路复用将请求的事件分发给对应的处理器处理。

Reactor 线程模型分类

根据 Reactor的数量处理资源的线程数量,分为三类:

1. 单 Reactor 单线程模型

在 Reactor 中处理并分发事件,如果是连接事件就交给 Acceptor,如果是读写事件就交给对应的 Handler 进行业务处理。这三个角色其实是一个线程在工作,始终是一个线程在处理所有的事。

2. 单 Reactor 多线程模型

区别于第一种,这种模型主要将业务处理从 Reactor 的单一线程中脱离出来,换成了额外的线程池去处理。也就是说,Reactor 只处理连接事件和读写事件,业务处理交给了线程池,线程池可以充分利用多核机器的资源。

3. 多 Reactor 多线程模型

与第二种模型相比,将 Reactor 拆分成了 MainReactor 和 SubReactor,前者只处理连接事件,读写事件交给后者,业务逻辑依旧使用线程池来处理。

image

@JemmyH JemmyH self-assigned this Jun 29, 2021
@JemmyH JemmyH added documentation Improvements or additions to documentation done labels Jun 29, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation done
Projects
None yet
Development

No branches or pull requests

1 participant