Analyzing Redis' Single‑Threaded Model and Event Loop from Source Code

This article examines Redis's single‑threaded architecture by walking through its source code, detailing the main function initialization steps, the event‑loop implementation, and how file and time events are processed, while also noting the promotional messages interspersed throughout.

Top Architect
Top Architect
Top Architect
Analyzing Redis' Single‑Threaded Model and Event Loop from Source Code

Redis is a single‑threaded in‑memory database whose speed comes from processing all operations in one thread. This article analyzes the Redis source (version 2.9.11) to illustrate how the single‑threaded model is implemented.

Brief Overview

The author introduces Redis as a C‑based project, mentions an annotated source repository, and sets the stage for a deeper dive into the code.

Main Function Entry

The main function in redis.c performs several key tasks:

Check for Sentinel mode startup.

Initialize server configuration (LRU time, RDB conditions, commands, client buffers, slow‑log, etc.).

Parse and load configuration files and command‑line options.

Initialize the server data structures, create time events, open TCP ports, set up the I/O multiplexor, Lua scripting, slow‑log, and the only multithreaded component (background persistence).

Load data from AOF or RDB.

Validate maxmemory settings.

Start the event processor, indicating successful server startup.

Stop the event loop and return.

int main(int argc, char **argv) {
    struct timeval tv;
    /* Initialize libraries and server configuration */
    // 初始化库
    #ifdef INIT_SETPROCTITLE_REPLACEMENT
    spt_init(argc, argv);
    #endif
    setlocale(LC_COLLATE, "");
    zmalloc_enable_thread_safeness();
    zmalloc_set_oom_handler(redisOutOfMemoryHandler);
    srand(time(NULL)^getpid());
    gettimeofday(&tv, NULL);
    dictSetHashFunctionSeed(tv.tv_sec^tv.tv_usec^getpid());
    // 检查服务器是否以 Sentinel 模式启动
    server.sentinel_mode = checkForSentinelMode(argc,argv);
    // 初始化服务器
    initServerConfig();
    // ... (rest of the initialization and event loop code) ...
    return 0;
}

Event Processor

After initialization, Redis enters the aeMain function, which runs an infinite loop processing events. The loop first executes any pre‑sleep callbacks, then calls aeProcessEvents to handle file and time events.

void aeMain(aeEventLoop *eventLoop) {
    eventLoop->stop = 0;
    while (!eventLoop->stop) {
        if (eventLoop->beforesleep != NULL)
            eventLoop->beforesleep(eventLoop);
        aeProcessEvents(eventLoop, AE_ALL_EVENTS);
    }
}

The aeProcessEvents function determines the appropriate timeout based on the nearest timer, then polls for file events, dispatches readable and writable callbacks, and finally processes any due time events.

Summary

From a source‑code perspective, Redis maintains a single‑threaded model: after the main function starts, no additional threads are created. File events correspond to socket reads/writes handled via an I/O multiplexor, and the entire event handling is driven by a continuous while loop.

Note: The article also contains promotional messages encouraging readers to join a WeChat group, claim interview question packs, and view related links.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backend Developmentredissource-code-analysisC languageevent loopSingle‑threaded
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.