SoFunction
Updated on 2025-05-16

Detailed explanation of Reactor model and C++ implementation framework

Detailed explanation of Reactor model and C++ implementation

1. The core idea of ​​Reactor model

Reactor mode is aEvent-drivenThe concurrent processing model of the coreSynchronous I/O multiplexingIt realizes monitoring of multiple I/O sources, and when an event is triggered, it is dispatched to the corresponding processor for non-blocking processing.

Key Features:

  • Non-blocking I/O: All operations do not block threads
  • Event loop: Continuously monitor the event source
  • Callback mechanism: The registered processing function is called after the event is triggered

2. Core components

Components Responsibility description
Event Demultiplexer useepoll/select/kqueueListen to multiple file descriptors
Event Handler Define event processing interface (read/write/exception)
Reactor Core Scheduler, Register/Remove Event Processor, Run Event Loop

3. C++ implementation architecture

1. Reactor class framework code

class Reactor {
public:
    void register_handler(EventHandler* handler, EventType et);
    void remove_handler(EventHandler* handler);
    void handle_events(timeval* timeout = nullptr);
private:
    EventDemultiplexer demux_;  // Actually use epoll to implement it    std::map<Handle, EventHandler*> handlers_;
};

2. Event Processor Interface

class EventHandler {
public:
    virtual void handle_read() = 0;
    virtual void handle_write() = 0;
    virtual Handle get_handle() const = 0;
};

3. Event demultiplexing implementation (taking epoll as an example)

class EpollDemultiplexer {
public:
    void add_event(Handle h, EventType et) {
        epoll_event ev;
         = et;
         = h;
        epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, h, &ev);
    }
    int wait(epoll_event* events, int max_events, int timeout) {
        return epoll_wait(epoll_fd_, events, max_events, timeout);
    }
};

4. Workflow

  • Initialization phase
    • Create a Reactor instance
    • Register multiple EventHandlers to Reactor
  • Event loop
while (running) {
    int num_events = demux_.wait(events, MAX_EVENTS, timeout);
    for (int i = 0; i < num_events; ++i) {
        EventHandler* handler = find_handler(events[i].);
        if (events[i].events & EPOLLIN) 
            handler->handle_read();
        if (events[i].events & EPOLLOUT)
            handler->handle_write();
    }
}

Event handling example (TCP connection)

class TcpConnection : public EventHandler {
public:
    void handle_read() override {
        char buf[1024];
        ssize_t n = read(socket_fd_, buf, sizeof(buf));
        if (n > 0) {
            process_data(buf, n);
        }
    }
};

5. Advanced Extension Mode

1. Multithreaded Reactor

model describe
Single Reactor Thread All operations are completed in a single thread
Reactor + ThreadPool Main thread handles I/O, worker thread handles business logic
Multiple Reactors Main Reactor handles connections, Sub Reactors handles connected sockets (Nginx style)

2. Key points of performance optimization

  • Use Edge Trigger (EPOLLET) mode
  • Use object pools to avoid frequent memory allocation
  • Implement zero-copy data transfer
  • Set a reasonable thread pool size

6. Comparison with Proactor mode

characteristic Reactor Proactor
I/O operation method Non-blocking asynchronous
Completion notification Notification when readable and writeable Notification when the operation is completed
Implement complexity Lower Higher
Typical implementation libevent, libuv IOCP(Windows)

7. Typical application scenarios

  • High concurrency network server (Web server/game server)
  • Real-time communication system
  • Distributed system middleware
  • There are many long connections required

8. Best Practice Suggestions

  • Avoid blocking in event processingLong-term operations should be handed over to thread pool processing
  • Set the buffer reasonablyReduce memory copy using ring buffer
  • Connection ManagementRealize heartbeat mechanism detection disconnection
  • Exception handlingUnified handling of EPOLLERR and EPOLLHUP events
  • Performance monitoringAdding event processing time-consuming statistics

Note: It is recommended to use mature network libraries (such as muduo) in actual projects.

This is the end of this article about the detailed explanation of the Reactor model and the C++ implementation framework. For more related C++ Reactor model content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!