为什么redis 是单线程模式呢?
官方是这么说的
## Redis is single threaded. How can I exploit multiple CPU / cores?
It's not very frequent that CPU becomes your bottleneck with Redis, as usually Redis is either memory or network bound. For instance, using pipelining Redis running on an average Linux system can deliver even 1 million requests per second, so if your application mainly uses O(N) or O(log(N)) commands, it is hardly going to use too much CPU.
However, to maximize CPU usage you can start multiple instances of Redis in the same box and treat them as different servers. At some point a single box may not be enough anyway, so if you want to use multiple CPUs you can start thinking of some way to shard earlier.
You can find more information about using multiple Redis instances in the [Partitioning page](https://redis.io/topics/partitioning).
However with Redis 4.0 we started to make Redis more threaded. For now this is limited to deleting objects in the background, and to blocking commands implemented via Redis modules. For the next releases, the plan is to make Redis more and more threaded.
意为,cpu 不会造成瓶颈,所以没必要使用多核。
那么为什么cpu不是瓶颈呢?
1.最先想到的就是内存,完全是基于内存的,当然持久化是题外话,一般是通过fork一个子进程去操作的。
2.数据结构上,大多数操作都是O(1)。
3.单线程,避免了加锁和频繁的上下文切换
4.i/o复用
void aeMain(aeEventLoop *eventLoop) {
eventLoop->stop = 0;
while (!eventLoop->stop) {
// 如果有需要在事件处理前执行的函数,那么运行它
if (eventLoop->beforesleep != NULL)
eventLoop->beforesleep(eventLoop);
// 开始处理事件
aeProcessEvents(eventLoop, AE_ALL_EVENTS);
}
}
简单来讲,复杂的我也不会讲。
就是典型的tcp链接,加上不同平台的i/o复用,linux用epoll。