IO multiplexing

This multiplexing refers to the multiplexed 线程 . In fact, the history of IO multiplexing is as long as multiple processes.


Linux has provided select system calls long enough to maintain 1024 connections in a single process.

Later, I added the poll system call, and the poll made some improvements to solve the 1024 limit problem and can maintain any number of connections.

One problem with select/poll is that it needs to loop through the connection to see if there is an event.

This problem comes. If the server has 1 million connections, only one connection sends data to the server at a time. Select/poll needs to do a loop of 1 million times, only one of which is hit, and the remaining 990,000. 9999 times are invalid, and the CPU resources are wasted.


Until the Linux 2.6 kernel provides a new epoll system call, an unlimited number of connections can be maintained, and no polling is required, which really solves the C10K problem. Now all kinds of high-end asynchronous IO server programs are based on epoll , such as Nginx、Node.js、Erlang、Golang . Single-process, single-threaded programs like Node.js and Redis can maintain more than 1 million TCP connections, all thanks to epoll technology.

It must be mentioned here that based on the Reactor model implemented by epoll , the IO复用 asynchronous non-blocking program uses the classic Reactor model. Reactor its name suggests, is the meaning of the 反应堆 , and it does not handle any data transmission and reception itself. It is only possible to monitor the event changes of a socket句柄 .


Efficient event processing mode Reactor mode

  • The main process/thread registers the read-ready event on the socket in the epoll内核事件 event.

  • The main process/thread calls epoll_wait wait for data on the socket to be readable.

  • When the data on the socket is readable, epoll_wait notifies the main process/thread. The main process/thread puts the socket readable event into the request queue.

  • A worker thread sleeping on the request queue is woken up, reads data from the socket , processes the client request, and then registers the write-ready event on the socket into the epoll kernel event table.

  • The main thread calls epoll_wait wait for the socket be writable.

  • When the socket is writable, epoll_wait notifies the main process/thread main process/thread to put the socket writable event into the request queue.

  • Sleeping on a worker thread on the request queue is awakened, it writes to the socket to process the client request

swoole 's Reactor thread is also based on the Reactor model.