Why can redis single thread be so fast?

Time:2021-8-25

1. Redis is a single threaded program!!!


Because all its data are stored in memory, all operations are memory level operations. Because redis is a single thread, redis instructions should be used with caution. Instructions with time complexity of O (n) must be used with caution, otherwise redis will get stuck.


2. Since redis is a single thread, how can it handle so many concurrent client requests?


  • Non blocking IO (noblocking I / O)

When the user thread initiates a read operation, it does not need to wait, but gets a result immediately. If the result is an error, it knows that the data is not ready, so it can send the read operation again. Once the data in the kernel is ready and receives the request from the user thread again, it immediately copies the data to the user thread and returns.
Therefore, in fact, in the non blocking IO model, the user thread needs to constantly ask whether the kernel data is ready, that is, the non blocking IO will not hand over the CPU, but will always occupy the CPU.

  • Event polling (multiplexing I / O multiplexing hands up mode)

In the multiplexed IO model, a thread will constantly poll the status of multiple sockets. The actual IO read-write operation will be called only when the socket really has a read-write event. In the multiplex IO model, only one thread is needed to manage multiple sockets. The system does not need to establish new processes or threads, nor maintain these threads and processes. Moreover, IO resources are used only when there are socket read-write events. Therefore, it greatly reduces the resource occupation.